目录
一.playbook介绍
playbook 是 ansible 用于配置,部署,和管理被控节点的剧本。通过 playbook 的详细描述,执行其中的一系列 tasks ,可以让远端主机达到预期的状态。playbook 就像 Ansible 控制器给被控节点列出的的一系列 to-do-list ,而被控节点必须要完成。也可以这么理解,playbook 字面意思,即剧本,现实中由演员按照剧本表演,在 Ansible 中,这次由计算机进行表演,由计算机安装,部署应用,提供对外服务,以及组织计算机处理各种各样的事情
二.playbook格式
1.书写格式
举例 安装挂载nfs服务
[root@tdm1 playbook]# cat nfs.yml
---
- hosts: web
remote_user: root
tasks:
- name: install nfs
yum: name=rpcbind,nfs-utils state=present
- name: nfs configure file
copy: src=./export.j2 dest=/etc/exports backup=yes
- name: mkdir share dir
file: path=/data state=directory owner=nfsnobody group=nfsnobody
- name: start rpcbind
service: name=rpcbind state=started enabled=yes
- name: start nfs
service: name=nfs state=started enabled=yes
- name: mount local
mount: src=47.93.98.117:/data path=/mnt fstype=nfs state=mounted
文件名称应该以.yml结尾
使用ansible-playbook运行playbook文件,得到以下输出信息,输出内容为json格式,由不同颜色组成
绿色代表执行成功,系统保持原样
黄色代表系统状态发生改变
红色代表失败,显示错误输出
执行有三个步骤:
2.notify介绍
Ansible提供了notify指令和handlers功能。如果在某个task中定义了notify指令,当Ansible在监控到该任务 changed=1时,会触发该notify指令所定义的handler,然后去执行handler。所谓handler,其实就是task,无论在写法上还是作用上它和task都没有区别,唯一的区别在于hander是被触发而被动执行的,不像普通task一样会按流程正常执行
测试1
当检测到nfs的配置发生变化是,会重启nfs服务和重新挂载
notify和handlers中定义的名称必须一致
[root@tdm1 playbook]# cat nfs.yml
---
- hosts: web
tasks:
- name: install nfs
yum: name=rpcbind,nfs-utils state=present
- name: nfs configure file
copy: src=./export.j2 dest=/etc/exports backup=yes
notify: restart nfs #当export.j2文件发生变化,就会由handlers来执行。
- name: mkdir share dir
file: path=/data state=directory owner=nfsnobody group=nfsnobody
- name: start rpcbind
service: name=rpcbind state=started enabled=yes
- name: start nfs
service: name=nfs state=started enabled=yes
- name: mount local
mount: src=47.93.98.117:/data path=/mnt fstype=nfs state=mounted
notify: client remount
handlers:
- name: restart nfs #名称和notify中的一致
service: name=nfs state=restarted
- name: client remount
service: src=47.93.98.117:/data path=/mnt fstype=nfs state=remounted
#修改export.j2的内容
vim export.j2
/data 47.93.98.0/24(rw,all_squash)
执行剧本,观察
#查看文件是否更改
[root@tdm1 playbook]# ansible web -m shell -a 'cat /etc/exports'
47.93.98.117 | CHANGED | rc=0 >>
/data 47.93.98.0/24(rw,all_squash)
测试2
修改nginx的文件,检测到文件被修改,handlers下面任务会被执行
[root@tdm1 playbook]# cat nginx.yml
---
- hosts: web
tasks:
- name: install nginx
yum:
name: nginx
state: installed
- name: index file
copy:
content: "This is ansible test"
dest: /usr/share/nginx/html/index.html
- name: nginx configure file
copy:
src: ./nginx.conf.j2
dest: /etc/nginx/conf.d/default.conf
backup: yes
notify: restart nginx #文件被修改,重启nginx
- name: start nginx
service:
name: nginx
state: started
handlers:
- name: restart nginx #重启nginx
service:
name: nginx
state: restarted
#修改nginx.conf.j2的文件
vim nginx.conf.j2
server {
listen 81;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
参考:https://blog.csdn.net/u012562943/category_6298590.html