You also can use json_query.
---
- name: test
hosts: localhost
become: no
gather_facts: no
vars:
postgres_create_users:
- {role: user1, password: password1}
- {role: user2, password: password2}
- {role: user3, password: password3}
- {role: user4, password: password4}
my_user: user4
tasks:
- debug:
msg: "{{ (postgres_create_users | json_query('[?role==`'+my_user+'`]'))[0].password }}"
Note that in my jinja2 variable template in the debug statement I insert a variable "my_user" to show that json queries can be dynamic based on a value only known at run-time. Change the value of my_user on the command line and see how it changes the output.
% ansible-playbook foo.yml
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [test] ************************************************************************************************************
TASK [debug] ***********************************************************************************************************
ok: [localhost] => {
"msg": "password4"
}
PLAY RECAP *************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
% ansible-playbook foo.yml -e my_user=user2
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'
PLAY [test] ************************************************************************************************************
TASK [debug] ***********************************************************************************************************
ok: [localhost] => {
"msg": "password2"
}
PLAY RECAP *************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
--
Walter Rowe, Chief
Infrastructure Services
Office of Information Systems Management
National Institute of Standards and Technology
United States Department of Commerce