Friday, February 4, 2022

[SOLVED] Is there any way to terminate all EC2 instances by tags with Ansible?

Issue

So I have a very simple ansible script to terminate EC2 instances that I filtered using tags.

- name: Destroy Web Instance.
  hosts: localhost
  connection: local
  
  vars_files:
  - group_vars/all

  tasks:
  - name: Gather Web Instance EC2 Facts.
    ec2_instance_info:
      region: "{{ region }}"
      filters:
        "tag:Type": "web"
      aws_access_key: "{{ec2_access_key}}"
      aws_secret_key: "{{ec2_secret_key}}"
    register: ec2_web

  - name: Kill EC2 Instance
    ec2:
      instance_ids: "{{ ec2_web.instances[0].instance_id }}"
      state: absent
      region: "{{ region }}"
      aws_access_key: "{{ec2_access_key}}"
      aws_secret_key: "{{ec2_secret_key}}"

The script worked fine, but when there is multiple instances within the same tags, it only terminates the first one. Is there any way to terminate every instances within those tags?


Solution

instance_ids: "{{ ec2_web.instances[0].instance_id }}"

This is just one instance and hence terminating only one. you can use count_tag to count the instances with a specific tag and terminate the exact number of instances using exact_count

example at the end of this documentation

https://docs.ansible.com/ansible/latest/collections/amazon/aws/ec2_module.html



Answered By - Raj
Answer Checked By - Dawn Plyler (WPSolving Volunteer)