user1174838
user1174838

Reputation: 323

How do I work with Ansible list of dicts?

I'm so confused with this. If I have a file containing:

users:
- name: jconnor
  first: john
  last: connor
  uid: 3003
- name: sconnor
  first: sarah
  last: connor
  uid: 3001

How do I get the details of each user? With this simple playbook:

- name: create users
  hosts: localhost
  gather_facts: false
  tasks:
  - name: Include vars
    include_vars:
      file: user_list.yml
      name: users
  - name: debug
    debug:
      msg: "{{ item }}"
    with_dict: "{{ users }}"

I get the following which I can't use:

ok: [localhost] => (item={'value': [{u'last': u'connor', u'uid': 3003, u'name': u'jconnor', u'first': u'john'}, {u'last': u'connor', u'uid': 3001, u'name': u'sconnor', u'first': u'sarah'}], 'key': u'users'}) => {
    "msg": {
        "key": "users",
        "value": [
            {
                "first": "john",
                "last": "connor",
                "name": "jconnor",
                "uid": 3003
            },
            {
                "first": "sarah",
                "last": "connor",
                "name": "sconnor",
                "uid": 3001
            }
        ]
    }
}

I want to create user accounts with this but I simply don't understand how to use this structure.

Note that this is part of a larger structure and I can't change it.

Thanks

Upvotes: 0

Views: 74

Answers (1)

seshadri_c
seshadri_c

Reputation: 7340

Since the users variable is a list of dicts, you should loop with loop or with_items. Then we can access the key of each dict with item.key. E.g.: item.name, item.uid, etc.

Note that you are importing the variables from the file with the name users. So this variable now contains the users hash of that file. If you skip name: users in include_var, then you can directly access the users dict while looping.

  tasks:
  - include_vars:
      file: user_list.yml
      name: users
  - debug:
        msg: "Username is {{ item.name }}, full name is {{ item.first }} {{ item.last }}, userid is {{ item.uid }}"
    with_items: "{{ users.users }}"

This outputs message (showing 1 item):

ok: [localhost] => (item={u'last': u'connor', u'uid': 3003, u'name': u'jconnor', u'first': u'john'}) => {
    "msg": "Username is jconnor, full name is john connor, userid is 3003"
}

Upvotes: 1

Related Questions