Working with lists and dictionary variables in ansible

From Notes_Wiki
Revision as of 10:47, 21 March 2015 by Saurabh (talk | contribs) (Created page with "<yambe:breadcrumb>Ansible_tips_and_tricks|Ansible tips and tricks</yambe:breadcrumb> =Working with lists and dictionary variables in ansible= For working with lists and dicti...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

<yambe:breadcrumb>Ansible_tips_and_tricks|Ansible tips and tricks</yambe:breadcrumb>

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
    


<yambe:breadcrumb>Ansible_tips_and_tricks|Ansible tips and tricks</yambe:breadcrumb>