How to extract a specific value from input list ?

I have the following input list

postgres_create_users:

  • {role: user1 , password: password1 }
  • {role: user2, password: password2}
  • {role: user3, password: password3}
  • {role: user4, password: password4}

As part of J2 template file I need to extract the password of user4 - How this can be done ?

insights.jdbc.password={{ postgres_create_users ??? }}

Thank you

insights.jdbc.password={{ postgres_create_users ??? }}

Create a dictionary. The best choice might be the same place the list
*postgres_create_users* comes from. For example,

cat group_vars/all/postgres_create_users.yml

postgres_create_users:
  - {role: user1, password: password1}
  - {role: user2, password: password2}
  - {role: user3, password: password3}
  - {role: user4, password: password4}
pcu_dict: "{{ postgres_create_users|
              items2dict(key_name='role',
                         value_name='password') }}"

gives

  pcu_dict:
    user1: password1
    user2: password2
    user3: password3
    user4: password4

The usage is trivial. For example, the template

cat templates/server.xml.j2

insights.jdbc.password="{{ pcu_dict.user4 }}"

and the playbook

cat pb.yml

- hosts: localhost
  tasks:
    - debug:
        msg: "{{ lookup('template', 'server.xml.j2') }}"

gives (abridged)

ansible-playbook pb.yml

TASK [debug]

You also can use json_query.

You also can use json_query.

For example, the template

cat templates/server.xml.j2

insights.jdbc.password="{{ my_pswd }}"

and the task

    - debug:
        msg: "{{ lookup('template', 'server.xml.j2') }}"
      vars:
        my_user: user4
        my_pswd: "{{ postgres_create_users|
                     json_query(_query)|first }}"
        _query: '[?role==`{{ my_user }}`].password'

gives the same result

TASK [debug]

Here is a way that

  • uses only ansible built-ins (note that json_query is a) in an unsupported collection b) requires python json libraries which may not be available)
  • works with every version of jinja2 (EL7 and later controller)

insights.jdbc.password={{ postgres_create_users | selectattr(‘role’, ‘match’, ‘^user4$’) | map(attribute=‘password’) | first }}

Nice!

Walter

Ansible is an amazing tool. So many creative and powerful ways to massage data and get what we want.