Issue
I have just started using Ansible for some of my projects. For a test script I've created 57 ec2 instances using ansible. All of these instances have same security group in common, It would be a tedious task to terminate them all by instance id's using ansible. Is there any way to terminate these instances using ansible based on some common factor like a security group or a key pair. Can I terminate all instances having same security group or having same key pair without their instance id's using ansible?
Here is the code snippet i used to create these instances.
---
- name: Launching the AWS instance
hosts: localhost
tasks:
- name: Launching the AWS instance
ec2:
key_name: Ansible
region: ap-south-1
instance_type: t2.micro
image: ami-0620d12a9cf777c87
group: Akshay_ansible
count: 57
aws_access_key: XXXXXXXXXXXXXXXXXXXX
aws_secret_key: XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Solution
It can be done using the ec2_instance
module.
- ec2_instance:
state: absent
filters:
key-name: Ansible
For the list of filters that can be used, refer to the Filter section under Request Parameters here.
Answered By - franklinsijo