Ansible: Playbook running task based on condition

Ansible_Logo

At times one may want to run certain tasks or command only if certain conditions are met.

For example add a user called “RedhatUser01” only if the managed node is a Redhat node. Similarly add a user named “centosUser01” only on CentOS managed nodes.

Below is a playbook that uses conditions to achieve the above mentioned example.

[root@centos9vm ~]# cat shijuplaybook.yml

==== ===
– – –
– name: shiju sample playbook
    hosts: 192.168.48.129
    vars:
        theRHUser:
            RedhatUser01
        theCOSuser:
            centosUser01

    tasks:
        – name: Add a user in Redhat
            ansible.builtin.user:
                name: “{{ theRHUser }}”
                state:┬ápresent
            when: ansible_facts[‘distribution’] == “Redhat”

        – name: Add a user in CentOS node
            ansible.builtin.user:
                name: “{{ theCOSuser }}”
                state:┬ápresent
            when: ansible_facts[‘distribution’] == “CentOS”

        – name: Check distribution name
            ansible.builtin.debug:
                var: ansible_facts[‘distribution’]

=== ====

Now let us run the playbook

[root@centos9vm ~]# ansible-navigator run -m stdout shijuplaybook.yml

===== ==

PLAY [shiju sample playbook] ***************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.48.129]

TASK [Add a user in Redhat] ****************************************************
skipping: [192.168.48.129]

TASK [Add a user in CentOS node] ***********************************************
ok: [192.168.48.129]

TASK [Check distribution name] *************************************************
ok: [192.168.48.129] => {
“ansible_facts[‘distribution’]”: “CentOS”
}

PLAY RECAP *********************************************************************
192.168.48.129 : ok=3 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0

===== =====

[root@centos9vm ~]# ssh 192.168.48.129 ‘tail -n 3 /etc/passwd’

=======
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
user800:x:1010:1010::/home/user800:/bin/bash
centosUser01:x:1011:1011::/home/centosUser01:/bin/bash

========