【问题标题】:retrieve the cloudformation stack name from the lambda function从 lambda 函数中检索 cloudformation 堆栈名称
【发布时间】:2017-10-20 10:19:57
【问题描述】:

我从cloudformation 模板中的custom resource 调用lambda function。此自定义资源有一个属性:cloudformation 堆栈的名称。我需要 lambda 函数中的这个属性值,以便我可以获取堆栈的其他变量,如 parametersoutputs。这里是custom resource

"DeployApp": {
  "Type" : "Custom::deployapplication",
  "Properties" : {
    "ServiceToken": { "Fn::GetAtt" :  ["lambda" , "Arn"]  },
    "StackName": { "Ref": "AWS::StackName" }
  }
}

目前,我通过这种方式在 lambda 函数中获取堆栈名称:

import boto3

def lambda_handler(event, context):

    cf_client = boto3.client('cloudformation')
    # Get the name of the stack
    stack = context.invoked_function_arn.split(':')[6]
    stack = stack.split('-')[:4]
    stack_name = stack[0]+'-'+stack[1]+'-'+stack[2]+'-'+stack[3]
    print('CloudFormation stack name : '+stack_name)

在这里,我总是将堆栈的名称设置为这样的:

stack-cfn-lambda-app : 4 个单词被 '-' 分割 但我想让它更通用,以便接受所有名称格式。 在不知道格式将如何的情况下,如何做到这一点并获得堆栈的确切名称?

换句话说,我如何在 python 中从这个字符串中获取(函数 lambda ARN):

arn:aws:lambda:eu-west-1:53436693423891:function:stackName-ELATEDLEXZPS

:function:ELATEDLEXZPS 之间的字符串?

【问题讨论】:

    标签: python json amazon-web-services aws-lambda amazon-cloudformation


    【解决方案1】:

    如果您已经将堆栈名称放在函数属性中,就像您在第一个代码示例中所做的那样,您可以简单地通过事件对象访问这些属性。

      StackInfo:
        Type: Custom::StackInfo
        Properties:
          ServiceToken: !GetAtt StackInfoFunction2.Arn
          StackName:
            Ref: "AWS::StackName"
    

    Lambda 代码:

    import json
    import cfnresponse
    def handler(event, context):
      print("stack name: " + event['ResourceProperties']['StackName'])
      cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
    

    【讨论】:

    • 是的!我明白了 非常感谢。实际上,事件变量只是简单化了事情
    猜你喜欢
    • 2019-03-15
    • 2017-11-25
    • 1970-01-01
    • 2018-06-15
    • 2022-01-27
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多