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

  1. pkiaas_csr:
  2. host1:
  3. subject_alt_name:
  4. - host1.domainA.com
  5. - host1.domainB.com
  6. host2:
  7. subject_alt_name:
  8. - host2.domainA.com
  9. - host2.domainB.com
pkiaas_csr:
  host1:
    subject_alt_name:
    - host1.domainA.com
    - host1.domainB.com
  host2:
    subject_alt_name:
    - host2.domainA.com
    - host2.domainB.com
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

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

The

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

The use of this in your yaml

  1. - name: Create a csr
  2. command: "/usr/bin/openssl req -config csr_config.conf -new -keyout my_private_key_{{ item.key }}.key -out my_certificate_{{ item.key }}.csr
- 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
- 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

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

 

Please follow and like us: