gpt4 book ai didi

python - 使用 Python 关闭没有特定标签的 EC2 实例

转载 作者:太空宇宙 更新时间:2023-11-03 16:24:51 25 4
gpt4 key购买 nike

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

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

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

非常感谢任何帮助。

最佳答案

这应该可以解决问题:

# 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 - 使用 Python 关闭没有特定标签的 EC2 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38085482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com