Search code examples
ansiblejinja2

I can't get Selectaddr to display attributes from my dict


We're running ansible 2.9.27 on Red Hat Linux 7.9. In my playbook, I have the following code:

- name: DEBUG THIS THING1
  debug:
    msg: "FOUND HOME: {{ found_service_accounts['svclinux']['home'] }}"

- name: DEBUG THIS THING2
  debug:
    msg: "FOUND: {{ found_service_accounts['svclinux']['home'] | selectattr('path', 'defined') | list }}"

The output looks like this:

TASK [service_accounts : DEBUG THIS THING1] ***************************************************************************
ok: [myhost.example.com] => {
    "msg": "FOUND HOME: {u'owner': u'svclinux', u'path': u'/home/svclinux', u'group': u'svc-linux', u'permissions': u'755'}"
}

TASK [service_accounts : DEBUG THIS THING2] ***************************************************************************
ok: [myhost.example.com] => {
    "msg": "FOUND: []"
}

I can't figure out why Ansible isn't printing the path attribute of my home. It just prints the empty list. Can you see my obvious mistake?

Thanks.

Note: found_service_accounts is a dict that was set as follows. The homes.results...stdout_lines[n] are simple strings gleaned from a shell command:

- name: set found_service_accounts
  set_fact:
    found_service_accounts: |
      {% set j2fsa = { } %}
        {%- for user in service_account_names -%}
          {% set _ = j2fsa.update(
             { user : { 'home' : { 'path' : homes.results[loop.index0].stdout_lines[0],
                                   'owner' : homes.results[loop.index0].stdout_lines[1],
                                   'group' : homes.results[loop.index0].stdout_lines[2],
                                   'permissions' : homes.results[loop.index0].stdout_lines[3]
                                 },
                         'ssh_subdirectory' : {
                                   'owner' : ssh_subdir.results[loop.index0].stdout_lines[0],
                                   'permissions' : ssh_subdir.results[loop.index0].stdout_lines[1]
                                 }
                      }
             })
          %}
        {%- endfor %}
      {{ j2fsa }}

and service_account_names is just a list like: [ 'svclinux' ]


Solution

  • found_service_accounts['svclinux']['home'] is a dictionary, not a list. You should directly access the value of path:

    - name: DEBUG THIS THING2
      debug:
        msg: "FOUND: {{ found_service_accounts['svclinux']['home']['path'] }}"
    

    What happens in your original attempt is that iterating over a dictionary returns just the dictionary keys (["owner", "path", "group", "permissions"]), and strings do not have an attribute named path.