Ansible/Jinja2 - Map nested key in list
Asked Answered
S

2

2

When map'ing a attribute in a list of nested variables, I am not able to retrieve its key.

I want to retrieve the key of "tls_cert_file" from followingemphasized text variables:

vault_config_listener:
  - tcp:
    - address: "0.0.0.0:8200"
    - tls_cert_file: "/etc/ssl/wildcard.crt"
    - tls_key_file: "/etc/ssl/private/wildcard.key"
    - tls_require_and_verify_client_cert: "false"
  - tcp:
    - address: "127.0.0.1:8200"
    - tls_disable: true

The debug task:

- debug:
    msg: "{{ (vault_config_listener | selectattr('tcp', 'defined') | map(attribute='tcp')) | selectattr('tls_cert_file','defined') | map(attribute='tls_cert_file') | join('') | dirname }}"

The output:

ok: [test] => {
    "msg": ""
}

I got the map'ing working until "tcp", but no further... What is wrong at the logic?

Sanjiv answered 14/8, 2017 at 16:24 Comment(0)
A
6

To get a list of tls_cert_file you can use

vault_config_listener | selectattr('tcp', 'defined') | map(attribute='tcp') | sum(start=[]) | selectattr('tls_cert_file','defined') | map(attribute='tls_cert_file') | list

note sum(start=[]) – it is used to flatten list of lists.

P.S. Why do you join possible(?) multiple paths into string?

P.P.S Your data structure seems rather weird. Why do you define tcp properties like list, and not just:

tcp:
  address: 0.0.0.0:8200
  tls_cert_file: /etc/ssl/wildcard.crt
  tls_key_file: /etc/ssl/private/wildcard.key
  tls_require_and_verify_client_cert: false
Applegate answered 14/8, 2017 at 16:37 Comment(3)
Thank you Konstantin! That worked fine. I am using the list in a ansible jinja2 template to loop the lines into a config file... That't not possible without a list, is it?Sanjiv
You can as well loop over dict using keys(), for example.Applegate
I have updated my list according to your suggestion. Thats actually better and easier to use. Much thanks!Sanjiv
P
0

You can fetch the value of tls_cert_file by putting the flatten filter in between.

It would be something like

- name: Get tls_cert_file
  debug:
    msg: "{{ vault_config_listener | selectattr('tcp', 'defined') | map(attribute='tcp') | flatten | selectattr('tls_cert_file', 'defined') | map(attribute='tls_cert_file') | first }}"
Prady answered 22/3, 2024 at 10:30 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.