Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Lambda Boto3基于标记停止实例的程序_Python_Amazon Web Services_Aws Lambda_Boto3 - Fatal编程技术网

Python Lambda Boto3基于标记停止实例的程序

Python Lambda Boto3基于标记停止实例的程序,python,amazon-web-services,aws-lambda,boto3,Python,Amazon Web Services,Aws Lambda,Boto3,我已经编写了基于特定标记自动停止实例的代码。虽然我的程序运行良好。但对我来说,问题是我的标记值是区分大小写的。例如,如果我将标记值重命名为“testinstance”,我的程序将无法运行。有人能帮我吗 提前谢谢 这是我的密码 import json import boto3 def lambda_handler(event, context): ec2 = boto3.client('ec2', region_name='ap-south-1') a = ec2.describ

我已经编写了基于特定标记自动停止实例的代码。虽然我的程序运行良好。但对我来说,问题是我的标记值是区分大小写的。例如,如果我将标记值重命名为“testinstance”,我的程序将无法运行。有人能帮我吗

提前谢谢

这是我的密码

import json
import boto3

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name='ap-south-1')
    a = ec2.describe_instances(Filters=[{'Name':'tag:Testing', 'Values':['TestInstance']}])
    b = a['Reservations']

    for c in b:
        inst = c['Instances']

        for d in inst:
           instid = d['InstanceId']
           instrun = d['State']['Name']

           if instrun == 'running':
              ec2.stop_instances(InstanceIds=[instid])
              print("The instance is stopped:" + instid)
           else:
              print("The instance in stop state:" + instid)
我不认为有什么“好”的方法可以做到这一点。理想情况下,我建议您将所有标记都改为小写,这样您就不会有这个问题

您可以做的是从AWS中提取所有实例,然后在Python中手动检查标记:

导入json
进口boto3
ec2=boto3.客户('ec2',地区名称='ap-south-1')
def lambda_处理程序(事件、上下文):
ec2_instances=ec2.description_instances()
ec2_reservations=ec2_实例['reservations']
对于ec2_预订中的预订:
实例=保留['instances']
例如:
如果应停止实例(实例):
停止_实例(实例)
def应停止实例(实例):
应该停止=错误
实例\状态=实例['state']['Name']
对于实例['Tags']中的标记:
如果标记['key'].lower()=='tag:testing'和标记['Value'].lower()=='testinstance'和instance_state=='running':
应该停止=真的吗
应该停止返回
def stop_实例(实例):
instance_id=instance['InstanceId']
ec2.stop_实例(instanceId=[instance_id])
打印(“实例已停止:“+instance\u id”)
此外,您还可以在将来发布更清晰的代码。命名变量
a
b
c
使人们很难理解它。看看我的变量是如何命名的,这样读起来更简单,逻辑被分解成函数,这有助于易读性


我还将
ec2=boto3.client('ec2',region\u name='ap-south-1')
移出了处理函数。您可能只想在lambda冷启动时初始化一次,而不是每次从“热”启动时初始化一次。

您可能运气不好。过滤器区分大小写。基于不区分大小写筛选器终止的唯一方法是实际检索所有实例,然后在python中手动执行标记检查,此时您可以使手动检查不区分大小写。如果您只想停止某些类型的实例。。还有很多其他的分组方式,比如安全组、子网、ami、密钥对(如果有)、实例类型等等。仅供参考:值得补充的是,我认为您最好使用不同的方法来停止这些。它们是否都可以放到ECS集群或类似的集群中。