首页 > 解决方案 > 有没有办法使用 aws cloudformation 更新堆栈仅指定更改的参数并避免对未更改的参数显式 UsePreviousValue?

问题描述

我正在尝试在 AWS Cloudformation CLI 中编写一个通用脚本,它将堆栈的参数 AMI 更新为新值,同时保持其余参数不变。

到目前为止,我尝试这样做:

aws cloudformation update-stack --stack-name asg-xxx-123 --use-previous-template --parameters ParameterKey=ApplicationName,UsePreviousValue=true  ParameterKey=ArtefactVersion,UsePreviousValue=true ParameterKey=MachineImage,ParameterValue=ami-123

请注意,有 2 个参数正在使用UsePreviousValue=true,只有 的值ParameterKey=MachineImage是需要更改的值 - 这很好用。

但是,既然我需要它是一个通用脚本,我该如何处理某些堆栈的参数比上面更多的情况(或者甚至有些堆栈具有不同的参数但仍然有ParameterKey=MachineImage)?有没有办法说只改变值,ParameterKey=MachineImage其余的都应该使用以前的值而不明确列出--parameters

标签: amazon-web-servicesamazon-cloudformationaws-cli

解决方案


我能够使用 aws cli 编写 unix 脚本,如下所示:

curdate=`date +"%Y-%m-%d"`
newami=${1} 
for sname in $(aws cloudformation describe-stacks --query "Stacks[?contains(StackName,'prefix-') ].StackName" --output text) ;
do
    paramslist="--parameters ";
     
    for paramval in $(aws cloudformation describe-stacks --stack-name $sname --query "Stacks[].Parameters[].ParameterKey" --output text) ;
    do
        if [ $paramval == "MachineImg" ] || [ $paramval == "AMI" ]
        then
            paramslist+="ParameterKey=${paramval},ParameterValue=${newami} "; #use the ami from args
        else
            paramslist+="ParameterKey=${paramval},UsePreviousValue=true "; #else keep using UsePreviousValue=true
        fi
    done
     
    printf "aws cloudformation update-stack --stack-name ${sname} --use-previous-template ${paramslist};\n" >> "/tmp/ami-update-${curdate}.sh"
done

这会生成一个包含更新命令的新 .sh 文件,然后我查看生成的 .sh 的内容并执行源代码来执行这些命令:

source ./ami-update-2020-08-17.sh

推荐阅读