检索自定义标签值以供稍后在 Lambda / Python 3.12 函数中使用

问题描述 投票:0回答:1

我是一名实习生,对 Python 和 lambda 很陌生,接到的练习任务是创建 Lambda / Python 3.12 函数,该函数将在特定账户中搜索运行 Windows 2022 Datacenter 的 EC2 实例,然后报告这些实例以及自定义标签“itowner”、“os”的值以及“Name”和“instanceid”的标准标签值。我有一些工作,但我正在按位置检索标签值,但我只想以另一种方式获取值,因为标签位置在不同实例上可能不同。我的代码如下。

import boto3

ec2 = boto3.client('ec2')


def lambda_handler(event, context):
    response = ec2.describe_instances(
        Filters=[
            {
                'Name': 'tag:os',
                'Values': [
                    'win2022dc',
                ],
            },
        ],
    )
    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            instance_id = instance["InstanceId"]
            instance_type = instance["InstanceType"]
            for tags in instance["Tags"]:
                os = instance["Tags"][0]["Value"]
                instance_name = instance["Tags"][6]["Value"]
                itowner = instance["Tags"][11]["Value"]
             
print("Instance Name: " + instance_name,"Instance ID: " + instance_id, "Operating System: " + os, "ITOwner: " + itowner,)
python-3.x aws-lambda boto3
1个回答
0
投票

您可以使用

iterator
next
。此外,您不需要标签循环。您在这里对循环所做的是将所有内容重复多次(取决于标签的数量)。你将改变这个:

for tags in instance["Tags"]:
    os = instance["Tags"][0]["Value"]
    instance_name = instance["Tags"][6]["Value"]
    itowner = instance["Tags"][11]["Value"]

对此:

os = next(e["Value"] for e in instance["Tags"] if e["Key"]=="os")
instance_name = next(e["Value"] for e in instance["Tags"] if e["Key"]=="Name")
itowner = next(e["Value"] for e in instance["Tags"] if e["Key"]=="itowner")

这将迭代实例[“Tags”]列表,检查标签的键(因为此列表中的所有项目都是具有

Key
Value
的字典。如果
Key
是您需要的,请使用它如果您确定所有实例都有这些键,则可以使用此方法,如果您认为某些键可能不存在,则应使用安全选项在标签不存在的情况下返回空字符串,因为
next
支持返回默认值,这样就不会抛出异常:

os = next((e["Value"] for e in instance["Tags"] if e["Key"]=="os"), "")
instance_name = next((e["Value"] for e in instance["Tags"] if e["Key"]=="Name"), "")
itowner = next((e["Value"] for e in instance["Tags"] if e["Key"]=="itowner"), "")
© www.soinside.com 2019 - 2024. All rights reserved.