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
{'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 }}"