Is there a way to specify only changed parameters using aws cloudformation update stack and avoid explicit UsePreviousValue for unchanged parameters?

Viewed 4262

I am trying to write a generic script in AWS Cloudformation CLI that will update the stacks' parameter AMI to a new value while leaving the rest of the parameters as is.

So far, I tried doing this like so:

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

Notice that there are 2 parameters who are just using UsePreviousValue=true and only the the value of ParameterKey=MachineImage is the one that needs to change - this works fine.

However, since I need it to be a generic script how can I handle the case where some stacks have more parameters than above (or even some have different parameters but still have ParameterKey=MachineImage)? Is there way to say only change value of ParameterKey=MachineImage and all the rest should be using previous value without explicitly listing in the --parameters?

2 Answers

Based on the comments.

The aws cloudformation update-stack does not provide desired functionality.

However, a possible solution is develop a custom wrapper around aws cloudformation update-stack. The wrapper would allow a user to provide only new/changed parameters. It would also use describe-stacks command to get the current values of existing stack parameters.

Having the current parameters from the stack, as well as the new/changed ones, the wrapper could construct construct the valid aws cloudformation update-stack command and execute the update.

I was able to write the unix script using the aws cli as per below:

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

Which generates a new .sh file which contains the update commands, I then review the contents of that generated .sh and do a source to execute these :

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