python - 无法通过自定义 cloudformation 资源调用 lambda 函数

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

我正在创建一个 cloudformation 模板,用于创建 DynamoDB 表。我想将模板参数的值放入 DynamoDB 表 中。为此,我创建了一个 lambda 函数,它接受堆栈参数并将它们放入表项中,如下所示:

import boto3

def lambda_handler(event, context):
    parameters = {}
    outputs = {}
    cf_client = boto3.client('cloudformation')
    dynamodb = boto3.resource('dynamodb')
    # Get the name of the stack cloudformation
    stack_name = context.invoked_function_arn.split(':')[6].rsplit('-', 2)[0]
    response = cf_client.describe_stacks(StackName=stack_name)
    # Get the outputs of the stack
    for r in response['Stacks'][0]['Outputs']:
        outputs[r['OutputKey']] = r['OutputValue']
    policy_table_name = outputs['PolicyDDBTableName']
    # Get the parametres of the stack
    for e in response['Stacks'][0]['Parameters']:
        parameters[e['ParameterKey']] = e['ParameterValue']
    DefaultRetentionDays = parameters['DefaultRetentionDays']
    CustomTagName = parameters['CustomTagName']
    AutoSnapshotDeletion = parameters['AutoSnapshotDeletion']
    response = dynamodb.put_item(
        TableName=policy_table_name,
        Item={'SolutionName': {'S': 'EbsSnapshotScheduler'},
              'DefaultRetentionDays': {'S': DefaultRetentionDays},
              'CustomTagName': {'S': CustomTagName},
              'AutoSnapshotDeletion': {'S': AutoSnapshotDeletion}
             })

然后在模板cloudformation中,我创建了一个自定义资源来调用该函数:

"PutInDB" : {
  "Type" : "Custom::customhelper",
  "Properties" : {
    "ServiceToken": { "Fn::GetAtt" :  ["FunctionHelper" , "Arn"]  },
    "StackName": {"Ref": "AWS::StackName" }
  }
},

该函数及其角色也在同一个堆栈中创建。

当我创建堆栈时,自定义资源挂起并无法创建,并出现错误:

Custom Resource failed to stabilize in expected time

。我在这里错过了什么吗? 如何成功创建自定义资源并调用函数,以便将堆栈参数插入到DynamoDB 表中?

来自AWS Documentation :

When you associate a Lambda function with a custom resource, the function is invoked whenever the custom resource is created, updated, or deleted

最佳答案

您是否在同一个 CF 模板中创建 lambda 函数?

我没有仔细研究过这一点,但我的初步印象是 lambda 函数没有完成让 cloudformation 知道它已完成创建的要求。

关键在于CF“response.SUCCESS”响应尚未发送回CF。 CF 将创建 lambda 函数,但它需要知道它是否成功。

这就是你在 node.js 中的做法,我不知道 python 的语法。

response.send(event, context, response.SUCCESS, responseData);

参见http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html

关于python - 无法通过自定义 cloudformation 资源调用 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42575342/

相关文章:

ios - "Initializer for conditional binding must have Optional type, not ' [字符串 : Any] '" error in swift

python - 在 AWS EC2 上部署 Pyramid 应用程序

mysql - Ansi SQL 查询给出不合理的结果

Python 名称未定义但计算结果为真。如何?

python - 将硬球装入盒子中

python - 有没有更好/更干净的方法来格式化这个脚本

python - 如何设置热图纵横比

ios - 无法将类型 '__NSDictionaryM' 的值转换为 'NSArray"

java - 安卓工作室 : Json Parsing loads only 10 objects out of 50 that exists in the URL

amazon-web-services - 从 Linux 连接到 EC2 Windows 主机