问题描述
我是 AWS CDK 的新手,我想要(使用 C#)完成的是对我的 lambda 函数进行版本控制,然后创建一个引用该版本的新 API 资源。
例如:程序接受一个版本参数。
internal CdkAppStack(Construct scope,string id,IStackProps props,string bucketName,string functionName,string version) : base(scope,id,props)
{
var bucket = new Bucket(this,bucketName,new BucketProps {
BucketName = bucketName
});
var handler = new Function(this,$"{functionName}Handler",new FunctionProps
{
Runtime = Runtime.DOTNET_CORE_3_1,Code = Code.FromAsset("Lambdas\\src\\Lambdas\\bin\\Debug\\netcoreapp3.1"),Handler = "Lambdas::Lambdas.Function::FunctionHandler",Environment = new Dictionary<string,string>
{
["BUCKET"] = bucket.BucketName,},FunctionName = functionName
});
string apiName = !string.IsNullOrEmpty(version) ? $"{functionName}-{version}" : functionName;
bucket.GrantReadWrite(handler);
var api = new RestApi(this,$"{apiName}-API",new RestApiProps
{
RestApiName = $"{apiName}API",Description = $"This service the Lambda - {functionName}.",RetainDeployments = true
});
var getWidgetsIntegration = new LambdaIntegration(handler,new LambdaIntegrationoptions
{
RequestTemplates = new Dictionary<string,string>
{
["application/json"] = "{ \"statusCode\": \"200\" }"
}
});
string resource = !string.IsNullOrEmpty(version) ? $"execute-{version}" : "execute";
var helloWorldResource = api.Root.AddResource(resource);
var method = helloWorldResource.AddMethod("POST",getWidgetsIntegration);
}
实际结果:
它覆盖了 lambda 和 api 资源。
预期结果:(版本参数为 3)。添加了新资源(execute-3)
解决方法
对于给定的代码,过程可能如下所示:
- 当前的配置状态包括
execute-2
- CDK 合成了一个 Cloudformation 模板,其中
execute-3
存在而execute-2
不存在。 - Cloudformation 发现,为了达到所需的状态(在模板中描述),它需要删除
execute-2
和 provisionexecute-3
.
如果您确实想要达到您所描述的内容,您将不得不添加资源并且不要删除之前配置的资源(比如编写一个运行超过 1..version 的循环并添加所有过去的版本)
另一个(不太推荐的)选项是使用 deletion policy。通过这种方式,您可以提示 cloudformation 而不是删除 execute-2
(这里的缺点是 execute-2
的生命周期不再由任何堆栈管理 --> 您必须手动管理对它的更改)>