我尝试使用cloudformation创建一组lambdas。我希望lambdas一旦被创建就会被触发。我在各个博客中看到了为s3
或sns
创建触发器,但似乎没有一个选项可以在创建后触发lambda
。有什么选择吗?
答案 0 :(得分:21)
是的,有可能。以下是一些选项:
手动create an SNS Topic。使用lambda函数作为AWS::SNS::Subscription
并将SNS主题添加为Endpoint
,将TopicArn
添加到堆栈。在堆栈创建/更新时,配置要发送到此SNS主题的堆栈事件通知。
--notification-arns
或其他AWS开发工具包。)添加AWS CLI引用要在创建时调用的Lambda函数。
DependsOn
attribute)。 CREATE_IN_PROGRESS
时调用Lambda函数,因为自定义资源是堆栈本身的一部分。DELETE_FAILED
状态。将Lambda函数引用添加到stack status,然后编写一个执行堆栈创建的简单脚本,然后手动调用Lambda函数。
答案 1 :(得分:1)
对于那些寻找类似解决方法的人。
CloudWatch能够捕获CloudFormation的API调用,即#34; CreateStack"," UpdateStack"和" DeleteStack",堆叠状态,如" Create_complete"或" Complete_Rollback"是不可赎回的,这意味着这种状态变化无法触发lambda。
解决方法是SNS,堆栈能够向SNS发送通知(在创建堆栈时提前设置)并且SNS可以选择触发lambda,但是,您无法选择特定状态。因此,lambda函数需要找到" Message"中的状态。事件的内容。每个人,只是编码。
答案 2 :(得分:1)
以下内容效果很好!
LambdaFunction2:
Type: AWS::Lambda::Function
Properties:
FunctionName: caller
Code:
ZipFile: |
import boto3, json
import cfnresponse
def handler(event, context):
print('EVENT:[{}]'.format(event))
lambda_client = boto3.client('lambda')
test_event = '{"name":"test1"}'
lambda_client.invoke(
FunctionName='target1',
InvocationType='Event',
Payload=test_event,
)
responseValue = 120
responseData = {}
responseData['Data'] = responseValue
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
Handler: index.handler
Role:
arn:aws:iam::11111111111:role/mylambda-role
Runtime: python3.7
Timeout: 60
Primerinvoke:
Type: AWS::CloudFormation::CustomResource
DependsOn: LambdaFunction2
Version: "1.0"
Properties:
ServiceToken: !GetAtt LambdaFunction2.Arn
答案 3 :(得分:0)
您可以选择通知SNS主题,并且您可以构建一个侦听该主题的lambda,因此工作流程将是:Cloudformation launch - > SNS主题 - > LAMBDA。
答案 4 :(得分:0)
以下模板应调用lambda:
“ InvokeLambda”:{ “ Type”:“ Custom :: InvokeLambda”, “版本”:“ 1.0”, “属性”:{ “ ServiceToken”:{ “ Fn :: GetAtt”:[“ InitFunction”,“ Arn”] } } }