标签:when erro conf [] 现在 grep host 选择 shutdown
When 语句有时候用户有可能需要某一个主机越过某一个特定的步骤.这个过程就可以简单的像在某一个特定版本的系统上 少装了一个包一样或者像在一个满了的文件系统上执行清理操作一样. 这些操作在Ansible上,若使用when
语句都异常简单.When语句包含Jinja2表达式 实际上真的很简单:
- name: "yum install lrzsz"
command: /sbin/shutdown -t now
when: ansible_os_family == "Centos"
当系统是centos的时候才会执行上面的command,否则是不会执行的
系统类型: **ansible docker -m setup ** 来查看
root@centos-mysql01:~# ansible docker -m setup|grep os_family
"ansible_os_family": "RedHat",
"ansible_os_family": "Debian",
tasks:
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/something
when: result|failed
- command: /bin/something_else
when: result|success
- command: /bin/still/something_else
when: result|skipped
当第一个command返回值为failed
第二个在返回值为failed的时候执行,否则执行第三个,当为命令为skipped的时候执行第三个
vars:
epic: true
一个条件选择执行也许看起来像这样:
tasks:
- shell: echo "This certainly is epic!"
when: epic
或者像这样:
tasks:
- shell: echo "This certainly isn‘t epic!"
when: not epic
如果一个变量不存在,你可以使用Jinja2的`defined`命令跳过或略过.例如:
tasks:
- shell: echo "I‘ve got ‘{{ foo }}‘ and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires ‘bar‘"
when: bar is not defined
例子:
- hosts: docker
remote_user: root
vars:
epic: true
tasks:
- name: file exeit
shell: ls /home/sh
register: result
ignore_errors: True
- file: path=/home/sh state=directory mode=644
when: result|failed #如果文件不存在 会创建
- file: path=/opt/sh state=directory mode=644
when: epic
#我现在是/opt/sh目录不存在,/home/sh目录存在
root@centos-mysql01:/data/sh# ls /opt/sh
ls: 无法访问/opt/sh: 没有那个文件或目录
root@centos-mysql01:/data/sh# ls /home/sh/
![](http://i2.51cto.com/images/blog/201812/13/ca5b8c55aa74a71eb2d4e7e3c9f08b12.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
剩下的失败和skipped需要自己去实现了
when
和with_items
句对于不同项目将会单独处理tasks:
- command: echo {{ item }}
with_items: [ 0, 2, 4, 6, 8, 10 ]
when: item > 5
- hosts: webservers
roles:
- { role: debian_stock_config, when: ansible_os_family == ‘Debian‘ }
标签:when erro conf [] 现在 grep host 选择 shutdown
原文地址:http://blog.51cto.com/9025736/2329785