Ansible Loop

Ansible Loop
Techiio-author
Written by Nilima PaulJanuary 24, 2022
13 min read
Ansible
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Techiio-author
Nilima Paul

Technology Security Analyst

We will know in this article, what's the Ansible Loop.

About Ansible Loop

Ansible circle is utilized to rehash any errand or a piece of code on numerous occasions in an Ansible playbook. It incorporates the formation of numerous clients utilizing the client module, introducing various bundles utilizing a well-suited or yum module, or changing consents on a few records or envelopes utilizing the document module. There are two watchwords utilized in Ansible to make a circle:

  • loop
  • with_<look_up>

Syntax:

- name: add multiple users
user:
name: “{{ item }}”
state: present
group: “<group_name>”
loop:
- <user_name>
- <user_name>

What's the use Loop Keyword with examples

It is included in Ansible 2.5 anyway it's anything but a full substitution of with_<look_up> however it is prescribed to utilize circle catchphrase to emphasize an errand in the majority of the situations.

Standard Loops

  • Iterating Over a Simple List
  • Iterating Over a List of Hashes
  • Iterating Over a Dictionary

1. Iterating Over a Simple List

We can use a simple list in a loop if we have a list of users, files, etc.

Code:

- name: delete multiple files from a location
file:
path: ‘/home/ansible/{{ item }}’
state: absent
loop:
- file1
- file2

Output:

blogpost

Code Explanation: In the above model, when we run the playbook, it will initially pick "document" as info and supplant the "thing" catchphrase from the way, once file1 is erased it will pick "file2" as information and erase "file2".

loop: “{{ list_of_files}}”

We can even pass the rundown straightforwardly to a boundary for some modules like yum and adept and so forth In some cases passing the rundown to a boundary is superior to utilizing the circle.

2. Iterating Over a List of Hashes

Now and then we have a circumstance like we need to add products clients to various gatherings, not in a solitary gathering. All things considered, we have a rundown of key-esteem sets called hashes. We can emphasize a rundown of hashes involving the circle also.

Code:

- name: add multiple users
user:
name: “{{ item.name }}”
state: present
group: “{{item.groups}}”
loop:
- { name: ‘user1’, groups: ‘SRE’ }
- { name: ‘user2’, groups: ‘dbadmin’ }

Code Explanation: In the above model, we have two clients and we need to add those two clients in various gatherings. So we have referenced the client name just as separa ate gathering and characterized the name involving a key in the errand that is, etc. The above playbook will add 'user1' to the 'SRE' bunch and 'user2' to 'dbadmin'.

3. Iterating Over a Dictionary

We can loop over a dictionary however we have to use dict2items Dict filter to turn a dictionary into a list of items.

Code:

vars:
tag:
Environment: QA
Application: Cart
Another: “{{ doesnotexist | default() }}”
tasks:
- name: create a tag dictionary of non-empty tags to set facts
set_fact:
tags_dict: “{{ (tags_dict|default({{}}))|combine({item.key: item.value})}}”
loop: “{{ tags | dict2items }}”
when: item.value !=””

Code Explanation: In the above model, we have been circling through word reference 'labels' and dict2items will initially change over the word reference into a rundown as beneath:

- key: Environment
value: Cart
- key: Application
value: Cart

Complex Loops

  • Iterating Over Nested Lists
  • Retrying a Task until a Condition Is Met
  • Looping Over Inventory

1. Iterating Over Nested Lists

Assuming we have a rundown that is a piece of another rundown that turns into a settled rundown. We need to utilize Jinja2 articulation to emphasize over-settled records. We should comprehend it with a model assuming we need to add numerous clients to different gatherings. In the beneath model, we have two clients and the two clients must be added to both the gatherings 'sre' and 'dbadmin'.

Code:

- name: add multiple users to multiple groups
user:
name: "{{ item[0] }}"
state: present
group: “{{ item[1] }}”
loop: "{{ ['user5', 'user6'] |product(['sre', ‘dbadmin’])|list }}"

