Declare the keystore filename, the dictionary of keytool options, and join the options
keystore: "kafka.server{{ '%02d' % (idx + 1) }}.keystore.jks"
kt_opt_dict:
genkey: ''
keystore: "{{ keystore }}"
validity: 365
storepass: testtest
keypass: testtest
dname: "CN={{ item }}"
storetype: pkcs12
kt_opt: "{{ kt_opt_dict|dict2items|
json_query('[].[key, value]')|
map('join', ' ')|map('trim')|
join(' -') }}"
Iterate the command and generate the keys and create the files
- command:
cmd: "keytool -{{ kt_opt }}"
creates: "{{ keystore }}"
loop: "{{ groups.kafka }}"
loop_control:
index_var: idx
delegate_to: localhost
run_once: true
register: out
shell> ls -1 kafka.server0*
kafka.server01.keystore.jks
kafka.server02.keystore.jks
kafka.server03.keystore.jks
kafka.server04.keystore.jks
Example of a complete playbook for testing
- hosts: all
vars:
keystore: "kafka.server{{ '%02d' % (idx + 1) }}.keystore.jks"
kt_opt_dict:
genkeypair: ''
keystore: "{{ keystore }}"
validity: 365
storepass: testtest
keypass: testtest
dname: "CN={{ item }}"
storetype: pkcs12
kt_opt: "{{ kt_opt_dict|dict2items|
json_query('[].[key, value]')|
map('join', ' ')|map('trim')|
join(' -') }}"
tasks:
- command:
cmd: "keytool -{{ kt_opt }}"
creates: "{{ keystore }}"
loop: "{{ groups.kafka }}"
loop_control:
index_var: idx
delegate_to: localhost
run_once: true
register: out
- debug:
msg: |
{% for i in out.results %}
{{ i.item }} rc: {{ i.rc }}
{% endfor %}
run_once: true
gives
shell> ansible-playbook pb.yml
PLAY [all] ************************************************************************************
TASK [command] ********************************************************************************
ok: [abc -> localhost] => (item=abc)
ok: [abc -> localhost] => (item=xyz)
ok: [abc -> localhost] => (item=tle)
ok: [abc -> localhost] => (item=zsa)
TASK [debug] **********************************************************************************
ok: [abc] =>
msg: |-
abc rc: 0
xyz rc: 0
tle rc: 0
zsa rc: 0
PLAY RECAP ************************************************************************************
abc: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0