# Playbook for terminating EC2 instances?

**URL:** <https://forum.ansible.com/t/playbook-for-terminating-ec2-instances/13330>\
**Category:** Ansible Project\
**Created:** [August 19, 2013, 5:33pm UTC](https://forum.ansible.com/t/playbook-for-terminating-ec2-instances/13330 "2013-08-19T17:33:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jharrod\_LaFon](https://avatars.discourse-cdn.com/v4/letter/j/3ab097/32.png) [@Jharrod\_LaFon](https://forum.ansible.com/u/Jharrod_LaFon)\
**Post date:** [August 19, 2013, 5:33pm UTC](https://forum.ansible.com/t/playbook-for-terminating-ec2-instances/13330/1 "2013-08-19T17:33:07Z")

</div>

I am still learning Ansible, so maybe I have missed something. What I would like to do is be able to launch, configure, and terminate EC2 instances using Ansible.  
Starting from the documentation, launching and configuring instances is easy. Also starting from the documentation, terminating instances is possible if you launched them from the same playbook.

What I need is to be able to run a playbook that terminates instances that are tagged with a certain value.  
I am using the ec2 inventory script, and have started on a playbook to terminate instances.

- name: Terminate OEWS Instances  
hosts: localhost  
connection: local  
gather\_facts: false

tasks:

- name: Terminating instances  
local\_action:  
module: ec2  
instance\_tags: ‘{“ansible\_class”: “test”}’  
state: ‘absent’  
instance\_ids: $ec2.instance\_ids

When I run this playbook, I get the following error:  
fatal: [localhost] =\> failed to parse: [‘$ec2.instance\_ids’]

I am assuming that the ec2 module has not run yet and therefore the variable is not defined.

Does anyone know the correct way to do this?

Thanks,

-Jharrod

---

<div class="post-metadata">

**Author:** ![benno\_joy](https://avatars.discourse-cdn.com/v4/letter/b/73ab20/32.png) [@benno\_joy](https://forum.ansible.com/u/benno_joy)\
**Post date:** [August 20, 2013, 2:04am UTC](https://forum.ansible.com/t/playbook-for-terminating-ec2-instances/13330/2 "2013-08-20T02:04:21Z")

</div>

Hi Jharrod,

There are couple of ways to do it, add an “id” tag to the create instance task and then when you want to delete those instance’s run the same create task and register the output, it wont create the instances as it checks for instance’s with that id.  
Otherwise you can use the ec2.py inventory script, and the hosts that are tagged as “test” would be grouped under “ec2\_tag\_test” group, then you can use “ec2\_id” host variable to get the instance id and pass it to the terminate task.

Regards,  
Benno
