How to create basic nested loop in ansible playbook?
In Ansible, you can create nested loops using the with_nested
keyword. Here’s an example of how to create a basic nested loop in an Ansible playbook:
Example:1
- name: Example of a nested loop
hosts: all
vars:
outer_list:
- item1
- item2
inner_list:
- subitem1
- subitem2
tasks:
- name: Print outer and inner loop values
debug:
msg: "{{ outer_item }} {{ inner_item }}"
with_nested:
- "{{ outer_list }}"
- "{{ inner_list }}"
In this example, we define two lists – outer_list
and inner_list
. We then use the with_nested
keyword to create a nested loop over these two lists. The outer_item
and inner_item
variables are defined within the loop and are used in the debug
module to print out the current values of both variables.
When you run this playbook, Ansible will iterate over each item in the outer_list
, and for each item in the outer_list
, it will iterate over each item in the inner_list
. This will result in a total of four iterations, with the debug
module printing out the following output:
ok: [localhost] => (item=['item1', 'subitem1']) => {
"msg": "item1 subitem1"
}
ok: [localhost] => (item=['item1', 'subitem2']) => {
"msg": "item1 subitem2"
}
ok: [localhost] => (item=['item2', 'subitem1']) => {
"msg": "item2 subitem1"
}
ok: [localhost] => (item=['item2', 'subitem2']) => {
"msg": "item2 subitem2"
}
Example:2
Create a ansible config file as ansible.cfg file in your project directory:
[defaults]
inventory = hosts
Create a hosts file as hosts in the project directory
[webservers]
ansnode1 ansible_ssh_host=192.168.56.202 ansible_python_interpreter=/usr/bin/python
ansnode2 ansible_ssh_host=192.168.56.203 ansible_python_interpreter=/usr/bin/python
[webservers:vars]
ansible_port=22
http_port=8080
[dbservers]
ansnode3 ansible_ssh_host=192.168.56.204 ansible_python_interpreter=/usr/bin/python
ansnode4 ansible_ssh_host=192.168.56.205 ansible_python_interpreter=/usr/bin/python
[dev:children]
webservers
dbservers
Create a file named called as with_nest_loop_playbook.yml in your project directory
---
# YAML documents begin with the document separator ---
# the minus in YAML this indicates a list item. The playbook contains a list
# of plays, with each play being a dictionary
- hosts: all
tasks:
- name: add multiple users
user:
name: "{{ item[0] }}"
state: present
with_nested:
- [ 'alice', 'bob' ]
- [ 'clientdb', 'employeedb', 'providerdb' ]
# three dots indicate the end of a YAML document
...