gpt4 book ai didi

amazon-web-services - 从 CloudFormation 调用 API/Web 请求

转载 作者:行者123 更新时间:2023-12-02 00:21:43 25 4
gpt4 key购买 nike

我希望在 CloudFormation 模板末尾调用 REST API 端点。

PUT https://example.com/v1/endpoint
{
// Body Content
}

有办法做到这一点吗?我唯一能想到的办法是:

  1. 创建 lambda 函数
  2. 使用 CF 执行 lambda 函数
  3. 删除lamdba函数

上面的方法看起来非常困惑并且比必要的花费更多的精力。

最佳答案

您正在寻找 custom resources 。它是由 Lambda 函数处理的资源。该函数不必创建任何实际资源。它可以直接调用您的端点。如果您将 Lambda 函数定义为堆栈的一部分,则当删除堆栈时,该函数也会被删除。

Lambda 函数得到如下内容:

{
"RequestType" : "Create",
"ResponseURL" : "http://pre-signed-S3-url-for-response",
"StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid",
"RequestId" : "unique id for this create request",
"ResourceType" : "Custom::TestResource",
"LogicalResourceId" : "MyTestResource",
"ResourceProperties" : {
"Name" : "Value",
"List" : [ "1", "2", "3" ]
}
}

并且需要将如下内容发送回 ResponseURL 中的 URL:

{
"Status" : "SUCCESS",
"PhysicalResourceId" : "TestResource1",
"StackId" : "arn:aws:cloudformation:us-west-2:123456789012:stack/stack-name/guid",
"RequestId" : "unique id for this create request",
"LogicalResourceId" : "MyTestResource",
"Data" : {
"OutputName1" : "Value1",
"OutputName2" : "Value2",
}
}

为了使这一过程变得更容易,Lambda 函数可以访问实现响应代码的 cfnresponse

这是一个完整的示例:

Resources:
CustomFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import cfnresponse
from botocore.vendored import requests
def handler(event, context):
if event["RequestType"] in ["Create", "Update"]:
requests.put("https://example.com/v1/endpoint", {})
elif event["RequestType"] == "Delete":
pass # if you want to do something on delete, do it here
cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "ok")
Handler: index.handler
Role: !GetAtt CustomFunctionRole.Arn
Runtime: python3.6
CustomFunctionRole:
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Action:
- sts:AssumeRole
Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Custom:
Type: Custom::Something
Properties:
ServiceToken: !GetAtt CustomFunction.Arn

您应该处理代码中的异常并使用 cfnresponse.send(event, context, cfnresponse.FAILED, {}, "ok") 来确保 CloudFormation 不会只是坐等某物。可能需要一段时间才能超时。

关于amazon-web-services - 从 CloudFormation 调用 API/Web 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55152863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com