(1)playbook基本用法:安装apache
playbook语法:注意空格,不能是tab键
#vim nginx.yml
- hosts: 192.168.1.31
tasks:
- name: Install Apache Package
yum: name=httpd state=latest
- name: Copy Apache Conf
copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/httpd.conf
notify: Restart Apache Service
- name: Start Apache
service: name=httpd state=started enabled=yes
handlers:
- name: Restart Apache Service
service: name=httpd state=restarted
说明:
目标主机是:192.168.1.31
安装httpd,把本地/tmp/httpd.conf文件拷贝到目标主机指定目录
启动httpd和开机启动
handlers:处理方式(重启httpd)
notify动作:当copy文件改变的时候,会触发处理方式handlers(重启httpd)
ansible-playbook nginx.yml --syntax-check //检测语法
ansible-playbook nginx.yml //执行
(2)role用法
1)主配置文件:定义主机的角色是nginx
#vim /root/roles/site.yml
- hosts: 192.168.1.32
roles:
- nginx
2)定义nginx的首页文件,这个目录可以放置一些不改变的文件
#vim /root/roles/nginx/files/index.html
Hello World
3)定义任务文件: yum安装epel源和nginx包,复制配置文件和首页文件(不需要加目录结构),当配置文件修改触发动作,服务启动和开机启动
# cat /root/roles/nginx/tasks/main.yml
- name: Install Nginx Package
yum: name={{ item }} state=latest
with_items:
- epel-release
- nginx
- name: Copy nginx.conf Template
template: src=nginx.conf.j2 dest=/etc/nginx/nginx.conf
notify: restart nginx
- name: Copy index.html
copy: src=index.html dest=/usr/share/nginx/html/index.html
- name: make sure nginx service running
service: name=nginx state=started enabled=yes
4)定义默认配置文件:注意这里配置文件使用了变量,注意这里其中一个变量 ansible_processor_cores 是使用setup模块收集自动引用的
# grep "{{" /root/roles/nginx/templates/nginx.conf.j2
worker_processes {{ ansible_processor_cores }};
worker_connections {{ worker_connections }};
5)定义变量:引用配置文件中的变量
# cat nginx/vars/main.yml
worker_connections: 10240
6)定义动作:当模板中的配置文件变动会触发重启nginx动作
# cat /root/roles/nginx/handlers/main.yml
- name: restart nginx
service: name=nginx state=restarted
ansible-playbook site.yml --syntax-check //检测语法
ansible-playbook site.yml //执行