Search This Blog

Wednesday, 3 March 2021

Ansible Loop examples

Simple Ansible playbook for demonstrating loop

[osboxes@master ansible-playbooks]$ cat install-packages.yml

---
- name: Install packages
  hosts: all
  become: true
  become_user: root
  tasks:
    - name: Install http and redis packages
      yum:
        name: "{{ item }}"
        state: present
      loop:
        - epel-release
        - redis
        - httpd


[osboxes@master ansible-playbooks]$ ansible-playbook install-packages.yml -i inventory.txt -K
BECOME password:

PLAY [Install packages] *************************************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.182]

TASK [Install http and redis packages] **********************************************************************************************************************
changed: [192.168.1.182] => (item=epel-release)
changed: [192.168.1.182] => (item=redis)
changed: [192.168.1.182] => (item=httpd)

PLAY RECAP **************************************************************************************************************************************************
192.168.1.182              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0


Create a play book for package installation and define the packages under vars section and use it in a loop.

[osboxes@master ansible-playbooks]$ cat install-packages_1.yml
---
- name: Install packages
  hosts: all
  become: true
  become_user: root
  vars:
    required_packages:
      - epel-release
      - redis
      - httpd

  tasks:
    - name: Install http and redis packages
      yum:
        name: "{{ item }}"
        state: present
      loop: "{{ required_packages }}"

[osboxes@master ansible-playbooks]$ ansible-playbook install-packages_1.yml -i inventory.txt -K
BECOME password:

PLAY [Install packages] *************************************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.182]

TASK [Install http and redis packages] **********************************************************************************************************************
ok: [192.168.1.182] => (item=epel-release)
ok: [192.168.1.182] => (item=redis)
changed: [192.168.1.182] => (item=httpd)

PLAY RECAP **************************************************************************************************************************************************
192.168.1.182              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Create a play book for Iterating over a list of hashes 

---
- name: Add multiple users belongs to different groups
  hosts: all
  become: true
  become_user: root
  tasks:
    - name: Add users
      user:
        name: "{{ item.name }}"
        state: present
        groups: "{{ item.groups }}"
      loop:
        - { name: 'user1', groups: 'wheel' }
        - { name: 'user2', groups: 'root' }


[osboxes@master ansible-playbooks]$ ansible-playbook addusers.yml -i inventory.txt

PLAY [Add multiple users belongs to differnt groups] ********************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.182]

TASK [Add users] ********************************************************************************************************************************************
changed: [192.168.1.182] => (item={'name': 'user1', 'groups': 'wheel'})
changed: [192.168.1.182] => (item={'name': 'user2', 'groups': 'root'})

PLAY RECAP **************************************************************************************************************************************************
192.168.1.182              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Playbook for Iterative over a dictionary 

[osboxes@master ansible-playbooks]$ cat dict.yml
---
- name: dict2items
  hosts: all
  become: true
  become_user: root
  tasks:
    - name: dict2items
      debug:
        msg: "{{ item.key }} - {{ item.value }}"
      loop: "{{ tag_data | dict2items }}"
      vars:
        tag_data:
          Environment: dev
          Application: payment


[osboxes@master ansible-playbooks]$ ansible-playbook dict.yml -i inventory.txt --syntax-check

playbook: dict.yml

[osboxes@master ansible-playbooks]$ ansible-playbook dict.yml -i inventory.txt

PLAY [dict2items] *******************************************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.182]

TASK [dict2items] *******************************************************************************************************************************************
ok: [192.168.1.182] => (item={'key': 'Environment', 'value': 'dev'}) => {
    "msg": "Environment - dev"
}
ok: [192.168.1.182] => (item={'key': 'Application', 'value': 'payment'}) => {
    "msg": "Application - payment"
}

PLAY RECAP **************************************************************************************************************************************************
192.168.1.182              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Registering variable with a loop

