I'm trying to distribute certificates to its corresponding hosts (I'll just give the example for the private key task):
- name: create certificate private key
community.crypto.openssl_privatekey:
path: "/root/client/{{ item }}.key"
type: Ed25519
backup: yes
return_content: yes
register: privatekey
loop: "{{ ansible_play_hosts_all }}"
when: "'prometheus1' in inventory_hostname"
I can invoke the variable for other hosts like this:
{{ hostvars['prometheus1']['privatekey']['results'][0]['privatekey'] }}
The index points to a certain key, so 0 is going to be the first host (prometheus1
), 1 the second one and so on.
I suppose templating would be the way to go, but I simply don't know how to compose the template.
I think ansible_play_hosts_all
is key to the solution, in that its index corresponds to the private key's index, so for instance:
ansible_play_hosts_all[2]
--> hostvars['prometheus1']['privatekey']['results'][2]['privatekey']
But the logic would be:
for i in index of ansible_play_hosts_all
add the hostvars['prometheus1']['privatekey']['results'][i]['privatekey']
if ansible_play_hosts_all[i] in inventory_hostname
Something to that effect, I suppose :) Any help is greatly appreciated.
Update
Maybe something slightly more accurate:
{% for i in ansible_play_hosts_all|length) %}
{{ hostvars['prometheus1']['privatekey']['results'][i]['privatekey'] }}
{% endfor %}
and to it add the condition:
{% if ansible_play_hosts_all[i] in inventory_hostname %}