Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kenmoini/733a80e55cf2c6571a2f46953b55d507 to your computer and use it in GitHub Desktop.
Save kenmoini/733a80e55cf2c6571a2f46953b55d507 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 }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment