如何使用命令行终止所有EC2实例?

8
如何通过命令行杀死所有实例?是否有相应的命令,还是必须编写脚本来完成?
6个回答

13

这是一个老问题,但我想分享一种适用于AWS CLI的解决方案:

aws ec2 terminate-instances --instance-ids $(aws ec2 describe-instances --filters  "Name=instance-state-name,Values=pending,running,stopped,stopping" --query "Reservations[].Instances[].[InstanceId]" --output text | tr '\n' ' ')

相关信息:

如果黑客已经禁用了实例的意外终止,请先运行此命令:


aws ec2 describe-instances --filters  "Name=instance-state-name,Values=pending,running,stopped,stopping" --query "Reservations[].Instances[].[InstanceId]" --output text  |  xargs --delimiter '\n' --max-args=1 aws ec2   modify-instance-attribute  --no-disable-api-termination --instance-id

1
希望你不介意我去掉了 $,这样人们可以通过三次点击复制和粘贴,而不是水平滚动到结尾。此外,我添加了第二个命令,而不是发布单独的答案并从你那里窃取信用。 - Sridhar Sarnobat
要遍历所有区域,您可以运行此脚本:https://pastebin.com/tMTL8sr6 - Sridhar Sarnobat

5

AWS ConsoleElasticfox使其变得非常容易。

可以使用EC2 API工具实现一行命令行解决方案:

for i in `ec2din | grep running | cut -f2`; do ec2kill $i; done

4
据我所知,ec2-terminate-instances 命令没有“全部(all)”选项。因此,您可能需要编写脚本。这并不难。您只需要生成一个用逗号分隔的实例列表。
以下是我使用的 Python 脚本:
import sys
import time
from boto.ec2.connection import EC2Connection

def main():
    conn = EC2Connection('', '')
    instances = conn.get_all_instances()
    print instances
    for reserv in instances:
        for inst in reserv.instances:
            if inst.state == u'running':
                print "Terminating instance %s" % inst
                inst.stop()

if __name__ == "__main__":
    main()

这个使用了boto库。虽然对于特定的任务来说并不是必需的(一个简单的shell脚本就足够了),但在很多情况下它可能会很方便。

最后,你是否知道Firefox的Elasticfox扩展?这绝对是访问EC2最简单的方式。


我相信现在你可以使用connection.terminate_instances()。 - rcell

2

以下是使用boto3的更新答案:

  1. 下载Python 3
  2. 按照boto3快速入门指南进行操作
  3. 将下面的代码复制到一个文件中,取任何没有空格的名字,我取名为delete_ec2_instances.py
最初的回答 import boto3
def terminateRegion(region, ignore_termination_protection=True):
    """This function creates an instance in the specified region, then gets the stopped and running instances in that region, then sets the 'disableApiTermination' to "false", then terminates the instance."""
    # Create the profile with the given region and the credentials from:
    # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html
    s = boto3.session.Session(region_name=region)
    ec2 = s.resource('ec2')
    # Get all the instances from the specified region that are either stopped or running
    instances = ec2.instances.filter(Filters=[{'Name':'instance-state-name', 'Values': ['stopped', 'running', 'pending']}])
    for instance in instances:
        # set 'disableApiTermination' to 'false' so we can terminate the instance.
        if ignore_termination_protection:
            instance.modify_attribute(Attribute='disableApiTermination', Value='false')
        instance.terminate()
    print("done with {0}".format(region))

if __name__ == "__main__":
    # We get a list of regions that the account is associated with
    ec2 = boto3.client('ec2')
    regions = [r['RegionName'] for r in ec2.describe_regions()['Regions']]
    # loop through the regions and terminate all the instances in each region
    for region in regions:
        terminateRegion(region)
    print("done with everything")
  1. 使用命令行,导航到上述文件并输入以下命令: python terminate_ec2_instances.py (或者你的文件名)。
  2. 当所有实例都被终止时,您应该会看到删除的区域名称和最终的完成消息。
注:Original Answer翻译成"最初的回答"

我喜欢“ctrl + c -> ctrl + v”在stackoverflow上能用的答案! - Austin Poole

1
为了完整起见。这里有另一种方式,更符合程序员的技能范畴,通过使用正则表达式和aws cli实现:
aws ec2 terminate-instances 
        --instance-ids 
         $(
          aws ec2 describe-instances 
            | grep InstanceId 
            | awk {'print $2'} 
            | sed 's/[",]//g'
          )

0

这个核心不是我的,但我必须进行修改以删除所有区域中的所有实例。这是在使用aws cli安装的powershell中运行的:

foreach ($regionID in (aws ec2 describe-regions --query "Regions[].{Name:RegionName}" --output text)){foreach ($id in (aws ec2 describe-instances --filters --query "Reservations[].Instances[].[InstanceId]" --output text --region $regionID)) { aws ec2 terminate-instances --instance-ids $id --region $regionID}}

这将列出AWS中的所有区域,然后在区域上运行foreach。 在区域的foreach中,它会列出该区域中的所有实例,然后在实例上运行foreach。 在每个实例的foreach中,它将终止实例。

这是在我的亚马逊帐户被盗并设置了10,000个需要删除的ec2实例之后所需的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接