# Creating dynamic hosts using ec2 module

**URL:** <https://forum.ansible.com/t/creating-dynamic-hosts-using-ec2-module/20169>\
**Category:** Ansible Project\
**Created:** [January 11, 2016, 11:55am UTC](https://forum.ansible.com/t/creating-dynamic-hosts-using-ec2-module/20169 "2016-01-11T11:55:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ori\_stoliar](https://avatars.discourse-cdn.com/v4/letter/o/4bbf92/32.png) [@ori\_stoliar](https://forum.ansible.com/u/ori_stoliar)\
**Post date:** [January 11, 2016, 11:55am UTC](https://forum.ansible.com/t/creating-dynamic-hosts-using-ec2-module/20169/1 "2016-01-11T11:55:02Z")

</div>

Hi,

I am new with using the dynamic hosts option. I am creating ec2 instances and creating a dynamic host group so I could run several different roles on them after the instances are created.

My issue is that after the instances are created my other roles are being ran only on the first host in the inventory.

**site.yml**

- name: Spin up EC2 servers  
hosts: ec2\_instances  
connection: local  
gather\_facts: true  
roles:

- ec2  
tags:

- ec2

- hosts: dynamic\_hosts  
gather\_facts: false  
tasks:

- ping:

- debug: var=hostvars[inventory\_hostname]

- debug: msg=dynamic\_hosts  
roles:

- ping  
tags:

- ec2

**Tasks file:**

- name: Launch Instance  
ec2:  
group\_id: “{{ hostvars[inventory\_hostname].group\_id }}”  
count: 1  
instance\_type: ‘t2.nano’  
image: ‘{{ hostvars[inventory\_hostname].image }}’  
wait: true  
region: ‘region’  
keypair: keypair  
instance\_tags: “{{ hostvars[inventory\_hostname].tags }}”  
profile: profile\_name  
register: ec2

- name: Add hosts group temporary inventory group  
add\_host:  
name: “{{ item.public\_ip }}”  
groups: dynamic\_hosts  
ansible\_ssh\_host: “{{ item.public\_ip }}”  
ansible\_ssh\_private\_key\_file: file.pem  
ansible\_ssh\_user: user  
ec2\_instance\_ids: “{{ ec2.instance\_ids }}”  
with\_items: ec2.instances

**inventory file**  
[ec2\_instances]  
ec2test1 image=“image\_id” tags=“{ ‘env’: ‘test’, ‘Name’: ‘test1’ }” group\_id=‘group’  
ec2test2 image=“image\_id” tags=“{ ‘env’: ‘test’, ‘Name’: ‘test2’ }” group\_id=‘group’

I run the playbook like this:  
ansible-playbook --tags=ec2 -i inventory site.yml

The outcome is both ec2test1\2 instances are created but the ping role is being run only on the first instance in the inventory file(ec2test1).  
It seems that the dynamic\_hosts group that I am creating will not assign more than 1 object there.

Please assist.  
Ori.

---

<div class="post-metadata">

**Author:** ![ori\_stoliar](https://avatars.discourse-cdn.com/v4/letter/o/4bbf92/32.png) [@ori\_stoliar](https://forum.ansible.com/u/ori_stoliar)\
**Post date:** [January 17, 2016, 4:18pm UTC](https://forum.ansible.com/t/creating-dynamic-hosts-using-ec2-module/20169/2 "2016-01-17T16:18:48Z")

</div>

> Anyone?

Its version 1.9.4.
