如何从命令行中删除所有EC2实例?

时间:2009-03-12 12:13:09

标签: amazon-ec2 amazon-web-services

如何从命令行终止所有实例?是否有命令或者我必须编写脚本吗?

5 个答案:

答案 0 :(得分:7)

这是一个老问题,但我想我会分享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 :(得分:5)

AWS ConsoleElasticfox让它变得非常简单。

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

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

答案 2 :(得分:3)

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

答案 3 :(得分:0)

为了完整起见。 这是另一种方式,通过使用正则表达式和aws cli更符合程序员的保留曲目:

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

答案 4 :(得分:0)

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

  1. 下载python 3
  2. 遵循Quickstart for boto3
  3. 将以下代码粘贴到文件中,然后将其命名为没有空格的任何东西,我做了delete_ec2_instances.py

import boto3

def terminateRegion(region):
    """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']}])
    for instance in instances:
        # set 'disableApiTermination' to 'false' so we can terminate the instance.
        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
    ec22 = boto3.client('ec2')
    regions = [r['RegionName'] for r in ec22.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")

def terminateRegion(region): """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']}]) for instance in instances: # set 'disableApiTermination' to 'false' so we can terminate the instance. 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 ec22 = boto3.client('ec2') regions = [r['RegionName'] for r in ec22.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. 当所有实例终止时,您应该看到该区域的名称以及该区域的名称。