fix(cloudformation): no-op stack update for unchanged fixed-name resources (#2385)

* fix(cloudformation): no-op stack update for unchanged fixed-name resources

CloudFormationService re-invokes provision() for every resource on every
UpdateStack, regardless of whether that resource's properties actually
changed. Several RDS/Kinesis/AutoScaling provisioners called their
service's create*() method unconditionally, so a fixed-name resource left
untouched between deploys collided with itself and threw an
AlreadyExists-style error, rolling back an otherwise no-op update
(lex00/floci#16, reported against AWS::RDS::DBSubnetGroup).

Fixed provisioners, each now checking the resource's prior physical id
before deciding whether to reconcile in place or create fresh:
 - provisionDbSubnetGroup: reconciles via RdsService.modifyDbSubnetGroup
 - provisionDbParameterGroup / provisionDbClusterParameterGroup: no-op,
   since DBParameterGroupName/Family/Description are immutable on AWS
 - provisionDbInstance / provisionDbCluster: reconciles via the existing
   (password/IAM-auth/subnet-group-scoped) modifyDbInstance/modifyDbCluster
 - provisionKinesisStream: reconciles stream mode, retention and tags
 - provisionLaunchConfiguration: no-op, since launch configurations have
   no update API on real AWS at all
 - provisionAutoScalingGroup: reconciles via updateAutoScalingGroup

A rename (explicit name changes) now creates the new resource and then
best-effort deletes the old one, mirroring the existing LogGroup pattern,
instead of leaking the old resource under its previous name.

Left unfixed, with rationale:
 - provisionCloudWatchAlarm: CloudWatchMetricsService.putMetricAlarm is
   already an upsert (real PutMetricAlarm semantics), so no bug exists
 - provisionCloudFrontDistribution: already checked the physical id and
   branched between create/update before this fix

Known pre-existing gaps not addressed here (narrow fix, not a rewrite):
 - modifyDbInstance/modifyDbCluster don't cover engine/instance-class/
   storage changes, so those template edits are silently not applied on
   reconcile
 - AutoScalingGroup's TargetGroupARNs/LoadBalancerNames/Tags aren't
   reconciled; updateAutoScalingGroup doesn't support them
 - KinesisStream's ShardCount isn't reconciled; no UpdateShardCount
   support in KinesisService

Adds an UpdateStack idempotent-redeploy integration test for each fixed
family (RDS DBSubnetGroup - the issue's repro, Kinesis stream, ASG/launch
config) plus focused RdsCfnProvisionerTest unit cases mocking the
update-reinvocation path for every RDS provisioner method above.

* fix(cloudformation): log the tolerated not-found in sameNameExistingResource

The lookup swallowed AwsException with no diagnostic, same catch-block
rule as elsewhere in this file's deleteRenamedResource.
This commit is contained in:
lex00 authored and GitHub committed 2026-08-18 19:14:24 -04:00
1 parent 9822dc34bd
commit 5864ff6aa8
5 files changed
+708 -83

No files matched your search

@@ -5,6 +5,7 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/**
* End-to-end check that CloudFormation provisions AWS::AutoScaling::LaunchConfiguration and
@@ -103,4 +104,97 @@ class CloudFormationAutoScalingIntegrationTest {
.body(containsString("<Value>only</Value>"))
.body(containsString("<PropagateAtLaunch>false</PropagateAtLaunch>"));
}
@Test
void updateStackReconcilesExistingLaunchConfigAndAsgInsteadOfFailing() {
// provision() re-runs on every UpdateStack for every resource regardless of whether its
// properties changed, so fixed-name LaunchConfiguration/AutoScalingGroup resources left
// unchanged between deploys used to call the create APIs again and roll back with
// "already exists" (same family of bug as lex00/floci#16).
String suffix = Long.toString(System.nanoTime(), 36);
String lcName = "cfn-lc-update-" + suffix;
String asgName = "cfn-asg-update-" + suffix;
String stackName = "cfn-asg-update-stack-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", asgTemplate(lcName, asgName, 1, 3, 2))
.when()
.post("/")
.then()
.statusCode(200);
// Redeploy with a changed DesiredCapacity: LaunchConfiguration is unchanged (immutable, so
// must reconcile to a no-op) and the ASG's capacity must reconcile in place.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", asgTemplate(lcName, asgName, 1, 3, 3))
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("ROLLBACK")));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", ASG_AUTH)
.formParam("Action", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", asgName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(asgName))
.body(containsString(lcName))
.body(containsString("<DesiredCapacity>3</DesiredCapacity>"));
}
private static String asgTemplate(String lcName, String asgName, int minSize, int maxSize,
int desiredCapacity) {
return """
{
"Resources": {
"LaunchConfig": {
"Type": "AWS::AutoScaling::LaunchConfiguration",
"Properties": {
"LaunchConfigurationName": "%s",
"ImageId": "ami-12345678",
"InstanceType": "t3.micro"
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchConfigurationName": {"Ref": "LaunchConfig"},
"MinSize": %d,
"MaxSize": %d,
"DesiredCapacity": %d,
"AvailabilityZones": ["us-east-1a"]
}
}
},
"Outputs": {
"AsgArn": {"Value": {"Fn::GetAtt": ["Asg", "Arn"]}}
}
}
""".formatted(lcName, asgName, minSize, maxSize, desiredCapacity);
}
}
@@ -8,6 +8,7 @@ import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/**
* End-to-end check that CloudFormation provisions an AWS::Kinesis::Stream for real (into
@@ -85,4 +86,84 @@ class CloudFormationKinesisIntegrationTest {
.body(containsString(streamName))
.body(containsString("\"RetentionPeriodHours\":48"));
}
@Test
void updateStackReconcilesExistingStreamInsteadOfFailing() {
// provision() re-runs on every UpdateStack for every resource regardless of whether its
// properties changed, so a fixed-name stream left unchanged between deploys used to call
// CreateStream again and roll back with "Stream already exists" (same family of bug as
// lex00/floci#16).
String suffix = Long.toString(System.nanoTime(), 36);
String streamName = "cfn-stream-update-" + suffix;
String stackName = "cfn-kinesis-update-stack-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", streamTemplate(streamName, 48))
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", streamTemplate(streamName, 72))
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("ROLLBACK")));
// The retention change was reconciled in place under the same stream name.
given()
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
.header("Authorization", KINESIS_AUTH)
.header("X-Amz-Target", "Kinesis_20131202.DescribeStreamSummary")
.contentType("application/x-amz-json-1.1")
.body("{\"StreamName\":\"" + streamName + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(streamName))
.body(containsString("\"RetentionPeriodHours\":72"));
}
private static String streamTemplate(String streamName, int retentionPeriodHours) {
return """
{
"Resources": {
"Stream": {
"Type": "AWS::Kinesis::Stream",
"Properties": {
"Name": "%s",
"ShardCount": 2,
"RetentionPeriodHours": %d
}
}
},
"Outputs": {
"StreamArn": {"Value": {"Fn::GetAtt": ["Stream", "Arn"]}}
}
}
""".formatted(streamName, retentionPeriodHours);
}
}
@@ -1,10 +1,13 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* End-to-end check that CloudFormation provisions RDS resources for real. Uses DBSubnetGroup
@@ -79,4 +82,101 @@ class CloudFormationRdsIntegrationTest {
.statusCode(200)
.body(containsString(groupName));
}
@Test
void updateStackReconcilesExistingDbSubnetGroupInsteadOfFailing() {
// Regression for lex00/floci#16: provision() re-runs on every UpdateStack for every resource
// regardless of whether its properties changed, so a fixed-name DBSubnetGroup left unchanged
// between deploys used to call CreateDBSubnetGroup again and roll back with
// "DB subnet group ... already exists".
String suffix = Long.toString(System.nanoTime(), 36);
String groupName = "cfn-rds-subnets-update-" + suffix;
String stackName = "cfn-rds-update-stack-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", dbSubnetGroupTemplate(groupName))
.when()
.post("/")
.then()
.statusCode(200);
String beforeXml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.extract().asString();
String groupNameBefore = XmlParser.extractPairs(beforeXml, "Outputs", "OutputKey", "OutputValue")
.get("GroupName");
// Redeploy the identical template: on real AWS this is a no-op update.
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", dbSubnetGroupTemplate(groupName))
.when()
.post("/")
.then()
.statusCode(200);
String afterXml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))
.body(not(containsString("ROLLBACK")))
.extract().asString();
String groupNameAfter = XmlParser.extractPairs(afterXml, "Outputs", "OutputKey", "OutputValue")
.get("GroupName");
// The physical id (Ref, which for a subnet group is its name) is unchanged across the update.
assertEquals(groupNameBefore, groupNameAfter);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", RDS_AUTH)
.formParam("Action", "DescribeDBSubnetGroups")
.formParam("DBSubnetGroupName", groupName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(groupName));
}
private static String dbSubnetGroupTemplate(String groupName) {
return """
{
"Resources": {
"DbSubnets": {
"Type": "AWS::RDS::DBSubnetGroup",
"Properties": {
"DBSubnetGroupName": "%s",
"DBSubnetGroupDescription": "managed by cfn",
"SubnetIds": ["subnet-default-a", "subnet-default-b"]
}
}
},
"Outputs": {
"GroupName": {"Value": {"Ref": "DbSubnets"}}
}
}
""".formatted(groupName);
}
}
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
@@ -103,6 +104,16 @@ class RdsCfnProvisionerTest {
region, "000000000000", "my-stack", physicalId, attributes);
}
/**
* Simulates an UpdateStack re-invocation: {@code provision()} is called again for the same
* resource with the physical id it was already assigned, exactly as CloudFormationService does
* on every update regardless of whether the resource's properties actually changed.
*/
private StackResource provisionUpdate(String logicalId, String type, String json, String existingPhysicalId) {
return provisioner.provision(logicalId, type, props(json), engine(),
"us-east-1", "000000000000", "my-stack", existingPhysicalId);
}
@Test
void provisionsDbInstanceWithMappedArgsAndEndpointAttributes() {
DbInstance instance = mock(DbInstance.class);
@@ -1007,6 +1018,101 @@ class RdsCfnProvisionerTest {
"us-west-2");
}
@Test
void updateStackReconcilesExistingDbSubnetGroupInsteadOfRecreating() {
// Regression for lex00/floci#16: CloudFormationService re-invokes provision() for every
// resource on every UpdateStack regardless of whether its properties changed, so a fixed-name
// DBSubnetGroup already on file used to hit createDbSubnetGroup again and throw
// DBSubnetGroupAlreadyExists, rolling back an otherwise no-op update.
DbSubnetGroup existing = mock(DbSubnetGroup.class);
when(rdsService.getDbSubnetGroup("my-subnet-group", "us-east-1")).thenReturn(existing);
DbSubnetGroup reconciled = mock(DbSubnetGroup.class);
when(reconciled.getDbSubnetGroupName()).thenReturn("my-subnet-group");
when(rdsService.modifyDbSubnetGroup(eq("my-subnet-group"), anyList(), eq("us-east-1")))
.thenReturn(reconciled);
StackResource r = provisionUpdate("Sg", "AWS::RDS::DBSubnetGroup", """
{"DBSubnetGroupName":"my-subnet-group","DBSubnetGroupDescription":"db subnets",
"SubnetIds":["subnet-a","subnet-b"]}
""", "my-subnet-group");
assertEquals("CREATE_COMPLETE", r.getStatus());
assertEquals("my-subnet-group", r.getPhysicalId());
verify(rdsService, never()).createDbSubnetGroup(any(), any(), anyList(), any());
verify(rdsService).modifyDbSubnetGroup("my-subnet-group", List.of("subnet-a", "subnet-b"), "us-east-1");
}
@Test
void updateStackNoOpsExistingDbParameterGroupInsteadOfRecreating() {
// DBParameterGroupName/Family/Description are all immutable on real AWS, so an unchanged
// re-apply must no-op rather than hit createDbParameterGroup's DBParameterGroupAlreadyExists.
DbParameterGroup existing = mock(DbParameterGroup.class);
when(existing.getDbParameterGroupName()).thenReturn("my-pg");
when(rdsService.getDbParameterGroup("my-pg", "us-east-1")).thenReturn(existing);
StackResource r = provisionUpdate("Pg", "AWS::RDS::DBParameterGroup", """
{"DBParameterGroupName":"my-pg","Family":"postgres16","Description":"params"}
""", "my-pg");
assertEquals("my-pg", r.getPhysicalId());
assertEquals("my-pg", r.getAttributes().get("DBParameterGroupName"));
verify(rdsService, never()).createDbParameterGroup(any(), any(), any(), any());
}
@Test
void updateStackNoOpsExistingDbClusterParameterGroupInsteadOfRecreating() {
DbClusterParameterGroup existing = mock(DbClusterParameterGroup.class);
when(existing.getDbClusterParameterGroupName()).thenReturn("my-cpg");
when(rdsService.getDbClusterParameterGroup("my-cpg", "us-east-1")).thenReturn(existing);
StackResource r = provisionUpdate("Cpg", "AWS::RDS::DBClusterParameterGroup", """
{"DBClusterParameterGroupName":"my-cpg","Family":"aurora-postgresql16","Description":"params"}
""", "my-cpg");
assertEquals("my-cpg", r.getPhysicalId());
assertEquals("my-cpg", r.getAttributes().get("DBClusterParameterGroupName"));
verify(rdsService, never()).createDbClusterParameterGroup(any(), any(), any(), any());
}
@Test
void updateStackReconcilesExistingDbInstanceInsteadOfRecreating() {
DbInstance existing = mock(DbInstance.class);
when(rdsService.getDbInstance("mydb")).thenReturn(existing);
DbInstance reconciled = mock(DbInstance.class);
when(reconciled.getDbInstanceIdentifier()).thenReturn("mydb");
when(rdsService.modifyDbInstance(eq("mydb"), any(), anyBoolean(), any())).thenReturn(reconciled);
StackResource r = provisionUpdate("Db", "AWS::RDS::DBInstance", """
{"DBInstanceIdentifier":"mydb","Engine":"postgres","MasterUsername":"admin",
"MasterUserPassword":"secret"}
""", "mydb");
assertEquals("mydb", r.getPhysicalId());
verify(rdsService, never()).createDbInstance(any(), any(), any(), any(), any(), any(), any(),
anyInt(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), anyBoolean(),
any(), anyMap(), nullable(String.class));
verify(rdsService).modifyDbInstance("mydb", "secret", false, null);
}
@Test
void updateStackReconcilesExistingDbClusterInsteadOfRecreating() {
DbCluster existing = mock(DbCluster.class);
when(rdsService.getDbCluster("mycluster")).thenReturn(existing);
DbCluster reconciled = mock(DbCluster.class);
when(reconciled.getDbClusterIdentifier()).thenReturn("mycluster");
when(rdsService.modifyDbCluster(eq("mycluster"), any(), anyBoolean())).thenReturn(reconciled);
StackResource r = provisionUpdate("Cluster", "AWS::RDS::DBCluster", """
{"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql",
"MasterUsername":"admin","MasterUserPassword":"secret"}
""", "mycluster");
assertEquals("mycluster", r.getPhysicalId());
verify(rdsService, never()).createDbCluster(any(), any(), any(), any(), any(), any(),
anyBoolean(), any(), any(), any(), anyBoolean(), any());
verify(rdsService).modifyDbCluster("mycluster", "secret", false);
}
@Test
void deleteDelegatesToRdsServiceForEachRdsType() {
// Stack deletion tears down RDS resources via the physical id set at provision time.