Ansible Tutorial | How to Use Loop in Playbook | Ansible With_item

Ansible Tutorial | How to Use Loop in Playbook | Ansible With_item

ansible loop, ansible loop, ansible playbook tutorial, ansible tutorial for beginners, ansible tasks, ansible, ansible tutorial, ansible ad hoc commands, ansible modules, ansible example, ansible facts, ansible linux, ansible best practices, ansible modules, ansible playbook, ansible playbook examples, ansible best practices, ansible roles, ansible-playbook
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

ansible loop, ansible loop, ansible playbook tutorial, ansible tutorial for beginners, ansible tasks, ansible, ansible tutorial, ansible ad hoc commands, ansible modules, ansible example, ansible facts, ansible linux, ansible best practices, ansible modules, ansible playbook, ansible playbook examples, ansible best practices, ansible roles, ansible-playbook


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

  1. with_items: "{{ items }}"
  2. with_list:
       - one
  3. with_indexed_items: "{{ items }}"
  4. with_flattened: "{{ items }}"
  5. with_together:
       - "{{ list_one }}"
       - "{{ list_two }}"
  6. with_dict: "{{ dictionary }}"
  7. with_sequence: start=0 end=4 stride=2 format=testuser%02x
  8. with_subelements:
       - "{{ users }}"
       - mysql.hosts
  9. with_nested:
       - "{{ list_one }}"
       - "{{ list_two }}"


Thanks

End of this ansble 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
Previous
Next Post »