使用Python关闭没有特定标签的EC2实例 [英] Shutdown EC2 instances that do not have a certain tag using Python

查看:87
本文介绍了使用Python关闭没有特定标签的EC2实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用mlapida的此脚本,发布在这里:
https://gist.github.com/mlapida/1917b5db84b76b1d1d55#file-ec2-stopped-tagged-lambda-py

I'm using this script by mlapida posted here: https://gist.github.com/mlapida/1917b5db84b76b1d1d55#file-ec2-stopped-tagged-lambda-py

The mlapida编写的脚本与我需要的功能相反,我对Python不太熟悉,不知道如何对其进行重组以使其正常工作。我需要关闭所有没有特殊标签标识它们的EC2实例。

The script by mlapida does the opposite of what I need, I'm not that familiar with Python to know how to restructure it to make this work. I need to shutdown all EC2 instances that do not have a special tag identifying them.

逻辑将是:
1.)标识所有正在运行的实例
2.)从该列表中删除所有带有特殊标签的实例
3.)处理要关闭的其余实例列表

The logic would be: 1.) Identify all running instances 2.) Strip out any instances from that list that have the special tag 3.) Process the remaining list of instances to be shutdown

我们非常感谢您的帮助。

Any help is greatly appreciated.

推荐答案

在mlapida和Yonatan的功劳下,我有一个工作脚本可以关闭所有没有标签 AutoOff的实例,以及所有没有将 AutoOff设置为

With credits to mlapida and Yonatan, I have a working script that shuts down all instances that don't have a tag "AutoOff" and any instance that does have "AutoOff" set to "False" stays on, hope this helps someone out there.

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

这篇关于使用Python关闭没有特定标签的EC2实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