五:Ansible Roles
A: Ansible Roles directory structure
1. The official recommended best practices for directory structure defined way
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
module_utils/ # roles can also include custom module_utils
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/ # ""
2. the Roles to create a directory structure using galaxy
[root@m01 ~]# cd /etc/ansible/roles/
[root@m01 roles]# tree wordpress/
nfs/ #项目名称
├── defaults #低优先级变量
├── files #存放文件
├── handlers #触发器文件
├── meta #依赖关系文件
├── tasks #工作任务文件
├── templates #jinja2模板文件
├── tests #测试文件
└── vars #变量文件
Note: You only need these directories, ansible's roles will automatically identify which of main.yml
Two: Ansible Roles Dependencies
roles
It allows you to automatically introduced into other roles in the use of roles. role-dependent roles in the directory meta / main.yml file relational storage.
For example: push wordpress and unzip, prerequisites, must be installed nginx and php, the service up and running, to run wordpress pages, then we can define nginx and php-dependent roles in the roles of wordpress
[root@m01 roles]# vim /etc/ansible/roles/wordpress/meta/main.yml
dependencies:
- { role: nginx }
- { role: php }
If you write a main.yml files in the meta directory, Ansible first execution dependencies automatically file meta directory main.yml file, as shown above, will be executed first nginx and php installation.
如果安装wordpress,main.yml里有nginx和php
流程:
1.当你执行worepress的playbook,会先在meta的main.yml里找nginx
2.找到后,会在roles目录里找nginx,再去nginx目录的meta找依赖,如果无,会在tasks目录里找到安装、配置、启动等
3.装完nginx后再同理执行php
4.最后再执行wordpress的tasks
Three: Ansible Roles Create a directory
ansible-galaxy init service name roles
[root@m01 ~]# cd /etc/ansible/roles/
[root@m01 /etc/ansible/roles]# ansible-galaxy init rsync roles
- rsync was created successfully
[root@m01 /etc/ansible/roles]# tree
.
└── rsync
├── defaults
│ └── main.yml
├── files
├── handlers
│ └── main.yml
├── meta
│ └── main.yml
├── README.md
├── tasks
│ └── main.yml
├── templates
├── tests
│ ├── inventory
│ └── test.yml
└── vars
└── main.yml
9 directories, 8 files