Output:

blogpost

2. Retrying a Task until a Condition is Met

In certain situations, we need to stop the circle once a specific condition is met. We use the 'until' catchphrase to stop a circle as underneath:

Code:

- shell: ls /root | grep “test”
register: result
until: result.rc == 0
retries: 2
delay: 1

Output:

blogpost

blogpost

Code Explanation:

In the above model, the shell module will run until the return code of the shell module doesn't return 0 or the undertaking has been retried twice with a postponement of 1 sec. In the primary preview, the play fizzled because RC is 1 since there is no document or organizer with name test2 in the root envelope however when pursuing the playbook making that organizer in the root envelope, it got passed. It thoroughly relies on the situation. The default esteem is multiple times and 5 seconds for retries and postponements individually.

3. Looping Over Inventory

In the above model, the shell module will run until the return code of the shell module doesn't return 0 or the assignment has been retried twice with a deferral of 1 sec. In the main preview, the play fizzledbecausetRCc is 1 since there is no record or envelope with name test2 in the root organizer however when pursued the playbook making that envelope in the root envelope, it got passed. It absolutely relies on the situation. The default esteem is multiple times and 5 seconds for retries and deferrals individually.

Code:

# to show the hosts defined under webservers group in the inventory
- debug:
msg: "{{ item }}"
loop: "{{ groups['webservers'] }}"
# to show all the hosts in the current play
- debug:
msg: "{{ item }}"
loop: "{{ ansible_play_batch }}"

Output:

blogpost

blogpost

Adding Controls to Loops

  • Limit Loop Output
  • Pause a Loop
  • Track Progress of A Loop

1. Limiting Loop Output

To restrict the result of the Ansible-playbook which is creating a colossal measure of result on the control center, we can utilize 'mark' mandate with 'loop_control'. For instance, we need to make various servers with some standard design and ansible-playbook will yield all subtleties with its name anyway we need to keep our result spotless and just intrigued by the name of the server to be shown as a control center result. Here is another model:

Code:

- name: add multiple users
user:
name: “{{ item.name }}”
state: present
group: “{{item.groups}}”
loop:
- { name: ‘user1’, groups: ‘SRE’ }
- { name: ‘user2’, groups: ‘dbadmin’ }
loop_control:
label: "{{ item.name }}"

Code Explanation: We have a model that is utilized in the clarification of 'Emphasize over a rundown of hashes' aside from added loop_control and you can consider the distinction to be it is just appearance clients name, not the gathering name in the result.

2. Pause a Loop

In certain situations, we possess to give some energy for the principal order to finish before executing the following one. We utilize the 'stop' mandate with loop_control. It resembles involving staying in bed in some programming language like PowerShell.

Code:

- name: pause for 5 secs after each file creation
digital_ocean:
name: "{{ item }}"
state: present
loop:
- file3.txt
- file4.txt
loop_control:
pause: 5

Output:

blogpost

3. Track Progress of A Loop

To inquisitively realize the number of things that have been executed in a circle, we can utilize the 'index_var' mandate with 'loop_control'.For model:

Code:

- name: count the fruits
debug:
msg: "{{ item }} with index {{ my_idx }}"
loop:
- kiwi
- papaya
- pear
loop_control:
index_var: my_id

Output:

blogpost

Conclusion

The circle is accessible after Ansible form 2.5 or higher and it is prescribed to utilize circle anyway it's anything but a full substitution of with_<look>. Punctuation of 'with_<lookup> is as yet substantial. Additionally here and there it is smarter to straightforwardly pass the rundown to a boundary.

Ansible
Ansible Loop
linux
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Nilima Paul
Technology Security Analyst
Techiio-followerTechiio-followerTechiio-follower
201 Blog Posts
0 Discussion Threads
Trending Technologies
15
Software91
DevOps48
Frontend Development24
Backend Development20
Server Administration17
Linux Administration28
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance