gpt4 book ai didi

python - 在 yaml 中构建 Lambda 函数 - 问题

转载 作者:行者123 更新时间:2023-12-03 07:22:56 25 4
gpt4 key购买 nike

我正在构建一个 CloudFormation 部署,其中包含一个用 python 3.9 构建的 Lambda 函数。但是,当我构建该函数时,它不允许我保留单引号。对于大多数脚本来说这并不是问题,因为我只需导入 json 并且双引号 (") 工作正常,但有一个部分需要单引号。

这是代码:

import boto3
import json

def lambda_handler(event, context):
client = client_obj()
associated = associated_list(client)
response = client.list_resolver_query_log_configs(
MaxResults=1,
)
config = response['ResolverQueryLogConfigs'][0]['Id']
ec2 = boto3.client('ec2')
vpc = ec2.describe_vpcs()
vpcs = vpc['Vpcs']

for v in vpcs:
if v['VpcId'] not in associated:
client.associate_resolver_query_log_config(
ResolverQueryLogConfigId= f"{config}",
ResourceId=f"{v['VpcId']}"
)
else:
print(f"{v['VpcId']} is already linked.")

def client_obj():
client = boto3.client('route53resolver')
return client

def associated_list(client_object):
associated = list()
assoc = client_object.list_resolver_query_log_config_associations()
for element in assoc['ResolverQueryLogConfigAssociations']:
associated.append(element['ResourceId'])
return associated

任何包含 f"{v['VpcId']}" 的部分都需要在 [] 内使用单引号,脚本才能正常运行。由于yaml要求将脚本封装在单引号中进行打包,如何解决这个问题?

来自另一个脚本的 yaml 示例:

CreateIAMUser:
Type: 'AWS::Lambda::Function'
Properties:
Code:
ZipFile: !Join
- |+

- - import boto3
- 'import json'
- 'from botocore.exceptions import ClientError'
- ''
- ''
- 'def lambda_handler(event, context):'
- ' iam_client = boto3.client("iam")'
- ''
- ' account_id = boto3.client("sts").get_caller_identity()["Account"]'
- ''

我想我可以重新安排脚本来避免这种情况,但如果可能的话,我想利用这个机会学习新的东西。

最佳答案

不确定您要做什么,但通常您只需使用 pipe在 yaml 中:

      Code:
ZipFile: |
import boto3
import json

def lambda_handler(event, context):
client = client_obj()
associated = associated_list(client)
response = client.list_resolver_query_log_configs(
MaxResults=1,
)
config = response['ResolverQueryLogConfigs'][0]['Id']
ec2 = boto3.client('ec2')
vpc = ec2.describe_vpcs()
vpcs = vpc['Vpcs']

for v in vpcs:
if v['VpcId'] not in associated:
client.associate_resolver_query_log_config(
ResolverQueryLogConfigId= f"{config}",
ResourceId=f"{v['VpcId']}"
)
else:
print(f"{v['VpcId']} is already linked.")

def client_obj():
client = boto3.client('route53resolver')
return client

def associated_list(client_object):
associated = list()
assoc = client_object.list_resolver_query_log_config_associations()
for element in assoc['ResolverQueryLogConfigAssociations']:
associated.append(element['ResourceId'])
return associated

关于python - 在 yaml 中构建 Lambda 函数 - 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70311791/

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