Trying to use lookup('file', ...) with an array of items.

Hi All,

I am trying to load up a list of users and their keys. As in something like:

authorized_key: user={{item.name}} key=“{{ lookup(‘file’, {{item.file}}) }}”
with_items:

  • { name: “{{bill_username}}”, file: ‘bill_ras.pub’ }
  • { name: “{{bob_username}}”, file: ‘bob_rsa.pub’ }
  • { name: “{{kim_username}}”, file: ‘kim_rsa.pub’ }

This fails with:

failed: [deploytest] => (item={‘name’: u’billsmith’, ‘file’: ‘bill_rsa.pub’}) => {“failed”: true, “item”: {“file”: “bill_rsa.pub”, “name”: “billsmith”}}
msg: Failed to lookup user {{item.name}}: 'getpwnam(): name not found: {{item.name}}

I have tried various permutations with quoting and can’t seem to get this to work. This looks like a related thread…

https://groups.google.com/forum/#!msg/ansible-project/mNy0xhZ8sew/wKA4qKOM15sJ

It is a strange error message that I don’t quite get. In any case how do I set a range of users and keys without repeating the line a number of times?

This is on ansible 1.6.3.

Thanks,
Jason

This is a known issue when using with_items and complex data structures, where the data structure is flattened to a string.

Do this instead:

  • authorized_key:
    user: “{{item[‘name’]}}”
    key: “{{ lookup(‘file’, {{item.file}}) }}”
    with_items:

  • { name: “{{bill_username}}”, file: ‘bill_ras.pub’ }

  • { name: “{{bob_username}}”, file: ‘bob_rsa.pub’ }

  • { name: “{{kim_username}}”, file: ‘kim_rsa.pub’ }

This preserves the data structure and works as intended.

Thanks! That is what I needed to know!

Cheers,
Jason

Too many mustaches!!! You just use a bare item.file inside the looks.

Brian Coca

Thanks! Yes, good point and that worked (having the bare item whereas with the extra moustaches it didn’t work.)

So in the end the following works:

  • authorized_key:
    user: “{{item[‘name’]}}”
    key: “{{ lookup(‘file’, item.file }}”
    with_items:

  • { name: “{{bill_username}}”, file: ‘bill_ras.pub’ }

  • { name: “{{bob_username}}”, file: ‘bob_rsa.pub’ }

  • { name: “{{kim_username}}”, file: ‘kim_rsa.pub’ }

Thanks all!

Cheers,
Jason

It’s also imaginary syntax.

authorized_key: user={{item.name}} key=“{{ lookup(‘file’, item.file) }}”

Do not nest “{{” inside “{{”, it’s not a thing :slight_smile: