This is what I came up with for a single host
- name: Check for Let's Encrypt certificate
block:
- name: Set default for variable
set_fact:
use_letsencrypt: false
- name: Get stat for cert file
stat:
path: /etc/letsencrypt/live/{{ hostname }}/cert.pem
register: certificate_file
- name: Set letsencrypt to true if certificate exists
set_fact:
use_letsencrypt: true
when: certificate_file.stat.exists
How can I make this more DRY? Pass it a hostname and it returns a true or false for the variable.
Edit: More info to make it more clear. It already works fine as is.
I want to use the above snippet for more than one host across different playbooks without copy and pasting the snippet every time.
I use the variable use_letsencrypt in different mail and web configuration files and would like to say, I'm busy setting up a config for example.com, do I have a cert for it.
OK. So playing around and reading some more docs, I found the answer.
You can put the above snippet in its own role and just include it every time you need it.
So it acts like a module and you just pass it a var. I can use that snippet multiple times across different playbooks now.
I'm not sure if I understand you right.
I expect that the posted code is just a snipped of complete playbook.
In order to pass the variable just temporarily, you can use -e parameter of ansible-playbook:
So you'd run ansible-playbook like:
And if you don't want to run on all nodes specified in the playbook/role, you can limit it from the command line too. Use parameter -l:
The command would be then:
If you want ansible to get local hosname, it's available via setup module. Tray to use {{ ansible_hostname }} instead of your {{ hostname }}.
If you want to see complete list of variables provided by setup module, just run: