是否有可能在Cloudformation json模板中执行某种数学运算?
我遇到了两个有用的区域:1.设置IOPS,它需要是磁盘大小的比率.2.为RDS免费存储空间设置Cloud Watch警报.将其设置为磁盘大小的百分比将是有用的.
在内部函数不支持的CloudFormation模板中执行自定义逻辑有两种通用解决方案,例如数学运算:
编写自定义资源以执行数学运算,将输入作为属性传递,并将输出作为值传递.这是一个独立的工作示例,它Result: 13
作为堆栈输出返回:
Resources: LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: {Service: [lambda.amazonaws.com]} Action: ['sts:AssumeRole'] Path: "/" ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole AddFunction: Type: AWS::Lambda::Function Properties: Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn Code: ZipFile: !Sub | var response = require('cfn-response'); exports.handler = function(event, context) { var result = parseInt(event.ResourceProperties.Op1) + parseInt(event.ResourceProperties.Op2); response.send(event, context, response.SUCCESS, {Value: result}); }; Runtime: nodejs AddTest: Type: Custom::Add Properties: ServiceToken: !GetAtt AddFunction.Arn Op1: 8 Op2: 5 Outputs: Result: Description: Result Value: !GetAtt AddTest.Value
使用您选择的全功能模板语言/平台编写"源"模板,生成有效的CloudFormation模板作为输出.您可以使用功能齐全的CloudFormation特定库,如对流层,但编写简单的预处理器层以满足您的用例和编程语言/库首选项也很容易.
我目前的选择是嵌入式Ruby(ERB),主要是因为我已经熟悉它了.这是一个template.yml.erb
使用嵌入式Ruby语法执行数学运算的示例文件,该操作Result: 13
作为堆栈输出返回:
Resources: # CloudFormation stacks require at least one resource Dummy: Type: AWS::SNS::Topic Outputs: Result: Description: Result Value: <%= 8 + 5 %>
要运行模板,请运行cat template.yml.erb | ruby -rerb -e "puts ERB.new(ARGF.read, nil, '-').result" > template.yml
,该模板会将以下CloudFormation-ready模板写入template.yml
:
Resources: # CloudFormation stacks require at least one resource Dummy: Type: AWS::SNS::Topic Outputs: Result: Description: Result Value: 13