Working with Ansible {Part-8}

Working with Ansible {Part-8}

In this blog, we will see the Relational Operators in the Ansible playbook.

Let's say I have below YAML code where I have defined a variable with value=9 and I am comparing it in when condition and getting below results

---
- name: working with relational operators 
  hosts: Node-1
  vars: 
    myval: 9
  tasks:
       - name: relational operators
         command: echo "myval value is {{ myval }}"
         when: myval <= 10

Now the above condition is true i.e. 9<=10 it'll print the data after execution as below.

Now, say I change the condition which does not suffice the condition then see what will happen.

---
- name: working with relational operators 
  hosts: Node-1
  vars: 
    myval: 11
  tasks:
       - name: relational operators
         command: echo "myval value is {{ myval }}"
         when: myval <= 10

Now, let's execute the above and see in the output it should say the conditional result was False.

Likewise, whenever we want to verify the existence of any variable in our playbook we can use the defined condition below

---
- name: working with relational operators 
  hosts: Node-1
  vars: 
    myval: 11
  tasks:
       - name: relational operators
         command: echo "myval value is {{ myval }}"
         when: myval <= 10
       - name: defined 
         command: echo "my environment is defined {{ env }}"
         when: env is defined

In the above-defined condition, we have defined that unless we won't define the environment it will not run the playbook it'll skip the playbook.

Now, we can define the env variable on the runtime with the below command.

ansible-playbook playbookname.yaml -e "env=envname" -v

Hence, we saw how we can use the Relational Operators in the Ansible playbook. You may find the Code in the below repo.

Did you find this article valuable?

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