Skip to content

Instantly share code, notes, and snippets.

@josnidhin
Created August 22, 2016 14:50
Show Gist options
  • Select an option

  • Save josnidhin/c57e2cc585d99e25cb3b234b703aad11 to your computer and use it in GitHub Desktop.

Select an option

Save josnidhin/c57e2cc585d99e25cb3b234b703aad11 to your computer and use it in GitHub Desktop.
The ansible script to find ec2 instances with certain tags and terminate them. Does not uses ec2 dynamic inventory script.
---
- name: Terminate EC2 instances
hosts: localhost
connection: local
gather_facts: no
vars:
aws_region: "eu-west-1"
ec2_tags:
Name: "Test Server"
Type: "API"
tasks:
- name: Find EC2 Facts
ec2_remote_facts:
region: "{{ aws_region }}"
register: ec2_facts
# (-) is used to stip white spaces
# http://jinja.pocoo.org/docs/dev/templates/#whitespace-control
- name: Filter EC2 instances
set_fact:
ec2_instances: |
{% set instances = [] %}
{% for item in ec2_facts.instances if item.tags == ec2_tags and item.state == 'running' -%}
{{ instances.append(item.id) }}
{%- endfor %}
{{ instances }}
- name: Terminate EC2 server
ec2:
region: "{{ aws_region }}"
instance_ids: "{{ item }}"
state: 'absent'
with_items: "{{ ec2_instances }}"
@babatundebusari
Copy link
Copy Markdown

does not work..does not target the instances with the specified tags
did this work for you?

@josnidhin
Copy link
Copy Markdown
Author

This script was written a long time back. But its still working for me. Did you update the vars to reflect your environment?

The Filter EC2 instances task not required anymore, ec2_remote_facts now supports filtering.

@speedlight
Copy link
Copy Markdown

speedlight commented Feb 20, 2019

As with latest version of ansible this is working for me searching by the Name tag but could be any key.

    ec2_instance_facts:
      region: "{{ region }}"
      filters:
        "tag:Name": "{{ ec2_tag_name }}"
    register: ec2_list

@aioue
Copy link
Copy Markdown

aioue commented May 12, 2022

They have renamed facts to info.

- name: collect list of node instances
  amazon.aws.ec2_instance_info:
    region: "{{ region }}"
    filters:
      "tag:Role": "node"
      "tag:Vpc": "{{ vpc_name }}"
  register: ec2_list 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment