当我们需要判断某些条件,符合才能执行tasks任务时,用when
如:当目标主机IP为192.168.1.111 的时候才输出
vim ip.yml
---
- hosts: web
tasks:
- name:
debug: msg={{ansible_default_ipv4.address}}
when: ansible_default_ipv4.address == '192.168.1.111'
可看到跳出了112 ,在111这个机器执行输出了对应IP
image.png
例2:安装http软件,当目标主机为centos系统yum时安装httpd, 为ubantu系统apt时候安装apache,安装完启动服务
vim install_http.yml
---
- hosts: web
tasks:
- name: apache version - yum
yum: name=httpd state=present
when: ansible_pkg_mgr == 'yum'
notify: restart hpptd service
- name: apache version - apt
apt: name=apache2 state=present update_cache=yes
when: ansible_pkg_mgr == 'apt'
notify: restart apache service
handlers:
- name: restart hpptd service
service: name=httpd state=restarted
- name: restart apache service
service: name=apache2 state=restarted
例3:当系统为Centos6和Debian 7才能重启 (条件可用and 和or )
image.png
循环 (loop关键字,{{item}}获取遍历value)
- hosts: web
gather_facts: no
tasks:
- name: xunhuan
debug: msg="{{item}}"
loop:
- one
- two
- three
结果为:
image.png
循环字典:
格式:
with_items:
- {key1: 'value1', key2: 'value2'}
- {key1: 'value1', key2: 'value2'}
. . .
例如:在远程主机批量创建用户,名字为字典中的列表名称。
[root@server-www xunhuan]# cat item.yml
- hosts: web
gather_facts: no
tasks:
- name: zidian
#debug: msg="{{item.groups}}"
user: name={{item.name}} groups={{item.groups}} state=present
with_items:
- {name: 'zhangsan', groups: 'nginx'}
- {name: 'lisi', groups: 'nginx'}
tags: add
结果为
image.png
image.png
网友评论