5.ansible roles
roles
将变量、任务、模板等文件单独配置在yaml文件中,在main.yaml中用include字段来指定要执行的yaml文件
官方建议目录/etc/ansible/roles
调用roles的yml文件与roles目录平级
roles的目录结构
roles目录中创建角色名 比如叫做project,其子目录包含如下:
files/ # 存放copy或script模块等调用的文件
templates/ # 存放模板文件
tasks/ # 书写单个任务
handlers/ # 指定触发动作
vars/ # 定义变量
meta/
default/
例子:配置nginx
创建目录
mkdir -p /root/ansible-playbook/roles/nginx/{tasks,templates}
cd /root/ansible-playbook/roles/nginx/tasks
编写tasks任务
vim group.yml
---
- name: create group
group: name=nginx
vim user.yml
---
- name: create user
user: name=nginx group=nginx system=yes shell=/sbin/nologin
vim install.yml
---
- name: install nginx
yum: name=nginx
vim template.yml
---
- name: copy config file
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
vim start.yml
---
- name: start nginx
service: name=nginx state=start enabled=yes
指定执行顺序
vim main.yml
- include: group.yml
- include: user.yml
- include: install.yml
- include: template.yml
- include: start.yml
编写template模板文件
cd /root/ansible-playbook/roles/nginx/templates
cp /usr/local/nginx/conf/nginx.conf ./nginx.conf.j2
vim nginx.conf.j2
...
worker_processes {{ ansible_processor_vcpus*3 }}; # 修改进程数为cpu核心数的3倍
...
编写调用role的playbook文件
cd /root/ansible-playbook
vim nginx_role.yml
- hosts: host10
remote_user: root
roles:
- nginx
例子:配置httpd 只创建用户,拷贝文件
mkdir -p /root/ansible-playbook/roles/httpd/{tasks,files}
cd /root/ansible-playbook/roles/httpd/tasks
vim user.yml
---
- name: create user
user: name=apache
vim copyfile.yml
---
- name: copy config file
copy: src=httpd.conf dest=/etc/httpd/httpd.conf # src文件在files目录中指定
vim main.yml
- include: user.yml
- include: copyfile.yml
cd /root/ansible-playbook/roles/httpd/files
cp /etc/httpd/httpd.conf ./
cd /root/ansible-playbook/
vim httpd_role.yml
---
- hosts: host10
remote_user: root
roles:
- httpd
指定多个roles
---
- hosts: host10
remote_user: root
roles:
- httpd
- nginx
一个角色调用另一个角色的任务
vim /root/ansible-playbook/roles/nginx/tasks/main.yml
- include: group.yml
- include: user.yml
- include: install.yml
- include: template.yml
- include: start.yml
- include: roles/httpd/tasks/copyfile.yml # 注意拷贝文件的路径,要求src路径为绝对路径
role打标签
vim some_role.yml
---
- hosts: host10
remote_user: root
roles:
- { role: httpd, tags: ['web', 'httpd'],when: ansible_distribution_major_version == "7" } # 也可以指定when语句
- { role: nginx, tags: ['web', 'nginx'] }
执行
ansible-playbook -t web some_role.yml # -t 指定要执行的标签
标签:httpd,roles,nginx,ansible,ansible05,include,yml
From: https://www.cnblogs.com/lixunblogs/p/18167312