Ansible: Automation using conditions

Ansible_Logo

While ansible runs playbook on group of managed nodes which are also present in the Inventory file, we can run tasks on selected nodes based on defined conditions. For example we may want to install the package “httpd” only on Linux nodes in a group pf nodes, though we may want to copy a file to all nodes in a the group. Here conditions are added in the task configurations.

In the below example let us install httpd on nodes with hostname “CentOS9test“, and is a RedHat node. This node is of IP 192.168.48.131 in the inventory group “testGRP“.

[root@centos9vm ~]# ssh 192.168.48.129 ‘dnf list httpd’
Last metadata expiration check: 0:04:10 ago on Tue 23 Apr 2024 03:49:55 PM IST.
Available Packages   httpd.x86_64 2.4.57-8.el9   appstream

[root@centos9vm ~]# ssh 192.168.48.131 ‘dnf list httpd’
Last metadata expiration check: 0:00:09 ago on Tue 23 Apr 2024 03:53:59 PM IST.
Available Packages httpd.x86_64 2.4.57-8.el9 appstream

[root@centos9vm ~]# ansible-navigator inventory –graph testGRP -m stdout

==== ===
@testGRP:
|–192.168.48.129
|–192.168.48.131

====== ===

[root@centos9vm ~]# cat playbook.yml

===== ===
– – –
– name: Playbook to install httpd in a particular host in a group of hosts
    hosts:
        – testGRP

    tasks:
        – name: Display hostnames
            ansible.builtin.debug:
                var: ansible_facts[‘hostname’]

        – name: Install httpd
            ansible.builtin.dnf:
                name: httpd
                state: latest

            when:
                – “ansible_facts[‘hostname’] == ‘CentOS9test'”
                – “ansible_facts[‘distribution’] == ‘RedHat'”
==== ====

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

======= ===

PLAY [Playbook to install httpd in a particular host in a group of hosts] ******

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

TASK [Display hostnames] *******************************************************
ok: [192.168.48.129] => {
“ansible_facts[‘hostname’]”: “centosMYOBvm”
}
ok: [192.168.48.131] => {
“ansible_facts[‘hostname’]”: “CentOS9test”
}

TASK [Install httpd] ***********************************************************
skipping: [192.168.48.129]
changed: [192.168.48.131]

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

====== ====