Terminate a set on EC2 instances by tags using AWS

2019-04-15 17:34发布

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.

3条回答
啃猪蹄的小仙女
2楼-- · 2019-04-15 18:13

I created the following script(.sh) and it worked for me:

aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId]' --filters 'Name=tag-value,Values=MYTAG' --output text |
grep stopped |
awk '{print $2}' |
while read line;
do aws ec2 terminate-instances --instance-ids $line
done
查看更多
姐就是有狂的资本
3楼-- · 2019-04-15 18:32

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.

查看更多
趁早两清
4楼-- · 2019-04-15 18:36

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.

查看更多
登录 后发表回答