使用Python关闭没有特定标记的EC2实例

时间:2016-06-28 20:14:20

标签: python amazon-web-services amazon-ec2 tags boto3

我在这里使用mlapida这个脚本: https://gist.github.com/mlapida/1917b5db84b76b1d1d55#file-ec2-stopped-tagged-lambda-py

mlapida的脚本与我需要的相反,我不熟悉Python,知道如何重组它以使其工作。我需要关闭所有没有特殊标记的EC2实例来识别它们。

逻辑是: 1.)识别所有正在运行的实例 2.)从该列表中删除具有特殊标记的任何实例 3.)处理要关闭的剩余实例列表

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题:

# open connection to ec2
conn = get_ec2_conn()
# get a list of all instances
all_instances = [i for i in conn.instances.all()]
# get instances with filter of running + with tag `Name`
instances = [i for i in conn.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}, {'Name':'tag-key', 'Values':['Name']}])]
# make a list of filtered instances IDs `[i.id for i in instances]`
# Filter from all instances the instance that are not in the filtered list
instances_to_delete = [to_del for to_del in all_instances if to_del.id not in [i.id for i in instances]]
# run over your `instances_to_delete` list and terminate each one of them
for instance in instances_to_delete:
    instance.stop()

在boto3中:

{{1}}

答案 1 :(得分:0)

使用mlapida和Yonatan的信用,我有一个工作脚本,关闭所有没有标签“AutoOff”的实例,任何“AutoOff”设置为“False”的实例都保持打开,希望这有助于那个人。

import boto3
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection
ec2 = boto3.resource('ec2')
# open connection to ec2
#conn = get_ec2_conn()

# get a list of all instances
all_instances = [i for i in ec2.instances.all()]

def lambda_handler(event, context):

    #instances = ec2.instances.filter(Filters=filters)
    # get instances with filter of running + with tag `Name`
    instances = [i for i in ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}, {'Name':'tag:AutoOff', 'Values':['False']}])]

    # make a list of filtered instances IDs `[i.id for i in instances]`
    # Filter from all instances the instance that are not in the filtered list
    instances_to_delete = [to_del for to_del in all_instances if to_del.id not in [i.id for i in instances]]

    # run over your `instances_to_delete` list and terminate each one of them
    for instance in instances_to_delete:
        instance.stop()