自1.2版本引入的新特性,用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等,只需要在playbook中使用include指令即可。
简单来讲,roles就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中,并通过include调用它们的一种机制,类似于其他开发语言中的项目。
每个角色,以特定的层级目录结构进行组织
Roles各目录作用
示例:建立nginx roles,在多台主机上部署nginx
cd /app/ansible/role
mkdir nginx{tesks,templates,hanslers} -pv
cd tasks/
touch insatll.yml config.yml service.yml file.yml user.yml
vim main.yml
- include: user.yml
- include: insatll.yml
- include: config.yml
- include: file.yml
- include: service.yml
ll /app/ansible/role/nginx/templates/
nginx7.conf.j2
nginx8.conf.j2
vim tasks/install.yml
- name: install
yum: name=nginx
vim tasks/config.yml
- name: config file
template: src=nginx7.conf.j2 dest=/etc/nginx/nginx.conf
when: ansible_distribution_major_version=="7"
notify: restrat
- name: config file
template: src=nginx8.conf.j2 dest=/etc/nginx/nginx.conf
when: ansible_distribution_major_version=="8"
notify: restrat
vim tasks/file.yml
- name: file.html
copy: src=roles/httpd/files/index.html dest=/usr/share/nginx/html/
vim tasks/service.yml
- name: start service
service: name=nginx state=started enabled=yes
vim handlers/main.yml
- name: restrat
service: name=nginx state=restarted
vim roles/role_nginx.yml
---
#test role
- hosts: appsrvs
roles:
- role: nginx
ansible-playbook role_nginx.yml
vim main.yml
---
- hosts: websrvs
remote_user: root
roles:
- mysql
- memcached
- nginx
传递变量给角色
vim main.yml
---
- hosts:
remote_user:
roles:
- mysql
- { role: nginx, username: nginx }
# 不同的角色调用不同的变量,键role用于指定角色名称,后续的k/v用于传递变量给角色
例2
---
- hosts: webservers
roles:
- common
- { role: foo_app_instance, dir: '/web/htdocs/a.com', port: 8080 }
还可基于条件测试实现角色调用
roles:
- { role: nginx, username: nginx, when: ansible_distribution_major_version == '7' }
参考:
《ansible权威指南》
https://www.bilibili.com/video/BV1HZ4y1p7Bf?from=search&seid=13215158654353304589&spm_id_from=333.337.0.0
有道云笔记