gpt4 book ai didi

python - 云形成 : Reference and use Parameters in inline python code for custom resource?

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

//这是在一个cloudformation模板内

//这些是参数,从这里我想使用 OpsBucketname

AWSTemplateFormatVersion: 2010-09-09
Transform:
- AWS::LanguageExtensions
- AWS::Serverless-2016-10-31
Parameters:
DeploymentHash:
Type: String
Description: sample description
Stage:
Type: String
Description: sample description
OpsBucketName:
Type: String

//这些是我想使用参数的资源,在lambda函数上,代码:zipfile: - 在lambda_handler上

Resources:
CognitoUiCustomizationLambdaRole:
Type: "AWS::IAM::Role"
// ...
CognitoSetUiCustomizationLambda:
Type: "AWS::Lambda::Function"
Properties:
Code:
ZipFile: |
          import boto3
import logging

logger = logging.getLogger()
client = boto3.client('cognito-idp')
s3 = boto3.client('s3')

def lambda_handler(event, context):
logo = s3.get_object(Bucket="${OpsBucketName}", Key="${BlockPrefix}/assets/frontend/assets/images/logo.png")

// other codes here not related to questions ...
      Description: Lambda for custom resource to customize the cognito login page
FunctionName: !Sub "CognitoLoginCustomization-${NamingSuffix}"
Handler: index.lambda_handler
Runtime: python3.9
Timeout: 10
Role: !GetAtt CognitoUiCustomizationLambdaRole.Arn

我的主要目的是从参数中获取存储桶名称,然后使用它从该存储桶获取 Logo ,并在 cognito_idp.setUiCustomization() 函数上使用该 Logo 来设置自定义认知登录页面。

在我的函数 lambda_handler 中,我使用 OpsBucketName 使用语法 ${OpsBucketName}但在我的cloudwatch日志中,错误是它是空的,但我确信它有一个值,因为不使用自定义资源的其他资源已成功创建并已成功使用该存储桶名称。

我在这里使用该参数的语法正确吗?我在互联网上找不到与我的问题相同的示例。非常感谢。

我尝试搜索此场景的文档,但没有看到。我希望看到一个在 lambda 函数上使用参数的示例,代码:使用 python 的 ZipFile。

最佳答案

我不确定如何直接从参数实现它,但是您可以通过引用参数来使用内联 lambda 函数内的环境变量code> 您在 Cloudformation 模板中定义的内容。

首先我们需要创建指向您的参数的环境变量:

LambdaFunction:
Type: AWS::Lambda::Function
Properties:
Environment:
Variables:
DeploymentHash: !Ref DeploymentHash
Stage: !Ref Stage
OpsBucketName: !Ref OpsBucketName

然后在内联代码中提取这些环境变量

# extracting the env variables first
deploymentHash = os.environ.get('DeploymentHash')
stage = os.environ.get('Stage')
opsbucketname = os.environ.get('OpsBucketName')

def lambda_handler(event, context):
# your code

关于python - 云形成 : Reference and use Parameters in inline python code for custom resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76473174/

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