I'm trying to figure out how to iterate a result array with Ansible.
I'm launching a few AWS EC2 instances like this:
- name: ec2-static-instances
ec2:
<all atributes here...>
with_itens:
- instance1
- instance2
register: instances
Ok, then I get the result of the instances above in a array of hashs/dictionaries. I'm able to get each instance id like this:
{{ instances.results[0].instance_ids[0] }}
{{ instances.results[1].instance_ids[0] }}
But, I would like to make it more dynamic and not need to know in advance how many elements I have in the array. I tried something like that, but it doesn't work.
# Elastic IPs for instances created above
- name: eip_static_instances
ec2_eip:
region: us-east-1
in_vpc: yes
instance_id: "{{ item.instance_id[0] }}"
with_items:
- "{{ instances.results }}"
I get the following error:
fatal: [127.0.0.1]: FAILED! => {"failed": true, "msg": "ERROR! 'dict object' has no attribute 'instance_id'"}
I went through the official documentation, but none of the examples shown there seem to do what I want to. Does anyone have a clue?
Thank you.
UPDATE
It turns out my problem was a simples mistake with the variable name, as anyone can see above (item.instance_id instead of item.instance_ids, the later being the right one). As reference for readers, fix it and the code above will work. Thanks.
instance_idswith anson the end, but the task that's referencing it is only usingitem.instance_idwithout thes. Make sure you have your variable names correct.