Loops in Ansible Playbook and Dictionaries.
Although, there are almost 14 loops in the Ansible Playbooks. But, we will see a few loops and try to understand them. We have a for loop in Python but in Ansible we have with_items and the item is like the iterator of the loop and this is fixed in the Ansible playbook.
Let's write the YAML to execute the with_item loop
---
- name: working with loops
hosts: Node-1
tasks:
- name: printing data
command: echo "my element value is {{ item }}"
with_items: [10,20,30,40,50]
Execute the above playbook
Likewise, we do have with_sequence loop in the Ansible Playbook and it is used to generate the sequence. Let's take a look at the YAML file below.
---
- name: working with loops
hosts: Node-1
tasks:
- name: printing data
command: echo "my element value is {{ item }}"
with_items: [10,20,30,40,50]
- name: working with with_sequence
command: echo "my element value is {{ item }}"
with_sequence: start=1 end=5
Now, Execute the playbook
Hence, we can conclude how we can use the loops in the playbook.
Now, let's see How we use Dictionaries in the Ansible playbook.
We will understand the concept of Dictionaries using the setup module. To gather the facts we use the setup module and we use the below command
ansible -m setup -a "filter=ansible_default_ipv4" yourserverornodename
Now, let's write and YAML and try to use the with_dict:
The main usage of with_dict is to parse the dictionary data.
---
- name: working with loops
hosts: Node-1
tasks:
- name: printing data
command: echo "my element value is {{ item }}"
with_items: [10,20,30,40,50]
- name: working with with_sequence
command: echo "my element value is {{ item }}"
with_sequence: start=1 end=5
- name: working with with_dict
command: echo "my key is {{ item.key }} && my value is {{ item.value }}"
with_dict: "{{
ansible_default_ipv4 }}"
Now, run the playbook and we will see it is printing the whole dictionary key-value pair.
Therefore, we saw how we can use loops in the Ansible Playbook. Kindly check out my GitHub repo for the whole code.