---
- name: Register loop output as a variable
  hosts: all
  become: true
  become_user: root
  tasks:

    - name: Register loop output
      shell: "echo {{ item }}"
      loop:
        - "one"
        - "two"
      register: echo

    - name: Show register variale echo results
      debug: var=echo

    - name: Fail if return code is not 0
      fail:
        msg: "The command ({{ item.cmd }}) did not have a 0 return code"
      when: item.rc != 0
      loop: "{{ echo.results }}"

    - name: Place the result of the current item in the variable
      shell: echo "{{ item }}"
      loop:
        - one
        - two
      register: echo
      changed_when: echo.stdout != "one"


[osboxes@master ansible-playbooks]$ ansible-playbook register.yml -i inventory.txt

PLAY [Register loop output as a variable] *******************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.182]

TASK [Register loop output] *********************************************************************************************************************************
changed: [192.168.1.182] => (item=one)
changed: [192.168.1.182] => (item=two)

TASK [Fail if return code is not 0] *************************************************************************************************************************
skipping: [192.168.1.182] => (item={'cmd': 'echo one', 'stdout': 'one', 'stderr': '', 'rc': 0, 'start': '2021-03-03 19:30:37.399257', 'end': '2021-03-03 19:30:37.406175', 'delta': '0:00:00.006918', 'changed': True, 'invocation': {'module_args': {'_raw_params': 'echo one', '_uses_shell': True, 'warn': True, 'stdin_add_newline': True, 'strip_empty_ends': True, 'argv': None, 'chdir': None, 'executable': None, 'creates': None, 'removes': None, 'stdin': None}}, 'stdout_lines': ['one'], 'stderr_lines': [], 'failed': False, 'item': 'one', 'ansible_loop_var': 'item'})
skipping: [192.168.1.182] => (item={'cmd': 'echo two', 'stdout': 'two', 'stderr': '', 'rc': 0, 'start': '2021-03-03 19:30:38.668798', 'end': '2021-03-03 19:30:38.676035', 'delta': '0:00:00.007237', 'changed': True, 'invocation': {'module_args': {'_raw_params': 'echo two', '_uses_shell': True, 'warn': True, 'stdin_add_newline': True, 'strip_empty_ends': True, 'argv': None, 'chdir': None, 'executable': None, 'creates': None, 'removes': None, 'stdin': None}}, 'stdout_lines': ['two'], 'stderr_lines': [], 'failed': False, 'item': 'two', 'ansible_loop_var': 'item'})

TASK [Place the result of the current item in the variable] *************************************************************************************************
ok: [192.168.1.182] => (item=one)
changed: [192.168.1.182] => (item=two)

PLAY RECAP **************************************************************************************************************************************************
192.168.1.182              : ok=3    changed=2    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0


Looping over inventory

[osboxes@master ansible-playbooks]$ cat inventory-loops.yml
---
- name:  looping over inventory
  hosts: all
  become: true
  become_user: root
  tasks:
    - name: Show all the hosts in the inventory
      debug:
        msg: "{{ item }}"
      loop: "{{ groups['all'] }}"

    - name: Show all the hosts in the current play
      debug:
        msg: "{{ item }}"
      loop: "{{ ansible_play_batch }}"

    - name: Show all the hosts in the inventory
      debug:
        msg: "{{ item }}"
      loop: "{{ query('inventory_hostnames', 'all') }}"


[osboxes@master ansible-playbooks]$ ansible-playbook inventory-loops.yml -i inventory.txt

PLAY [looping over inventory] *******************************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.182]

TASK [Show all the hosts in the inventory] ******************************************************************************************************************
ok: [192.168.1.182] => (item=192.168.1.182) => {
    "msg": "192.168.1.182"
}

TASK [Show all the hosts in the current play] ***************************************************************************************************************
ok: [192.168.1.182] => (item=192.168.1.182) => {
    "msg": "192.168.1.182"
}

TASK [Show all the hosts in the inventory] ******************************************************************************************************************
ok: [192.168.1.182] => (item=192.168.1.182) => {
    "msg": "192.168.1.182"
}

PLAY RECAP **************************************************************************************************************************************************
192.168.1.182              : ok=4    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0






No comments: