Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ansible templating with dictionaries unable to find the key

I’m using following code:

    - name: Find cert file
      ansible.builtin.find:
        file_type: file
        paths: /etc/ilmaotus
        patterns: '*_X509.pem'
      register: cert_files

    - name: Set cert based facts
      ansible.builtin.set_fact:
        device_id: "{{ cert_files['files'] | first | attr('path') }}"

I’m getting the file names (should always be only one file) from the targeted host and early part works fine including getting the first item on the list but I don’t seem to be able to get the value for ‘path’ attribute in the dictionary. I can access ‘device_id’ in my j2 file but cannot get the value as part set_fact-play.

When I print the devide_id just with first is looks like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'path': '/etc/myservice/mypem_X509.pem', 'mode': '0544', 'isdir': False, 'is....

so there should be the key in dictionary. I’m doing something wrong but not sure what.

>Solution :

Unlike most ways of accessing attributes in Jinja, attr() only retrieves object attributes, not collection items. Both . and [] will work, with different precedence in each case:

        device_id: "{{ (cert_files['files'] | first).path }}"
        device_id: "{{ (cert_files['files'] | first)['path'] }}"

You can also use map() to retrieve the item before using first():

        device_id: "{{ cert_files['files'] | map(attribute='path') | first }}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading