Ansible loops

Ansible loop is used to repeat any task or a part of code multiple times in an Ansible-playbook. It includes the creation of multiple users using the user module, installing multiple packages using apt or yum module, or changing permissions on several files or folders using the file module. When creating loops, Ansible provides these two directives: loop and with_*  keyword.

In this example below how to create multiple files in the target server

create a new file called newcreate.yml using your favorite editor

#cat newcreate.yml 

---

- hosts: database

 tasks:

 - name: multiple items - "{{ item }}"

 file:

 state: touch

 path: /home/ansible/{{ item }}

 with_items:

 - file_no_1

 - file_no_2

 - file_no_3

 we have added three files that should be created in that specific path

To run the playbook,

#ansible-playbook newcreate.yml 

PLAY [database] ****************************************************************

TASK [Gathering Facts] *********************************************************

ok: [ansible2.zippyops.com]

TASK [multiple items - "{{ item }}"] *******************************************

changed: [ansible2.zippyops.com] => (item=file_no_1)

changed: [ansible2.zippyops.com] => (item=file_no_2)

changed: [ansible2.zippyops.com] => (item=file_no_3)

PLAY RECAP *********************************************************************

ansible2.zippyops.com : ok=2 changed=1 unreachable=0 failed=0 

All the three files has been create on target server

# ls

Desktop Downloads file_no_2 Music Public variable_was_true

Documents file_no_1 file_no_3 Pictures Templates Videos

Successfully create three files!!!!

The loop keyword was recently added to Ansible 2.5. The loop keyword is usually used to create simple and standard loops that iterate through several items.




Relevant Blogs:

Register in ansible 

Ansible list variable  

Zabbix agent installation and configuration 

Statefulset in kubernetes

Recent Comments

No comments

Leave a Comment