Ansible Roles
一、Ansible Roles基本概述
1.Ansible Roles介绍
roles不管是Ansible还是saltstack,我在写一键部署的时候,都不可能把所有的步骤全部写入到一个'剧本'文件当中,我们肯定需要把不同的工作模块,拆分开来,解耦,那么说到解耦,我们就需要用到roles官方推荐,因为roles的目录结构层次更加清晰。
例如:我们之前推荐大家写一个lnmp.yml里面写所有基础优化的项目,其实把所有东西摞进去也是很鸡肋的,不如我们把这些功能全部拆分开,谁需要使用,就调用即可。
建议:每个roles最好只使用一个tasks这样方便我们去调用,能够很好的做到解耦。(SOA)
# 运维复杂的场景:建议使用 roles,代码复用度高
2.目录结构
production # inventory file for production servers
staging # inventory file for staging environment
group_vars/
group1.yml # here we assign variables to particular groups
group2.yml
host_vars/
hostname1.yml # here we assign variables to particular systems
hostname2.yml
library/ # if any custom modules, put them here (optional)
module_utils/ # if any custom module_utils to support 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/
nginx/ # 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.创建roles目录
1.手动创建 (不推荐)
[root@m01 ~]# mkdir /project
[root@m01 ~]# cd /project/
[root@m01 project]# mkdir roles
[root@m01 project]# touch site.yml
[root@m01 project]# ll
total 0
drwxr-xr-x 2 root root 6 May 9 16:47 roles
-rw-r--r-- 1 root root 0 May 9 16:47 site.yml
[root@m01 roles]# mkdir {mariadb,php,nfs-client,nfs-server,nginx}
[root@m01 roles]# mkdir nginx/{tasks,files,templates,vars,handlers,meta} -p
[root@m01 roles]# tree nginx
nginx
├── files
├── handlers
├── meta
├── tasks
├── templates
└── vars
6 directories, 0 files
# 注释
nginx/ #项目名称
├── defaults #低优先级变量
├── files #存放文件
├── handlers #触发器文件
├── meta #依赖关系文件
├── tasks #工作任务文件
├── templates #jinja2模板文件
├── tests #测试文件
└── vars #变量文件
Roles各目录作用
- files/ :存放由copy或script模块等调用的文件
- templates/&