Ansible Looping Programming with Playbooks

Example 1 - Using loop and with_items

# EXAMPLE 
- name: Install common software requirements
  apt: pkg={{ item }} state=installed
  with_items:
     - git
     - htop
     - vim
    

Example 2 - Using loop and with_items

# EXAMPLE 
tasks:
    - command: echo {{ item }}
      loop: [ 0, 2, 4, 6, 8, 10 ]
      when: item > 5
    

Example 3 - Using loop and with_items

# EXAMPLE    
- command: echo {{ item }}
  loop: "{{ mylist|default([]) }}"
  when: item > 5
    

Example 4 - Using loop and with_items

# EXAMPLE 
- command: echo {{ item.key }}
  loop: "{{ query('dict', mydict|default({})) }}"
  when: item.value > 5
    

Example 5 - Using loop and with_items

# EXAMPLE 
- name: Remove users �Chuck� and �Craig� from the system.
  user:
    name: "{{ item }}"
    state: absent
    remove: yes
  with_items:
    - chuck
    - craig
# EXAMPLE
---
# this is a trivial example of how to do a nested loop.

- hosts: all
  tasks:
    - shell: echo "nested test a={{ item[0] }} b={{ item[1] }} c={{ item[2] }}"
      with_nested:
        - [ 'red', 'blue', 'green' ]
        - [ 1, 2, 3 ]
        - [ 'up', 'down', 'strange']
		
# EXAMPLE
# you can reference a raw variable name without putting it in {{ brackets }}
- hosts: all
  vars:
    listvar1:
    - 'a'
    - 'b'
    - 'c'
  tasks:
    - shell: echo "nested test a={{ item[0] }} b={{ item[1] }}"
      with_nested:
        - listvar1
        - [ 1, 2, 3 ]


Avail Rajesh Kumar as trainer at 50% Discount
Puppet Online Training
Puppet Classroom TrainingEnroll Now