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

发布于 2024-07-15 03:05:42 字数 39 浏览 5 评论 0原文

如何从命令行杀死所有实例? 是否有相关命令或者我必须编写脚本?

How can I kill all my instances from the command line? Is there a command for this or must I script it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

荒芜了季节 2024-07-22 03:05:42

这是一个老问题,但我想分享一个 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

This is an old question but thought I'd share a solution for 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' ' ')

Related info:

If hackers have disabled accidental instance termination, first run this command:

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
酸甜透明夹心 2024-07-22 03:05:42

AWS 控制台Elasticfox 使其变得非常简单。

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

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

AWS Console and Elasticfox make it pretty easy.

A command-line solution can be achieved in one-line using the EC2 API tools:

for i in `ec2din | grep running | cut -f2`; do ec2kill $i; done
作业与我同在 2024-07-22 03:05:42

据我所知,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 最简单的方法。

As far as I know there isn't an 'all' switch for the ec2-terminate-instances command. So you probably need to script it. It won't be that hard. You only need to generate a comma separated list of your instances.

This is a python script I am using:

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()

It uses boto library. This is not necessary for the specific task (a simple shell script will be enough), but it may be handy in many occasions.

Finally are you aware of Elasticfox extension for Firefox? This is by far the easiest way to access EC2.

且行且努力 2024-07-22 03:05:42

这是使用 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终止_ec2_instances.py
    (或者无论您的文件被命名为什么。
  2. 您应该看到该区域被删除时的名称,以及当所有实例都终止时的最终完成消息。

Here is an updated answer using boto3:

  1. Download python 3
  2. Follow the Quickstart for boto3
  3. Paste the following code into a file and call it anything without a space, I did 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. Using the commandline, navigate to the above file and type:
    python terminate_ec2_instances.py
    (or whatever your file is named.
  2. You should see the name of the region as it is deleted and a final done message when all the instances have been terminated.
演出会有结束 2024-07-22 03:05:42

为了完整性。
这是另一种方法,通过使用正则表达式和 aws cli,更符合程序员的技能:

aws ec2 terminate-instances 
        --instance-ids 
         $(
          aws ec2 describe-instances 
            | grep InstanceId 
            | awk {'print $2'} 
            | sed 's/[",]//g'
          )

For completeness sake.
Here's another way, being more in line with the repertoire of a programmer, by using regular expressions and the aws cli:

aws ec2 terminate-instances 
        --instance-ids 
         $(
          aws ec2 describe-instances 
            | grep InstanceId 
            | awk {'print $2'} 
            | sed 's/[",]//g'
          )
汐鸠 2024-07-22 03:05:42

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

foreach ($regionID in (aws ec2 describe-regions --query "Regions[].{Name:RegionName}" --output text)){foreach ($id in (aws ec2 描述实例 --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 实例之后需要的。

The core of this wasn't mine, but I had to make modifications to make it delete all instances in all regions. This was run in powershell using the aws cli install:

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}}

This lists all the regions in AWS, then runs a foreach on the regions.
In the regions foreach it lists all the instances in the region, then runs a foreach on the instances.
In the instances foreach it terminates the instance.

This was needed after my amazon account got hacked and they setup 10,000 instances of ec2 that needed deleting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文