How to create and use variables with_nested loop in ansible playbook?

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 vars_with_nested_loop.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
  vars:
    users_with_items:
      - name: "alice"
        personal_directories:
          - "bob"
          - "carol"
          - "dan"
      - name: "bob"
        personal_directories:
          - "alice"
          - "carol"
          - "dan"
        common_directories:
          - ".ssh"
          - "loops"

  tasks:
    - name: create common users directories using with_nested loop
      file:
        dest: "/home/{{item.0.name}}/{{ item.1 }}"
        state: directory

      with_nested:
        - "{{ users_with_items }}"
        - "{{ common_directories }}"
# three dots indicate the end of a YAML document
...

Become a Subscriber
Get the Notify on latest Videos in your Desktop and Mobile . We never spam!
Popular Videos
Read next

Mastering Ansible Variables: A Comprehensive Guide for Beginners

Ansible Variables: Simplifying Your Automation Tasks Table of Contents Introduction to Ansible Variables Ansible is a powerful automation tool used for configuration management, application deployment, and task automation. One of the key components that makes it so flexible is Ansible variables. Understanding how to effectively use variables can drastically simplify your automation scripts and make […]

May 10, 2025