Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate a set on EC2 instances by tags using AWS CLI

Faily new to AWS however I am looking to terminate a set of ec2 instances using the AWS CLI by filtering by a Tag name.

If I use describe-instances, I can filter by tag:key=value . For terminate-instances I don't see a way of filtering. I assume this is possible since I can filter and terminate using the AWS console but I am looking to do this via CLI.

like image 504
Geddon Avatar asked Feb 06 '17 20:02

Geddon


People also ask

Can you terminate an EC2 instance?

To terminate an instance using the consoleOpen the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . In the navigation pane, choose Instances. Select the instance, and choose Actions, Instance State, Terminate. Choose Yes, Terminate when prompted for confirmation.

Which AWS CLI command correctly adds tags to an EC2 instance?

If you're using the Amazon EC2 API, the AWS CLI, or an AWS SDK, you can use the CreateTags EC2 API action to apply tags to existing resources. Additionally, some resource-creating actions enable you to specify tags for a resource when the resource is created.


2 Answers

Latest AWS CLI allows you to avoid the need for any scripts or jq:

aws ec2 terminate-instances --instance-ids $(aws ec2 describe-instances --query 'Reservations[].Instances[].InstanceId' --filters "Name=tag:tagkey,Values=tagvalue" --output text)

as long as the number of expected instances is not huge, the above can be used.

like image 191
m1keil Avatar answered Oct 13 '22 20:10

m1keil


The terminate-instances command only takes a list of instance IDs. You would need to write a script to run the describe-instances command first and capture the instance IDs, then pass those IDs to the terminate-instances command.

like image 35
Mark B Avatar answered Oct 13 '22 20:10

Mark B