无法为执行AWS :: CloudFormation :: CustomResource的aws lambda函数设置环境变量

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

我试图通过我的CloudFormation模板json为CustomResource设置环境变量,该变量在运行时获取它的值。所以稍后它会执行python lambda,我可以读取lambda中的环境变量并处理一些数据。

我希望我的python lambda能够在os.environ中读取这个变量

以下是我的CustomResource的Cloudformation

"TriggerRedshiftSetupLambda": {
      "Type": "AWS::CloudFormation::CustomResource",
      "Version": 1.0,
      "Properties": {
       "Environment": {
          "Variables": {
            "AHost": {
                "Fn::GetAtt" : [ "A", "Endpoint.Address" ]
            },
            "APort": {
                "Fn::GetAtt" : [ "A", "Endpoint.Port" ]
            }
         }
        },
        "ServiceToken": {
          "Fn::GetAtt" : [ "ASetupLambda", "Arn" ]
        }
      }
    }

这是我使用变量的lambda代码

def lambda_handler(event, context):
    print(os.environ)
    print(os.environ['AHost'])

第一个print语句打印整个环境变量列表,但没有'AHost'的任何键/值对

难道我做错了什么?如何通过lambda的customresource正确初始化环境变量?

amazon-web-services environment-variables aws-lambda amazon-cloudformation
2个回答
1
投票

似乎不支持通过自定义资源定义设置环境变量。您正在设置的是实际调用的属性部分(因此事件数据)。

因此,使用您的模板,您的配置应该可以在以下路径下访问。

event['ResourceProperties']['Environment']['Variables']['AHost']

0
投票

如上面的@jens所述,使用CustomResource CloudFormation在os.environ下设置环境变量是不可能的。

相反,Lambda CloudFormation需要定义这些值 -

"RedshiftSetupLambda": {
  "Type": "AWS::Lambda::Function",
  "Properties": {
    "Code": {
      "S3Bucket": { "Fn::Sub": "XYZ-${Branch}" },
      "S3Key": { "Fn::Sub": "XYZ-${Commit}.zip" }
    },
    "Description": "Setup Lambda",
    "FunctionName": { "Fn::Sub": "${BlockId}-setup-${Branch}" },
    "Handler": "setup.lambda_handler",
    "KmsKeyArn": {
      "Fn::ImportValue": {
        "Fn::Sub": "${BlockId}-Common-RolesKeys-${Branch}-KMSKeyArn"
      }
    },
    "Role": {
      "Fn::ImportValue": {
        "Fn::Sub": "${BlockId}-Common-RolesKeys-${Branch}-LambdaIAMRoleArn"
      }
    },
    "Runtime": "python2.7",
    "Timeout": 30,
    "VpcConfig": {
      "SecurityGroupIds": [ {"Ref": "SecurityGroup"} ],
      "SubnetIds": [
        { "Fn::ImportValue": "VPCCreate-PrivateSubnet1Id" },
        { "Fn::ImportValue": "VPCCreate-PrivateSubnet2Id" },
        { "Fn::ImportValue": "VPCCreate-PrivateSubnet3Id" }
      ]
    },
    "Environment": {
      "Variables": {
        "DB_USERNAME": {
          "Ref": "MasterUsername"
        },
        "AHOST": {
          "Fn::GetAtt": ["RedshiftCluster", "Endpoint.Address"]
        },
        "APORT": {
          "Fn::GetAtt": ["RedshiftCluster", "Endpoint.Port"]
        },
        "CLUSTER_IDENTIFIER": {
          "Ref": "RedshiftCluster"
        }
      }
    }
  }
}

可以通过以下方式访问它们:

print(os.environ['AHOST'])
© www.soinside.com 2019 - 2024. All rights reserved.