Ansible role入门

2017-04-20 阅读: Ansible

ansible role

当一个配置管理的任务十分复杂时,playbook文件会十分庞大,这这种情况下将不利于扩展和复用。 这个时候可以使用ansible role将这个复杂的playbook模块化。Ansible role实际上是对playbook进行了逻辑上的划分,分成不同目录。 ansible已经规定好了目录的结构:

roles/
  xxrole/
    defaults/
    handlers/
    meta/
    tasks/
    vars/

有了ansible role之后,来看一下一个ansible配置管理项目的目录结构:

production                # inventory file for production servers
staging                   # inventory file for staging environment

group_vars/
   group1                 # here we assign variables to particular groups
   group2                 # ""
host_vars/
   hostname1              # if systems need specific variables, put them here
   hostname2              # ""

library/                  # if any custom modules, put them here (optional)
filter_plugins/           # if any custom filter plugins, put them here (optional)

site.yml                  # master playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

当playbook需要引用某个role时:

  • tasks/main.yml中的task都会被自动添加到该playbook中
  • handlers/main.yml中的handler都会被自动添加到该playbook中
  • vars/main.yml中的所有变量都会被自动添加到该playbook中
  • meta/main.yml中的所有role依赖关系都会被自动添加到该playbook中
  • defaults/main.yml中是一些默认变量值,如果在其他地方没有指定该变量的值时,才会用到默认变量
  • task中的copy模块和script模块会自动从files目录中寻找文件
  • task中的template模块会自动从templates目录中加载模块文件
  • 通过include包含文件会自动从tasks目录中加载文件

在meta/main.yml中定义该role依赖于其他的role,同时可以向依赖的role传递变量:

---
dependencies:
  - { role: common, some_parameter: 3 }
  - { role: apache, apache_port: 80 }
  - { role: postgres, dbname: blarg, other_parameter: 12 }

参考

标题:Ansible role入门
本文链接:https://blog.frognew.com/2017/04/ansible-role.html
转载请注明出处。

目录