简介
roles是ansible,playbooks的目录的组织结构,将代码或文件进行模块化,成为roles的文件目录组织结构。 易读,代码可冲哟美好,层次清晰
目录机构
mkdir roles/nginx/{files,handlers,tasks,templates,vars} -p
touch roles/site.yaml roles/nginx/{handlers,tasks,vars}/main.yaml
echo 1234 > roles/nginx/files/index.html
yum -y install nginx && cap /etc/nginx/nginx.conf roles/nginx/templates/nginx.conf.j2
编写任务
vim roles/nginx/tasks/main.yaml
---
- name: install epel-release package
yum: name=epel-release state=latest
- name: install nginx package
yum: name=nginx state=latest
- name: copy index.html
copy: src=index.html dest=/usr/share/nginx/html/index.html
- name: copy nginx.conf template
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: restart nginx
- name: make sure nginx service running
service: name=nginx state=started enabled=yes
template,相当于copy,会替换原来的
准备配置文件
vim roles/nginx/templates/nginx.conf.j2
编写变量
vim roles/nginx/vars/main.yaml
worker_connections: 1024
上面的worker_connections 调用此处的变量
编写处理程序
vim roles/nginx/handlers/main.yaml
---
- name: restart nginx
service: name=nginx state=restarted
编写剧本
vim roles/site.yaml
- hosts: sever2
roles:
- nginx
实施
cd roles
ansible-playbook site.yaml --syntax-check
ansible-playbook site.yaml