Pages

Thursday, 28 November 2019

EX294: Use conditionals to control play execution

official doc: conditionals

0 Basic idea

A task can be executed conditionally based on the value of a  variable which may be a normal variable, a fact, inventory variable, or register variable.

e.g. a "yum" module may only be run on RedHat systems but not on Debian distributions.

1 Example

1.1 "when" based on ansible_facts

---
- hosts: localhost
  tasks:
        - name: print version of CentOS
          shell: cat /etc/redhat-release
          register: version
          when: ansible_facts['distribution'] == "CentOS"

        - debug: var=version.stdout

1.2 "when" based on register variables

This play will create a user named "user01" if it doesn't exist yet.
(NOTE: Ansible has a user management module to do such a job.)

---
- hosts: vm1
  tasks:
        - name: check if user user01 exists
          shell: 'cat /etc/passwd | grep ^user01'
          ignore_errors: yes
          register: result

        - debug: var=result

        - name: create user01 if not existing
          become: yes
          shell: 'useradd user01'
          when: result.rc != 0

1.3 "when" based on special variables

---
- hosts: all
  tasks:
        - name: only run on inentory_hostname
          command: 'hostname'
          when: inventory_hostname == 'vm1'

1.4 "when" based on normal variables

---
- hosts: all
  vars:
          foo: "bar"
  tasks:
        - command: 'uname'
          when: foo == "bar"

2 Key points

  • the value of "when" is already in JinJa2 context, don't add {{}} any more.
  • different versions of Ansible support different facts. Ansible 2.4 uses "facts" while 2.8 uses "anisble_facts" as the variable name.

No comments:

Post a Comment