How to create basic loop using with inline dictionary items variables in ansible playbook?
In Ansible, you can create a loop using the with_items
keyword and pass an inline dictionary to it. Here’s an example of how to create a basic loop using inline dictionary items variables in an Ansible playbook:
Example:1
- name: Example of a loop with inline dictionary items
hosts: all
vars:
my_dict:
item1: value1
item2: value2
item3: value3
tasks:
- name: Print dictionary items
debug:
msg: "{{ item.key }}={{ item.value }}"
with_items: "{{ my_dict|dict2items }}"
In this example, we define a dictionary called my_dict
with three key-value pairs. We then use the dict2items
filter to convert the dictionary to a list of dictionaries with key
and value
keys. We pass this list to the with_items
keyword to create a loop.
Within the loop, we use the item.key
and item.value
variables to print out the current key-value pair. The debug
module will be called once for each key-value pair in the dictionary, resulting in the following output:
ok: [localhost] => (item={'key': 'item1', 'value': 'value1'}) => {
"msg": "item1=value1"
}
ok: [localhost] => (item={'key': 'item2', 'value': 'value2'}) => {
"msg": "item2=value2"
}
ok: [localhost] => (item={'key': 'item3', 'value': 'value3'}) => {
"msg": "item3=value3"
}
As you can see, the loop iterates over each key-value pair in the dictionary and prints out the key and value for each pair.
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 user_playbook.yml in your project directory
---
# the minus in YAML this indicates a list item. The playbook contains a list
#of plays, with each play being a dictionary
- hosts: webservers
tasks:
- name: add several users
user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
with_items:
{ name: 'testuser1', groups: 'wheel' }
{ name: 'testuser2', groups: 'root' }
# Three dots indicates the end of YAML document
...
# Three