Bootstrap FreeKB - Ansible - Getting Started with Dictionaries (key value pairs)
Ansible - Getting Started with Dictionaries (key value pairs)

Updated:   |  Ansible articles

Here is how you can create an empty dictionary using vars, a dictionary that contain no keys and no values.

---
- hosts: localhost
  vars:
    employees: {}
  tasks:
  - debug: 
      var: employees
...

 

Which should return the following.

ok: [localhost] => {
    "employees": {}
}

 

Here is how you could create a dictionary that contains some key value pairs.

---
- hosts: localhost
  vars:
    employees:
      - { name: 'john.doe', department: 'it' }
      - { name: 'jane.doe', department: 'sales' }
      - { name: 'jack.doe', department: 'hr' }
  tasks:
  - debug:
      var: employees
...

 

Or like this.

---
- hosts: localhost
  vars:
    employees:
      - name: john.doe
        department: it
      - name: jane.doe
        department: sales
      - name: jack.doe
        department: hr
  tasks:
  - debug: 
      var: employees
...

 

Which should return the following.

ok: [localhost] => {
    "employees": [
        {
            "department": "it", 
            "name": "john.doe"
        }, 
        {
            "department": "sales", 
            "name": "jane.doe"
        }, 
        {
            "department": "hr", 
            "name": "jack.doe"
        }
    ]
}

 

And here is how you could create a dictionary that contains a list of values.

---
- hosts: localhost
  tasks:
  - set_fact:
      dictionary: { list: [ 'foo', 'bar' ] }

  - debug:
      var: dictionary
...

 


Looping through a dictionary 

The following can be used to loop through each item in a dictionary.

In this example, the loop parameter is used to loop over the food dictionary.

---
- hosts: localhost
  vars:
    employees:
      - { name: 'john.doe', department: 'it' }
      - { name: 'jane.doe', department: 'sales' }
      - { name: 'jack.doe', department: 'hr' }
  tasks:
  - name: loop through the dictionary
    debug:
      msg: "{{ item.key }} = {{ item.value }}"
    with_dict: "{{ employees }}"
...

 

Which should return the following.

ok: [localhost] => (item={u'key': u'department', u'value': u'it'}) => {
    "msg": "department = it"
}
ok: [localhost] => (item={u'key': u'name', u'value': u'john.doe'}) => {
    "msg": "name = john.doe"
}
ok: [localhost] => (item={u'key': u'department', u'value': u'sales'}) => {
    "msg": "department = sales"
}
ok: [localhost] => (item={u'key': u'name', u'value': u'jane.doe'}) => {
    "msg": "name = jane.doe"
}
ok: [localhost] => (item={u'key': u'department', u'value': u'hr'}) => {
    "msg": "department = hr"
}
ok: [localhost] => (item={u'key': u'name', u'value': u'jack.doe'}) => {
    "msg": "name = jack.doe"
}

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e4c0be in the box below so that we can be sure you are a human.