Stop multiple untagged AWS EC2 instances with a Bash script

 List all EC2 instances without a specific tag

One day we have found 499 instances running in our account without any tags. Most likely someone accidentally started a process to launch those, so we needed a way to find them and stop them. Later we will terminate them with the same script below when we can make sure those are not needed.

For simplicity, place the appropriate aws_access_key_id and aws_secret_access_key into the [default] section of the “~/.aws/credentials” file or use the –profile option in every command below.

List all instances

To list all EC2 instances, execute

aws ec2 describe-instances

List all instances missing a specific tag

I have found the command to list those instances that are missing the “Name” tag at https://www.onica.com/blog/using-aws-cli-to-find-untagged-instances/

I have directed the output to a text file with the additional last line.

To get all info on the instances with no “Name” tag into a JSON file

aws ec2 describe-instances \
--query 'Reservations[].Instances[?!not_null(Tags[?Key == `Name`].Value)]' \
> instances-no-name-tag.json

To output multiple properties into a tab-separated file for reporting in Excel.

aws ec2 describe-instances \
--output text \
--filters Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[?!not_null(Tags[?Key == `Name`].Value)] | [].[InstanceId,ImageId,InstanceType,Platform,LaunchTime,SubnetId,KeyName]' \
> instance-info-no-name-tag.csv

Get the list of instance IDs into a text file for batch processing

aws ec2 describe-instances \
--output text \
--filters Name=instance-state-name,Values=running \
--query 'Reservations[].Instances[?!not_null(Tags[?Key == `Name`].Value)] | [].[InstanceId]' \
> instance-ids-no-name-tag.txt

Stop an instance with the instance Id

aws ec2 stop-instances --instance-ids MY_INSTANCE_ID

Stop multiple instances

To stop all instances listed in the “instance-ids-no-name-tag.txt” file created above, create and execute this Bash script:

#!/bin/bash

# The file with the instance IDs
filname=instance-ids-no-name-tag.txt

# Iterate through the lines
while read p; do
  echo "Stopping $p"
  aws ec2 stop-instances --instance-ids $p
done <$filname

 

Leave a comment

Your email address will not be published. Required fields are marked *