条件语句When

类似于编程语言的if

When语句

有时候用户有可能需满足特定条件才执行某一个特定的步骤。在某一个特定版本的系统上装包,或者只在磁盘空间满了的文件系统上执行清理操作一样。这些操作在Ansible上,使用when语句都非常简单.

主机为Debian Linux立刻关机

  1. tasks:
  2. - name: "shutdown Debian flavored systems"
  3. command: /sbin/shutdown -t now
  4. when: ansible_os_family == "Debian"

根据action的执行结果,来决定接下来执行的action。

  1. tasks:
  2. - command: /bin/false
  3. register: result
  4. ignore_errors: True
  5. - command: /bin/something
  6. when: result|failed
  7. - command: /bin/something_else
  8. when: result|success
  9. - command: /bin/still/something_else
  10. when: result|skipped

远程中的系统变量facts变量作为when的条件,用“|int”还可以转换返回值的类型:

  1. ---
  2. - hosts: web
  3. tasks:
  4. - debug: msg="only on Red Hat 7, derivatives, and later"
  5. when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6

条件表达式

  1. vars:
  2. epic: true

基本款

  1. tasks:
  2. - shell: echo "This certainly is epic!"
  3. when: epic

否定款:

  1. tasks:
  2. - shell: echo "This certainly isn't epic!"
  3. when: not epic

变量定义款

  1. tasks:
  2. - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
  3. when: foo is defined
  4. - fail: msg="Bailing out. this play requires 'bar'"
  5. when: bar is not defined

数值表达款

  1. tasks:
  2. - command: echo {{ item }}
  3. with_items: [ 0, 2, 4, 6, 8, 10 ]
  4. when: item > 5

与Include一起用

  1. - include: tasks/sometasks.yml
  2. when: "'reticulating splines' in output"

与Role一起用

  1. - hosts: webservers
  2. roles:
  3. - { role: debian_stock_config, when: ansible_os_family == 'Debian' }