CloudFormation - 从 Lambda 代码访问参数

Asd*_*dfg 5 amazon-web-services aws-cloudformation aws-lambda

我有一个CloudFormation如下所示的模板:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "This template will deploy stuff",
    "Parameters":{
    "myParamToLambdaFunction" : {
        "Description" : "Please enter the the value",
        "Type" : "String",
        "ConstraintDescription" : "must have some value."
    }
},
"Resources": {
    "SecGrpValidatorFromCFTemplate": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "FunctionName": "mylambdafunctionname",
            "Handler": "myfile.lambda_handler",
            "Role": {
                "Fn::GetAtt": ["somerole", "Arn"]
            },
            "Timeout": "30",
            "Runtime": "python2.7",
            "Code": {
                "S3Bucket":"mybucket",
                "S3Key":"mylambdafunction.zip"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要将 的值传递myParamToLambdaFunction给 Lambda 函数。

有办法这样做吗?

wjo*_*dan 4

截至2016 年 11 月 18 日,AWS Lambda 现在支持环境变量,CloudFormation 通过资源Environment上的属性来支持环境变量AWS::Lambda::Function

向您的资源添加一个Environment属性,如下所示:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "This template will deploy stuff",
    "Parameters":{
    "myParamToLambdaFunction" : {
        "Description" : "Please enter the the value",
        "Type" : "String",
        "ConstraintDescription" : "must have some value."
    }
},
"Resources": {
    "SecGrpValidatorFromCFTemplate": {
        "Type": "AWS::Lambda::Function",
        "Properties": {
            "FunctionName": "mylambdafunctionname",
            "Handler": "myfile.lambda_handler",
            "Role": {
                "Fn::GetAtt": ["somerole", "Arn"]
            },
            "Timeout": "30",
            "Runtime": "python2.7",
            "Code": {
                "S3Bucket":"mybucket",
                "S3Key":"mylambdafunction.zip"
            },
            "Environment": {
                "Variables": {
                    "myParam": {
                        "Ref": "myParamToLambdaFunction"
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后根据您的运行时平台(例如,os.environ['myParam']在 Python 中)从部署的 Lambda 函数引用环境变量。