简体   繁体   English

Python AWS CDK 自定义资源仅在第一次执行

[英]Python AWS CDK Custom resource only executes the first time

I have wired up a Python 3.8 lambda function as a custom resource in a cdk stack.我已将 Python 3.8 lambda function 作为 cdk 堆栈中的自定义资源连接起来。 The stack ran and triggered off the lambda execution.堆栈运行并触发了 lambda 执行。 However on subsequent updates to the stack it does nothing to call the lambda custom resource.但是,在对堆栈进行后续更新时,它不会调用 lambda 自定义资源。

This is the lambda这是lambda

def lambda_handler(event, context):
   print('lambda executed')
   print('request: {}'.format(json.dumps(event)))
   return { 'PhysicalResourceId': "1234" }

This is how it is wired up in the stack这就是它在堆栈中的连接方式

from constructs import Construct
from aws_cdk import (
    Stack,
    custom_resources as cr,
    aws_lambda as _lambda,
    CustomResource
)

cust_res_lambda = _lambda.Function(
   self, 'crLambda',
   runtime=_lambda.Runtime.PYTHON_3_8,
   code=_lambda.Code.from_asset('my-resources'),
   handler='lambda.lambda_handler',
   function_name='cr_Lambda'
)
        
res_provider = cr.Provider(
   self,'crProvider',
   on_event_handler= cust_res_lambda
)
            
CustomResource(self, 'cust_res',service_token= res_provider.service_token,properties={"curr_account":"4563563","curr_region":"us-east-1", "res_id": ''})

Why isn't the custom resource lambda getting called the second time I deploy the cdk stack?为什么我第二次部署 cdk 堆栈时自定义资源 lambda 没有被调用?

TL;DR Because your resource hasn't changed. TL;DR 因为您的资源没有改变。

docs : When you associate a Lambda function with a custom resource, the function is invoked whenever the custom resource is created, updated, or deleted. docs :当您将 Lambda function 与自定义资源相关联时,只要创建、更新或删除自定义资源,就会调用 function。

In other words, CloudFormation (which lurks behind the CDK abstraction) will invoke your Lambda when the Custom Resource is added to the stack, deleted from the stack, or has its properties changed.换句话说,当自定义资源添加到堆栈、从堆栈中删除或更改其属性时,CloudFormation(隐藏在 CDK 抽象背后)将调用您的 Lambda。 1 1个

So, if you want your flavour 2 of CR Lambda to be invoked on every deploy, include a timestamp as a property.因此,如果您希望在每次部署时调用 CR Lambda 的 flavor 2 ,请将时间戳作为属性包含在内。 The timestamp value will change each deploy, causing the CR Lambda to fire with an update event.时间戳值将更改每次部署,导致 CR Lambda 触发更新事件。


  1. This behaviour mimics how CloudFormation treats "regular" resources.此行为模仿 CloudFormation 处理“常规”资源的方式。 If your template is deployed a second time with, say, an unchanged S3 bucket configuration, CloudFormation won't touch it.如果您的模板第二次部署时使用未更改的 S3 存储桶配置,CloudFormation 将不会触及它。
  2. Consider the Trigger construct, a higher-level CR implementation that's easier to work with.考虑Trigger构造,这是一种更易于使用的更高级别的 CR 实现。 It has a executeOnEveryDeployment option.它有一个executeOnEveryDeployment选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM