---
- name: Install VIM
hosts: all tasks:
- name:Install VIM via yum
yum: name=vim-enhanced state=installed
when: ansible_os_family =="RedHat"
- name:Install VIM via apt
apt: name=vim state=installed
when: ansible_os_family =="Debian"
- name: Unexpected OS family
debug: msg="OS Family {{ ansible_os_family }} is not supported" fail=yes
when: not ansible_os_family =="RedHat" or ansible_os_family =="Debian"
- hosts: all
user: root
vars:
epic: true
tasks: - shell: echo "This certainly is epic!" when: epic
- shell: echo "This certainly is not epic!"
when: not epic
4、如果变量不存在,则可以通过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
- name: this command prints FAILED when it fails
command: /usr/bin/example-command -x -y -z
register: command_result
failed_when: "'FAILED' in command_result.stderr"我们也可以直接通过fail模块和when条件语句,写成如下:
- name: this command prints FAILED when it fails
command: /usr/bin/example-command -x -y -z
register: command_result
ignore_errors: True
- name: fail the play if the previous command did not succeed
fail: msg="the command failed"
when: "'FAILED' in command_result.stderr"五、changed_when
- shell: /usr/bin/billybass --mode="take me to the river"
register: bass_result
changed_when: "bass_result.rc != 2" #只有该条task执行以后,bass_result.rc的值不为2时,才会返回changed状态
# this will never report 'changed' status
- shell: wall 'beep'
changed_when: False #当changed_when为false时,该条task在执行以后,永远不会返回changed状态