Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rajcdlmec/b3f53d9b609dfb1043e60353e417421f to your computer and use it in GitHub Desktop.
Save rajcdlmec/b3f53d9b609dfb1043e60353e417421f to your computer and use it in GitHub Desktop.

Revisions

  1. @josnidhin josnidhin created this gist Aug 22, 2016.
    35 changes: 35 additions & 0 deletions terminate_ec2_with_tags.yml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    ---
    - 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 }}"