0

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.

2
  • 1
    The output you showed has the property named as instance_ids with an s on the end, but the task that's referencing it is only using item.instance_id without the s. Make sure you have your variable names correct. Commented Nov 28, 2015 at 15:11
  • Oh, obviously! How could I not see this? I'm sorry for that. I think I had been working for too long on this thing. Thank you. Commented Nov 28, 2015 at 15:45

1 Answer 1

1

Just posting my comment as an answer so that the question can be marked as answered:

The output you showed has the property named as instance_ids with an s on the end, but the task that's referencing it is only using item.instance_id without the s. Make sure you have your variable names correct.

Sign up to request clarification or add additional context in comments.

Comments

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.