问题描述
我正在使用 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
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
非常感谢任何帮助.
推荐答案
这应该可以解决问题:
# open connection to ec2
conn = get_ec2_conn()
# get a list of all instances
all_instances = conn.get_all_instances()
# get instances with filter of running + with tag `Name`
instances = conn.get_all_instances(filters={'tag-key': 'Name', 'instance-state-name': 'running'})
# 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:
conn.stop_instances(instance.id)
在boto3中:
# 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()
这篇关于使用 Python 关闭没有特定标签的 EC2 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!