Ansible role入门

Ansible role入门

2017-04-20
Ansible

ansible role #

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

1roles/
2  xxrole/
3    defaults/
4    handlers/
5    meta/
6    tasks/
7    vars/

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

 1production                # inventory file for production servers
 2staging                   # inventory file for staging environment
 3
 4group_vars/
 5   group1                 # here we assign variables to particular groups
 6   group2                 # ""
 7host_vars/
 8   hostname1              # if systems need specific variables, put them here
 9   hostname2              # ""
10
11library/                  # if any custom modules, put them here (optional)
12filter_plugins/           # if any custom filter plugins, put them here (optional)
13
14site.yml                  # master playbook
15webservers.yml            # playbook for webserver tier
16dbservers.yml             # playbook for dbserver tier
17
18roles/
19    common/               # this hierarchy represents a "role"
20        tasks/            #
21            main.yml      #  <-- tasks file can include smaller files if warranted
22        handlers/         #
23            main.yml      #  <-- handlers file
24        templates/        #  <-- files for use with the template resource
25            ntp.conf.j2   #  <------- templates end in .j2
26        files/            #
27            bar.txt       #  <-- files for use with the copy resource
28            foo.sh        #  <-- script files for use with the script resource
29        vars/             #
30            main.yml      #  <-- variables associated with this role
31        defaults/         #
32            main.yml      #  <-- default lower priority variables for this role
33        meta/             #
34            main.yml      #  <-- role dependencies
35        library/          # roles can also include custom modules
36        lookup_plugins/   # or other types of plugins, like lookup in this case
37
38    webtier/              # same kind of structure as "common" was above, done for the webtier role
39    monitoring/           # ""
40    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传递变量:

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

参考 #

© 2024 青蛙小白