如何在SSM Document中传入表达式作为值更新CloudFormation栈参数
问题原因
- 你在
GetDesiredCount步骤中定义的DesiredCapacity输出类型为String,字符串类型无法直接执行数值加法运算 - SSM Automation文档的变量语法不支持直接在
{{}}内写+运算符做算术计算,需要使用官方内置的数学运算函数
修正方案
修改两处配置即可实现需求:
- 将
GetDesiredCount步骤输出的Type从String改为Integer,确保拿到的是数值类型的期望实例数 - 在
UpdateCloudFormationStack步骤的ParameterValue中,使用SSM内置的add()函数和math()工具实现数值加1
修正后的完整SSM Document代码如下:
schemaVersion: '0.3' parameters: cfnStack: description: 'The cloudformation stack to be updated' type: String mainSteps: - name: GetDesiredCount action: 'aws:executeAwsApi' inputs: Service: cloudformation Api: DescribeStacks StackName: '{{ cfnStack }}' outputs: - Selector: '$.Stacks[0].Outputs.DesiredCapacity' Type: Integer # 原String类型改为Integer Name: DesiredCapacity - name: UpdateCloudFormationStack action: 'aws:executeAwsApi' inputs: Service: cloudformation Api: UpdateStack StackName: '{{ cfnStack }}' UsePreviousTemplate: true Parameters: - ParameterKey: WebServerCapacity ParameterValue: '{{ math(add(GetDesiredCount.DesiredCapacity, 1)) }}' # 调用内置函数完成加法
额外注意事项
- 如果你的
DesiredCapacity是存放在CloudFormation栈的参数而非输出中,需要把GetDesiredCount步骤的Selector改为$.Stacks[0].Parameters[?ParameterKey=='WebServerCapacity'].ParameterValue | [0] - 要保证执行SSM文档的IAM角色拥有CloudFormation DescribeStacks和UpdateStack的对应权限
内容的提问来源于stack exchange,提问作者chenchuk
相关产品推荐
相关产品推荐

