您的位置:首页 > 其它

ansible playbook 详解

2016-03-17 21:10 411 查看
上篇文章介绍了 ansible 的安装配置及实例:http://msiyuetian.blog.51cto.com/8637744/1748143
下面这篇文章主要介绍 ansible 的 playbook 详解,playbook 就是相当于把模块或函数写入到配置文件里面,然后我们执行该配置文件来达到远程运维自动化的目的。

一、playbook的简单使用
1、创建文件实例

1)编辑配置文件
[root@master ~]# cd /etc/ansible/
[root@master ansible]# vim test.yml //固定后缀为yml,一定要注意空格

---
- hosts: testhost
user: root
tasks:
- name: playbook_test
shell: touch /tmp/playbook.txt
注意:
hosts参数指定了对哪些主机进行参作;
user参数指定了使用什么用户登录远程主机操作;
tasks指定了一个任务,其下面的name参数同样是对任务的描述,在执行过程中会打印出来。
2)执行配置文件
[root@master ansible]# ansible-playbook test.yml



3)远程机查看





2、创建用户实例

1)编辑配置文件
[root@master ansible]# vim create_user.yml

---- name: create_user
hosts: testhost
user: root
gather_facts: false
vars:
- user: "msiyuetian"
tasks:
- name: create user
user: name="` user `"
注意:
name参数对该playbook实现的功能做一个概述,后面执行过程中,会打印 name变量的值 ,可以省略;
gather_facts参数指定了在以下任务部分执行前,是否先执行setup模块获取主机相关信息,这在后面的task会使用到setup获取的信息时用到;
vars参数指定了变量,这里指字一个user变量,其值为test ,需要注意的是,变量值一定要用引号引住;
user提定了调用user模块,name是user模块里的一个参数,而增加的用户名字调用了上面user变量的值。
2)执行配置文件
[root@master ansible]# ansible-playbook create_user.yml



3)远程机查看





二、playbook循环
实例:修改 /tmp/ 目录下的 1.txt 和 2.txt 文件属性
1)新建实验文件
# touch /tmp/{1.txt,2.txt} //在 testhost 组中的所有主机上操作
2)编辑配置文件
[root@master ansible]# vim loop.yml

---
- hosts: testhost
user: root
tasks:
- name: change mode for files
file: path=/tmp/` item ` mode=600 owner=root group=root
with_items:
- 1.txt
- 2.txt
3)执行配置文件

[root@master ansible]# ansible-playbook loop.yml



4)远程查看效果




注意:可看到权限为 600,主和组都为root。

三、playbook条件判断
条件判断一般用于针对不同版本的系统,比如对centos、ubuntu 等系统进行不同的操作命令。
1)编辑配置文件
[root@master ansible]# vim when.yml

---- hosts: testhost
user: root
gather_facts: True
tasks:
- name: use when
shell: touch /tmp/when.txt
when: facter_ipaddress == "192.168.0.110"
注意:只有当参数 facter_ipaddress 为 192.168.0.110 时才在该机器上新建指定文件;意思就是只对 testhost 组中特定的主机进行操作,忽略组内其他的主机。我们可以通过下面命令查看各个参数的值:
[root@master ansible]# ansible testhost -m setup



2)执行配置文件

[root@master ansible]# ansible-playbook when.yml



3)远程查看效果

[root@slaver ~]# ll /tmp/




四、playbook handlers
当我们执行 tasks 后,服务器发生变化之后我们要执行一些操作。比如我们修改了某个服务的配置文件,需要重启下服务。实例如下:
1)编辑配置文件
[root@master ansible]# vim handlers.yml

---
- name: handlers test
hosts: testhost
user: root
tasks:
- name: test copy
copy: src=/etc/passwd dest=/tmp/handlers.txt
notify: test handlers
handlers:
- name: test handlers
shell: echo "msiyuetian.blog.51cto.com" >> /tmp/handlers.txt
说明:只有 copy 模块真正执行后,才会去调用下面的 handlers 相关的操作,追加内容。也就是说如果 src 和 dest 内容是一样的,并不会去执行 handlers 里面的 shell 相关命令。所以这种比较适合配置文件发生更改后,需要重启服务的操作。
2)执行配置文件
[root@master ansible]# ansible-playbook handlers.yml



3)远程查看效果

[root@slaver ~]# cat /tmp/handlers.txt



可查看到 copy 文件成功,同时也执行了 handlers 的相关命令,追加了新的信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  playbook ansible