44232111 发表于 2017-2-6 11:51:45

ansible-playbook 使用详解

1.playbook参数详解:

1
2
3
4
5
6
7
8
9
10
11
12
hosts:hosts 用于指定要执行指定任务的主机其可以是一个或多个由冒号分隔主机组。
user:root   指定远程主机上执行任务的用户
remote_user:root
vars:变量
tasks:任务
- name:描述
module:options
如:serverice name=httpd state=running
shell:/sbin/setenforce 0
handlers:触发条件
files:文件赋权
template:模板





tags 用于让用户选择运行或略过playbook中的部分代码。ansible具有幂等性因此会自动跳过没有变化的部分即便如此有些代码为测试其确实没有发生变化的时间依然会非常地长。
此时如果确信其没有变化就可以通过tags跳过此些代码片断。

循环:

1
2
3
4
5
6
7
8
9
10
11
循环with_items:
---
- hosts: testhost
user: root
tasks:
   - name: change mod for file
   file: path=/tmp/{{ item }} mode=600 owner=root group=root
   with_items:
       - 1.txt
       - 2.txt
- 3.txt






条件判断使用handlers模块:

1
2
3
4
5
6
7
8
9
10
---
- hosts: testhost
remote_user: root
tasks:
   - name: test copy
   copy: src=/tmp/1.txt dest=/tmp/2.txt
   notify: test handlers   
handlers:
   - name: test handlers
    shell: echo "111111" >> /tmp/2.txt




如果要使用handlers模块,则需要调用notify: test handlers是handlers模块的name,要保持一致。

从ansible主上拷贝1.txt到远程服务器2.txt,只有到copy完成了,才会执行handlers。

条件判断条件when:

1
2
3
4
5
6
7
8
---
- hosts: testhost
remote_user: root
gather_facts: True
tasks:
   - name: use when
   shell: touch /tmp/when.txt
   when: ansible_system_vendor == "IBM"




注意变量要写对,不能写数组,数组的要注意.
cat /tmp/when.yml :





页: [1]
查看完整版本: ansible-playbook 使用详解