Playbook for terminating EC2 instances?

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

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