Ansible Jinja2 join dict nected values

For a certain configuration file I needed all my SSH users to be listed as p.puk,j.snot,s.sjors  etc from the following dict.

USERS:
  - name: "Pietje Puk"
    account: p.puk
  - name: "Jan Snot"
    account: j.snot
  - name: "Sjaakie Sjors"
    account: s.sjors

But whenever I ran the following task:

- template:
    src: templates/file
    dest: /tmp/file

With the following template:

{{ USERS.account | join(',') }}

it would give me:

AnsibleUndefinedVariable: ‘list object’ has no attribute ‘account’

But having found:

https://stackoverflow.com/questions/42698232/complex-string-concatenation-in-jinja-ansible-template#

I put the following in my template:

{{ SSH_USERS | json_query('[*].account') | join(',') }}

It gave me the following in /tmp/file.

p.puk,j.snot,s.sjors

The StackOverflow article covered something else so I wasn’t able to thank Crypto for his/her contribution but hopefully by creating this small post I can reach out to this person to say that this little fix saved my evening!

Guess I’d overlooked http://docs.ansible.com/ansible/latest/playbooks_filters.html#json-query-filter as I was of the assumption that my dict was YAML structured and therefor such a thing as json-query-filter wouldn’t work.

But then again:

Source: https://nl.pinterest.com/pin/301881981246842503/

 

Join the Conversation

1 Comment

  1. Great article. You saved my day!
    I have been searching for this solution for a couple of hours.
    Apparently, the Ansible documentation seems to be too abstract or difficult.

Leave a comment

Your email address will not be published. Required fields are marked *