2

Consider the following returned data from an ansible module, I register the results in a variable called kibana_lc_all.

I'd like to be able to iterate over all of the name values, but I'm not sure how to do so with Ansible... I know I can print the first value via:

- debug:
    msg: "LC info is: {{ kibana_lc_all.results[0].name }}"

But how could I iterate and either print all 3 names, or store the 3 names in an array variable and iterate over them later in another task? Also, there won't always be 3 names, could be anywhere from 1 to 20...

  {
   u'results':[  
   {  
      u'ram_disk_id':u'',
      u'name':u'pro-ELK-Kibana-20170628-1152',
      u'image_id':u'ami-1a96a60c'
   },
   {
      u'ram_disk_id':u'',
      u'name':u'pro-ELK-Kibana-20170625-1050',
      u'image_id':u'ami-1b97d64f'
   }, 
   {
      u'ram_disk_id':u'',
      u'name':u'pro-ELK-Kibana-20170621-0931',
      u'image_id':u'ami-1b97d64f'
   },
  ]
 }

1 Answer 1

3

Use map filter:

- set_fact:
    my_list: "{{ kibana_lc_all.results | map(attribute='name') | list }}"

or json_query filter:

- set_fact:
    my_list: "{{ kibana_lc_all | json_query('results[].name') }}"
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I was close as I had stumbled on the json_query, but wasn't quite sure of the syntax. One more follow up question. Now that I have a list, is there any easy way to cut X elements off the array? i.e. I want to do actions against all list values except the first two items.
Ah, I think I found it, reading up on jmsepath, I can use the json_query to just grab from array element 2 on, via lc_list: "{{ kibana_lc_all | json_query('results[2:].name') }}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.