ANSIBLE- LOOPS & CONDITION USAGE
Every programming language have loops & condition to control the flow of code execution.
Loop is used to iterate through the code based on logic and application/program requirement.
Whereas, condition is used to control the program execution.
LOOPS:
Ansible offers the loop
, with_<lookup>
, and until
keywords to execute a task multiple times. Examples of commonly-used loops include changing ownership on several files and/or directories with the file module, creating multiple users with the user module, and repeating a polling step until a certain result is reached.
Note: loop
is added in Ansible 2.5. It is not yet a full replacement for with_<lookup>
, but we recommend it for most use cases.
STANDARD LOOPS:
- Iterating over simple loop
- name: Add users from given lists.
ansible.builtin.user:
name: "{{ item }}"
state: present
groups: "devops"
loop:
- user1
- user2
- user3
We define the list in a variables file, or in the ‘vars’ section of your play, then refer to the name of the list in the task.
loop: "{{ somelist }}"
- Iterating over lists of hashes.
If you have a list of hashes, you can reference subkeys in a loop. For example:
- name: Add several users
ansible.builtin.user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
loop:
- { name: 'user1', groups: 'devops' }
- { name: 'user2', groups: 'aiops' }
- Iterating over dictionary.
To loop over a dict, use the dict2items:
- name: Using dict2items
ansible.builtin.debug:
msg: "{{ item.key }} - {{ item.value }}"
loop: "{{ tag_data | dict2items }}"
vars:
tag_data:
Environment: dev
Application: payment
- Registering variables with a loop.
- name: Register loop output as a variable
ansible.builtin.shell: "echo {{ item }}"
loop:
- "one"
- "two"
register: echo
WITH_ITEMS:
with_items is replaced by loop and the flatten filter.
---
- hosts: node
tasks:
- name: Here we are providing a simple list.
debug:
msg: "The given car vehicles company name is: {{ item }}"
with_items:
- bmw
- mercedes
- tata
- toyota
- mazada
CONDITIONS: