Ansible loops
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:
Recent Comments
No comments
Leave a Comment
We will be happy to hear what you think about this post