How to create a dict using Ansible inventory

Viewed 186

I need bit of help in creating a dict of host names and ip address out of a Ansible inventory.

Here is my inventory:

web:
  hosts:
    Webserver1:
      ansible_host: "10.10.10.10"
      Environment: "Dev"
      location: DC1
    Webserver2:
      ansible_host: "10.10.10.11"
      Environment: "Dev"
      location: DC1
    Webserver3:
      ansible_host: "10.11.10.10"
      Environment: "Dev"
      location: DC2

and I want to run a playbook on my local Ansible control machine to create a dict as follows

host_dict={Webserver1:10.10.10.10, Webserver2:10.10.10.11, Webserver3:10.11.10.10}

Any help is greatly appreciated. Thanks

1 Answers

Here's a simple demo:

- name: a play that runs entirely on the ansible host
  hosts: localhost
  vars:
   host_dict:
    Webserver1: 10.10.10.10
    Webserver2: 10.10.10.11

  tasks:
    - debug: msg="{{ host_dict }}"

In YAML, if it does not start with a - then it is a dictionary key, otherwise it's a list. See more advanced examples here: https://docs.ansible.com/ansible/latest/plugins/lookup/dict.html

Related