Working with lists and dictionary variables in ansible

From Notes_Wiki

Home > CentOS > CentOS 6.x > System administration tools > ansible > Ansible tips and tricks > Ansible lookup plugins > Working with lists and dictionary variables in ansible

For working with lists and dictionary variables in ansible, refer to following example:

---
- name: Test playbook for checking dictionaries
  hosts: all
  remote_user: root

  vars:
    dict1: {hostname: "test", ip: "127.0.0.1"}
    list_dict2:
      - {hostname: "test2", ip: "127.0.0.2"}
      - {hostname: "test3", ip: "127.0.0.3"}
    list_dict3: 
      - {hostname: "test4", ip: [ "127.0.0.4", "127.0.0.5", "127.0.0.6" ] }

  tasks:
    - name: Accessing direct dictionary
      debug: msg=" hostname is {{dict1.hostname}} and ip is {{dict1.ip}}"

    - name: Accessing list of dictionary
      debug: msg=" hostname is {{item.hostname}} and ip is {{item.ip}}"
      with_items: list_dict2

    - name: Accessing dictionary with one of the value as lists
      template: src=host.j2 dest=/root/message.txt
      with_items: list_dict3

The example refers to jinja2 file name 'host.j2" with contents:

{% for host1 in list_dict3 %}
   Current host is {{host1.hostname}}
   The ips for this host are:
   {% for ip1 in host1.ip %}
   - {{ip1}}
   {% endfor %} 
{% endfor %}


The output message file on destination would get created with contents:

   Current host is test4
   The ips for this host are:
      - 127.0.0.4
      - 127.0.0.5
      - 127.0.0.6
    


Home > CentOS > CentOS 6.x > System administration tools > ansible > Ansible tips and tricks > Ansible lookup plugins > Working with lists and dictionary variables in ansible