Descending into subdirs and running commands against files

I have a directory on the intermediate CA server, that holds two subdirs, that are named with the hostnames of my two test workstations. What I’m trying to do is instruct Ansible to descent into each directory and run an openssl command against a host.csr and host.req. This is what I have so far:
First: just to find the csr and req files in the subdirs:

  • name: find all csr
    ansible.builtin.find:
    paths: /mypath
    recurse: yes
    file_type: file
    patterns: “.req" (this whole section repeated for ".csr”
    register: serverCSR (for the next section - serverReq)

  • name: Run registered results in openssl
    ansible.builtin.shell
    cmd: openssl ca -bath {{ serverReq.files }} -extensions server_cert -days 730 -notext -md sha256 -in {{ serverCSR }} -out server.crt

Of course the above isn’t working and I don’t know if you can use registered variables in this way. Also, my preference would be “hostname”.crt to match the directory the *.req and *.csr were in, but I could mv the file in a later play.

Someone suggested using block, but I don’t see how that would be helpful. I’d really wish this could be run on the hosts but security rules prevent me from copying the CA’s private key to the workstations.

If anyone has any ideas I’d appreciate it.

You can use registered variables like that, it is just that it won’t give you what you want, in this case files is a list of dictionaries, what you want is to extract the paths key of each, try:

... {{ serverReq.files|map(attribute='path')|join(' ') }}

That will add all the files, space separated, but I think you want a loop, your command does not look like it is set to handle the list

name: Run registered results in openssl
ansible.builtin.shell:
cmd: openssl ca -bath  -extensions server_cert -days 730 -notext -md sha256 -in {{ item }} -out {{item|basename}}-server.crt
loop:  "{{ serverReq.files|map(attribute='path') }}"
2 Likes