Ansible – Using key value of a dict

Ansible – Using key value of a dict

29 September 2018 0 By Eric Deleforterie

When you do some things that needs complex data structure, it could be great to acces to the key and value of the complex data structure.

You can do it with the lookup magic word.

Here is that complex data structure

pkiaas_csr:
  host1:
    subject_alt_name:
    - host1.domainA.com
    - host1.domainB.com
  host2:
    subject_alt_name:
    - host2.domainA.com
    - host2.domainB.com

So you want to loop on that structure for creating a certificate signing request with this playbook

- name: Creating the CSR
  include: create_csr.yml
  loop: "{{ lookup('dict', pkiaas_csr, wantlist=True) }}"

The wantlist=True is mandatory for looping when you have only one element in your data structure.

The use of this in your yaml

- name: Create a csr
  command: "/usr/bin/openssl req -config csr_config.conf -new -keyout my_private_key_{{ item.key }}.key -out my_certificate_{{ item.key }}.csr

and in your template file used for creating the csr_config.conf

subjectAltName = {% for alias in item.value.subject_alt_name %}DNS:{{ alias }}{% if not loop last %},{% endif %}{% endfor %}

 

Please follow and like us: