Working with Ansible {Part-7}

Working with Ansible {Part-7}

Conditions in Ansible Playbook

In Python, we used to define with if-else but in Ansible Playbooks we use when block. Ansible supports arithmetic operators, boolean operators and logical operators. 2 specific operators we use in Ansible are:

  • Defined

  • Undefined

Whenever we feel like we need to gather the facts of a server we use the setup module. We use the command below

ansible - m setup yourserverornodename

Suppose, we want to gather a particular fact i.e. say Ansible_distribution then we will use the below command

ansible -m setup -a "filter=ansible_distribution" yourserverornodename

ansible -m setup -a "filter=ansible_os_family" yourserverornodename

\=> Let's say with the above 2 conditions I want to play with the AND condition in the Ansible playbook then the YAML will look like as below.

---
-  name: working with conditions & operators
   hosts: Node-1
   tasks:
        - name: working with and operator
          command: echo "Hi and condition is working fine"
          when: ansible_distribution == "Amazon" and ansible_os_family == "RedHat"

Now, execute the Ansible playbook and check if the condition is working fine or not.

Let's say we changed the above YAML Code from RedHat to Redhat now, let's see the output

---
-  name: working with conditions & operators
   hosts: Node-1
   tasks:
        - name: working with AND operator
          command: echo "Hi and condition is working fine"
          when: ansible_distribution == "Amazon" and ansible_os_family == "Redhat"

\=> Again, Let's say with the above 2 conditions I want to play with the OR condition in the Ansible playbook then the YAML will look like as below.

Now, deliberately I have changed a fact value from RedHat to Redhat. Now, the playbook should work fine.

---
-  name: working with conditions & operators
   hosts: Node-1
   tasks:
        - name: working with OR operator
          command: echo "Hi OR condition is working fine"
          when: ansible_distribution == "Amazon" or ansible_os_family == "Redhat"

Let's Execute the above playbook and see the results

Hence, we saw how we can use Conditional Operators AND/OR in our Ansible Playbook. You may find he code in the below Repo.

Did you find this article valuable?

Support Chirag Kukreja by becoming a sponsor. Any amount is appreciated!