我正在构建一个 CloudFormation 模板,其属性应根据阶段(例如,beta、prod)设置为不同的值。该属性的类型是数字。但是,Fn.FindInMap 返回字符串标记。那么如何使用 FindInMap 来设置这种数字类型的属性呢?
这适用于 AWS CDK Java 语言 API。
这是映射的代码部分:
Mapping writeCapacityMapping = new Mapping(parent, "TableWriteCapacityMapping", MappingProps.builder()
.withMapping(ImmutableMap.of(
Stage.beta.name(), ImmutableMap.of(
"min", 5,
"max", 100),
Stage.prod.name(), ImmutableMap.of(
"min", 400,
"max", 1200)))
.build());
这是试图通过阶段参数从映射中获取值并分配给需要数字类型的属性(minCapacity 和 maxCapacity)的代码部分。
String minCapacity = Fn.findInMap("TableWriteCapacityMapping", stageParameter.getValueAsString(), "min");
String maxCapacity = Fn.findInMap("TableWriteCapacityMapping", stageParameter.getValueAsString(), "max");
ScalableTargetProps props = ScalableTargetProps.builder()
.withMinCapacity(Integer.valueOf(minCapacity))
.withMaxCapacity(Integer.valueOf(maxCapacity))
.build();
预期的 CloudFormation 模板是:
Mappings:
WriteCapacityMap:
beta:
min: 5
max: 100
prod:
min: 400
max: 1200
TableWriteCapacityScalableTarget:
Type: "AWS::ApplicationAutoScaling::ScalableTarget"
Properties:
MinCapacity:
Fn::FindInMap: [WriteCapacityMap, { Ref: "Stage" }, min]
MaxCapacity:
Fn::FindInMap: [WriteCapacityMap, { Ref: "Stage" }, max]
但是,会抛出以下异常,因为 minCapacity 或 maxCapacity 是令牌字符串:Exception in thread "main" java.lang.NumberFormatException: For input string: "${Token[TOKEN.14]}"