Variables are necessary when you need to store the output of a task and need to access it in some other tasks. They are mostly used when dealing with a conditional statement where you can opt to run the task based on the output of another task. Here I will show some examples of using variable substitution in conditionals.
Ansible when variable equals another value
Following is the simplest example of checking whether the value of a variable. We have created a variable test1 and checking if the value is “Hello World” using the when statement.
Note: We need not use the “{{ }}” in the when statement for the variable. It is by default considered as a variable.
- hosts: all vars: test1: "Hello World" tasks: - name: Ansible when variable equals example debug: msg: "Equals" when: test1 == "Hello World"
Ansible when variable not equals another value
We can also set the reverse, i.e. if the variable is not equal to another value.
- hosts: all vars: test1: "Bye World" tasks: - name: Ansible when variable not equals example debug: msg: "Not Equals" when: test1 != "Hello World"
Ansible when variable contains string
We can also make a conditional statement based on whether the variable contains a particular string. We can use variable.find for checking the contents. In the following example, the task will only run when the variable test1 contains the string “World”.
- hosts: all vars: test1: "Bye World" tasks: - name: Ansible when variable contains string example example debug: msg: "Equals" when: test1.find("World") != -1
If the variable value is registered from a shell command you may have to use stdout.find to check the content.
- hosts: all tasks: - shell: cat /etc/temp.txt register: output - name: Ansible when variable contains string example example debug: msg: "Equals" when: output.stdout.find("World") != -1
Ansible when variable is empty
We can also check if a variable is empty using similar manner.
- hosts: all tasks: - shell: cat /etc/temp.txt register: output - name: Ansible when variable is empty example debug: msg: "empty" when: output.stdout == ""