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

Is there a loopable way to only execute a task when a file exists in Ansible?

I’m looking for an easy way to add public keys to the authorized_keys file, if the key for the user is present in a specific directory. Right now it throws an error if the public key doesn’t exist.

I want to create users on systems and push their public keys. For that, I am using the authorized_key module:

- name: Add pubkeys
  ansible.posix.authorized_key:
    user: "{{ item.username }}"
    state: present
    key: "{{ lookup('file', '~/ap/ansible/sonderfiles/{{ item.username }}_pubkey.pub') }}"
  loop: "{{ userlist }}"

I found threads mentioning the module stat but I cant figure out a way to iterate through a list of files and use the results in a when condition in the authorized_key module.

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

>Solution :

This can be achieve with a condition and an is file test.

This said, there is a little trick to it, like in maths, some operators are taking precedence on others, and in this case, the is operator of the test is taking precedent on the concatenation operator ~.
So, the trick is to put the concatenated path in parenthesis:

- name: Add pubkeys
  ansible.posix.authorized_key:
    user: "{{ item.username }}"
    state: present
    key: >-
      {{ lookup(
           'file', 
           '~/ap/ansible/sonderfiles/' ~ item.username ~ '_pubkey.pub'
      ) }}
  loop: "{{ userlist }}"
  when: "('~/ap/ansible/sonderfiles/' ~ item.username ~ '_pubkey.pub') is file"
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