Re: [ansible-project] How to extract a value of a field within a list of dictionaries when a key matches another value

16 views
Skip to first unread message
Message has been deleted

Vladimir Botka

unread,
Mar 26, 2020, 3:03:07 PM3/26/20
to jean-christophe manciot, ansible...@googlegroups.com
On Thu, 26 Mar 2020 11:43:33 -0700 (PDT)
jean-christophe manciot <actionm...@gmail.com> wrote:

> Let’s suppose the following data structure:
> - domain_definition:
> - name: server11
> cluster: cluster1
> port: '8080'
> - name: server12
> cluster: cluster2
> port: '8090'
> - name: server21
> cluster: cluster3
> port: '9080'
> - name: server22
> cluster: cluster4
> port: '9090'
> The goal is for example to *extract the port number when
> domain_definition.name == 'server21'.*

The playbook below

- name: test with json_query 1/2
hosts: localhost
vars:
domain_definition:
- name: server11
cluster: cluster1
port: '8080'
- name: server12
cluster: cluster2
port: '8090'
- name: server21
cluster: cluster3
port: '9080'
- name: server22
cluster: cluster4
port: '9090'
tasks:
- debug:
msg: "{{ domain_definition|
json_query('[?name==`server21`].port') }}"

gives

"msg": [
"9080"
]

HTH,

-vlado

Vladimir Botka

unread,
Mar 26, 2020, 3:11:11 PM3/26/20
to jean-christophe manciot, ansible...@googlegroups.com
"selectattr" below gives the same result

- debug:
msg: "{{ domain_definition|
selectattr('name', 'regex', '^server21$')|
map(attribute= 'port')|
list }}"

HTH,

-vlado
Message has been deleted
Message has been deleted

Dick Visser

unread,
Mar 26, 2020, 7:19:20 PM3/26/20
to ansible...@googlegroups.com
What Vladimir said (twice):

You are using:

debug:
var:


while you should be doing:

debug:
msg:


Dick

On Thu, 26 Mar 2020 at 20:19, jean-christophe manciot
<actionm...@gmail.com> wrote:
>
> Same result with your second proposal.
>
> --
> You received this message because you are subscribed to the Google Groups "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/7143cacb-46da-4263-a877-84cf9de1e559%40googlegroups.com.



--
Dick Visser
Trust & Identity Service Operations Manager
GÉANT
Reply all
Reply to author
Forward
0 new messages