简体   繁体   English

使用AWS CLI通过标签终止EC2实例上的集合

[英]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. 对于AWS来说还很陌生,但是我希望通过标签名称过滤来使用AWS CLI终止一组ec2实例。

If I use describe-instances , I can filter by tag:key= value . 如果使用describe-instances ,则可以按tag:key = value进行filter For terminate-instances I don't see a way of filtering. 对于terminate-instances我看不到过滤的方法。 I assume this is possible since I can filter and terminate using the AWS console but I am looking to do this via CLI. 我认为这是可行的,因为我可以使用AWS控制台进行过滤和终止,但是我希望通过CLI进行此操作。

Latest AWS CLI allows you to avoid the need for any scripts or jq: 最新的AWS CLI使您无需使用任何脚本或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. 只要预期实例的数量不是很大,就可以使用上面的实例。

The terminate-instances command only takes a list of instance IDs. terminate-instances命令仅获取实例ID的列表。 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. 您可能需要编写一个脚本来首先运行describe-instances命令并捕获实例ID,然后将这些ID传递给terminate-instances命令。

I created the following script(.sh) and it worked for me: 我创建了以下脚本(.sh),它对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM