Hello,
This is the problem I’m trying to solve:
I have an inventory consisting of a bunch of groups, all with a bunch of hosts. I want to run a list of tasks locally, but which depends on the inventory host list. More specifically I’m generating locally placed certs with openssl for each of the hosts in the inventory. This is where I’m currently at:
the playbook:
`
- hosts: 127.0.0.1
connection: local
roles:
- tls
`
an example task from tls/tasks/main.yml:
`
- name: create server certificate key
command: openssl genrsa
-out {{ cert_path }}/{{ naming_prefix }}{{ item }}/server-key.{{ naming_prefix }}{{ item }}.pem 4096
with_inventory_hostnames: all:!127.0.0.1
`
Where cert_path and naming_prefix are extra variables passed to the playbook.
This works! BUT… I only want to perform these tasks when a certificate doesn’t already exists. I would like some way to run the stat module for each hosts certificate file and only run their respective certification generating tasks if the file doesn’t exist.
I hope that made sense
Thanks for your time and input!
I would revers this and run
- hosts: all
vars:
certfile: “{{ cert_path }}/{{ naming_prefix }}{{ inventory_hostname }}/server-key.{{ naming_prefix }}{{ inventory_hostname }}.pem”
have a task check for cert existence
- stat: path={{ certfile}}
register: stat_cert
and then just delegate the generation command to localhost:
- command: openssl genrsa -out {{certfile}} 4096
delegate_to: localhost
when: not stat_cert.stat.exists
Thanks for the help Brian!
So, in my first iteration of the solution I actually had i reversed and used hosts: all. Instead of delegating I ran local_action. The problem I would run into then was that ansible tried to use SSH locally and fail during the SETUP-phase. This is because the hosts are not available during the time of this task execution (they are VMs that get spun up later).
I tried googling how to prevent ansible from assuming there would be SSH locally, but to no avail. A solution to that problem would most likely serve as a solution to this one as well.
Cheers,
Jens
connection: local should prevent ansible from trying to connect to remote hosts via ssh.
Maybe you also need gather_facts: no.
Thanks everyone for the help! I’ll try your suggestions out as soon as I get an opportunity.
Cheers,
Jens