ansible loop |
In ansible 2.5 with_X replace by loop keyword. In this topic we use loop and replace value like fruit name.
With_X ---> loop
With_item ---> loop
cd /etc/ansible
vi loop.yml
- hosts: 127.0.0.1
gather_facts: false
tasks:
- name: echo fruits name -> loop
debug:
msg: This is "{{ item }}"
loop:
- orange
- apple
- greps
- banana
To run playbook
ansible-playbook loop.yml
Example 2 : We define 2 value one is fruit name and second is fruit color. Its something like nested loop.
- hosts: 127.0.0.1
gather_facts: false
tasks:
- name: echo fruits name -> loop
debug:
msg: This is "{{ item.name }} and it color is {{ item.type }}"
loop:
- { name: 'orange', type: 'orange' }
- { name: 'greps', type: 'green' }
- { name: 'banana', type: 'yellow' }
- { name: 'apple', type: 'red' }
ansible-playbook loop.yml
Example 3 : we touch file with define file name and file extension create file
---
- hosts: 127.0.0.1
gather_facts: false
tasks:
- name: Create Directory
file:
state: directory
path: /tmp/linuxtopic/
- name: Create file
file:
state: touch
path: /tmp/linuxtopic/{{ item.0 }}-{{ item.1 }}.{{ item.2 }}
mode: 0755
loop:
- [ 'data1','file1','txt']
- [ 'data2','file2','doc']
- [ 'data3','file3','xls']
ansible-playbook loop.yml
ans
Verify :
ll /tmp/linuxtopic
Before ansible 2.5 - loop with_xxx
with_items: "{{ items }}"
with_list:
- one
with_indexed_items: "{{ items }}"
with_flattened: "{{ items }}"
with_together:
- "{{ list_one }}"
- "{{ list_two }}"
with_dict: "{{ dictionary }}"
with_sequence: start=0 end=4 stride=2 format=testuser%02x
with_subelements:
- "{{ users }}"
- mysql.hosts
with_nested:
- "{{ list_one }}"
- "{{ list_two }}"
Thanks
End of this ansible loop or with_items tutorial, we need your support so i request you to please comment if something missed by me, share and like this post.
www.linuxtopic.com