fix(cloudformation): skip unchanged resources during updates (#4442)

* fix(cloudformation): skip unchanged resources during updates

* fix(cloudformation): refresh dependent resources during updates (#4442)

* fix(cloudformation): support SQS rollback and scope dependent updates to replaced resources

- Implement replacement and in-place update rollback in SqsCfnProvisioner

- Scope dependent updates during stack update to only resources depending on replaced resources

- Compute and include dependent modified resources in ChangeSets to align DescribeChangeSet with execution

- Prevent unmodified resources such as S3 buckets from losing configuration when referenced resources update in-place

* fix(cloudformation): load create-only properties from schemas and handle condition changes

* fix(cloudformation): skip resources on outputs-only update and include create-only schema in native image

* fix(cloudformation): accurately assert unchanged queue events on outputs-only update

* fix(cloudformation): supply location constraint when creating nested stack templates bucket

* fix(cloudformation): revisit dependents on attribute changes and treat empty schema create-only lists as authoritative

* fix(cloudformation): preview in-place attribute dependents in changesets and support ASG rollback

- Include dependents of in-place modified resources with changed attributes in ChangeSet previews

- Snapshot and roll back in-place AutoScalingGroup updates on stack failure

- Implement LaunchTemplate update rollback to cleanly unwind launch template versions

* fix(cloudformation): restore ASG defaults during rollback

* fix(cloudformation): skip unchanged resources for empty updates

* fix(cloudformation): reconcile resources on identical updates and tolerate null attributes

* fix(cloudformation): skip unchanged resources on identical updates
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-10-01 23:05:38 -04:00
1 parent 2170c89d88
commit 60985b9a80
20 files changed
+2644 -9

No files matched your search

@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.cloudformation;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CfnCreateOnlyPropertiesTest {
@Test
void isCreateOnly_matchesSchemaDefinedProperties() {
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Redshift::Cluster", "DBName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::Redshift::Cluster", "ClusterIdentifier"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::EC2::Subnet", "CidrBlock"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::DomainName", "DomainName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "QueueName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "FifoQueue"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "BucketName"));
}
@Test
void isCreateOnly_returnsFalseForMutableProperties() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "VisibilityTimeout"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Redshift::Cluster", "NumberOfNodes"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "VersioningConfiguration"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Cognito::UserPool", "UserPoolName"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::UsagePlan", "UsagePlanName"));
}
@Test
void isCreateOnly_fallsBackToHeuristicForCustomOrUnknownTypes() {
assertTrue(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "WidgetName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "Name"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "ClusterIdentifier"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("Custom::Widget", "Description"));
}
@Test
void getCreateOnlyProperties_returnsExpectedSet() {
Set<String> redshiftProps = CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::Redshift::Cluster");
assertTrue(redshiftProps.contains("DBName"));
assertTrue(redshiftProps.contains("ClusterIdentifier"));
Set<String> unknownProps = CfnCreateOnlyProperties.getCreateOnlyProperties("Unknown::Type");
assertTrue(unknownProps.isEmpty());
}
}
@@ -4,11 +4,17 @@ import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
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;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* UpdateStack must leave an unchanged resource alone, whatever its type.
@@ -28,6 +34,8 @@ class CfnUnchangedResourceUpdateIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/cloudformation/aws4_request";
private static final String SQS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260808/us-west-2/sqs/aws4_request";
private static String stackWith(String namedResourceJson, String queueName) {
return """
@@ -65,6 +73,25 @@ class CfnUnchangedResourceUpdateIntegrationTest {
return physicalIdOf(body, "Named");
}
private String queueAttribute(String queueUrl, String attributeName) {
String body = given()
.header("Authorization", SQS_AUTH)
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueAttributes")
.formParam("QueueUrl", queueUrl)
.formParam("AttributeName.1", attributeName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
return XmlParser.extractPairs(body, "Attribute", "Name", "Value").get(attributeName);
}
private void deleteStack(String stackName) {
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack").formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stackName);
}
/**
* Creates the stack, updates it with only the churn queue renamed, then asserts both that the
* update completed and that the untouched resource kept its physical id. The second assertion
@@ -286,6 +313,189 @@ class CfnUnchangedResourceUpdateIntegrationTest {
}""");
}
@Test
void updatesAResourceWhenItsReferencedQueueIsReplaced() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-sqs-redrive-" + suffix;
String oldDeadLetterName = "probe-dlq-old-" + suffix;
String newDeadLetterName = "probe-dlq-new-" + suffix;
String mainQueueName = "probe-main-" + suffix;
String initialTemplate = redriveTemplate(oldDeadLetterName, mainQueueName);
String updatedTemplate = redriveTemplate(newDeadLetterName, mainQueueName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.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>CREATE_COMPLETE</StackStatus>"));
String beforeXml = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResources").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().body().asString();
String oldDeadLetterUrl = physicalIdOf(beforeXml, "DeadLetterQueue");
String mainQueueUrl = physicalIdOf(beforeXml, "MainQueue");
String oldDeadLetterArn = queueAttribute(oldDeadLetterUrl, "QueueArn");
assertTrue(queueAttribute(mainQueueUrl, "RedrivePolicy").contains(oldDeadLetterArn));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", updatedTemplate)
.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>"));
String afterXml = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResources").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().body().asString();
String newDeadLetterUrl = physicalIdOf(afterXml, "DeadLetterQueue");
String newDeadLetterArn = queueAttribute(newDeadLetterUrl, "QueueArn");
assertNotEquals(oldDeadLetterArn, newDeadLetterArn);
assertTrue(queueAttribute(mainQueueUrl, "RedrivePolicy").contains(newDeadLetterArn));
deleteStack(stackName);
}
@Test
void changeSetIncludesDependentQueueWhenReferencedQueueIsReplaced() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-sqs-cs-" + suffix;
String changeSetName = "cs-" + suffix;
String oldDeadLetterName = "probe-dlq-old-" + suffix;
String newDeadLetterName = "probe-dlq-new-" + suffix;
String mainQueueName = "probe-main-" + suffix;
String initialTemplate = redriveTemplate(oldDeadLetterName, mainQueueName);
String updatedTemplate = redriveTemplate(newDeadLetterName, mainQueueName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.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>CREATE_COMPLETE</StackStatus>"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateChangeSet").formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", updatedTemplate)
.when().post("/").then().statusCode(200);
String describeXml = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeChangeSet").formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.when().post("/").then().statusCode(200).extract().body().asString();
assertTrue(describeXml.contains("<LogicalResourceId>DeadLetterQueue</LogicalResourceId>"));
assertTrue(describeXml.contains("<LogicalResourceId>MainQueue</LogicalResourceId>"));
assertTrue(describeXml.contains("<Replacement>True</Replacement>"));
deleteStack(stackName);
}
@Test
void unchangedBucketRetainsCorsWhenReferencedLogGroupUpdatesInPlace() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-s3-cors-" + suffix;
String bucketName = "probe-bucket-cors-" + suffix;
String logGroupName = "/cfn/log-group-" + suffix;
String initialTemplate = """
{
"Resources": {
"LogGroup": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "%s", "RetentionInDays": 7}
},
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "%s",
"Tags": [{"Key": "LogGroupRef", "Value": {"Ref": "LogGroup"}}]
}
}
}
}
""".formatted(logGroupName, bucketName);
String updatedTemplate = """
{
"Resources": {
"LogGroup": {
"Type": "AWS::Logs::LogGroup",
"Properties": {"LogGroupName": "%s", "RetentionInDays": 14}
},
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": "%s",
"Tags": [{"Key": "LogGroupRef", "Value": {"Ref": "LogGroup"}}]
}
}
}
}
""".formatted(logGroupName, bucketName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.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>CREATE_COMPLETE</StackStatus>"));
String corsXml = """
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>http://example.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
""";
given().contentType("application/xml").body(corsXml)
.when().put("/" + bucketName + "?cors")
.then().statusCode(200);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", updatedTemplate)
.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>"));
given()
.when().get("/" + bucketName + "?cors")
.then().statusCode(200)
.body(containsString("http://example.com"));
deleteStack(stackName);
}
private static String redriveTemplate(String deadLetterQueueName, String mainQueueName) {
return """
{
"Resources": {
"DeadLetterQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
},
"MainQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "%s",
"RedrivePolicy": {
"deadLetterTargetArn": {"Fn::GetAtt": ["DeadLetterQueue", "Arn"]},
"maxReceiveCount": 3
}
}
}
}
}
""".formatted(deadLetterQueueName, mainQueueName);
}
@Test
void ecrRepository() {
assertUnchangedResourceSurvivesUpdate("ecr", """
@@ -348,4 +558,151 @@ class CfnUnchangedResourceUpdateIntegrationTest {
"Properties": {"BucketName": "probe-bucket-SUFFIX"}
}""");
}
@Test
void outputsOnlyUpdate_skipsUnchangedResources() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-outputs-only-" + suffix;
String queueName = "probe-q-" + suffix;
String initialTemplate = """
{
"Resources": {
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(queueName);
String updatedTemplate = """
{
"Resources": {
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
},
"Outputs": {
"QueueArn": {"Value": "static-output"}
}
}
""".formatted(queueName);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.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>CREATE_COMPLETE</StackStatus>"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", updatedTemplate)
.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(containsString("<OutputKey>QueueArn</OutputKey>"));
// Queue was unchanged, so it should have only CREATE_IN_PROGRESS / CREATE_COMPLETE events,
// never UPDATE_IN_PROGRESS or UPDATE_COMPLETE.
String events = given()
.contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents").formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
List<String> queueStatuses = XmlParser.extractGroups(events, "member").stream()
.filter(member -> "Queue".equals(member.get("LogicalResourceId")))
.map(member -> member.get("ResourceStatus"))
.toList();
assertTrue(queueStatuses.contains("CREATE_COMPLETE"));
assertFalse(queueStatuses.contains("UPDATE_IN_PROGRESS"));
assertFalse(queueStatuses.contains("UPDATE_COMPLETE"));
deleteStack(stackName);
}
@Test
void createChangeSet_updateRestApiAndUserPoolRename_reportsReplacementFalse() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "probe-cs-rename-" + suffix;
String changeSetName = "cs-rename-" + suffix;
String initialTemplate = """
{
"Resources": {
"Api": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {"Name": "api-initial-%s"}
},
"Pool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {"UserPoolName": "pool-initial-%s"}
}
}
}
""".formatted(suffix, suffix);
String updatedTemplate = """
{
"Resources": {
"Api": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {"Name": "api-renamed-%s"}
},
"Pool": {
"Type": "AWS::Cognito::UserPool",
"Properties": {"UserPoolName": "pool-renamed-%s"}
}
}
}
""".formatted(suffix, suffix);
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.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>CREATE_COMPLETE</StackStatus>"));
given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", updatedTemplate)
.when().post("/").then().statusCode(200);
String desc = given().contentType("application/x-www-form-urlencoded").header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.when().post("/").then().statusCode(200)
.extract().body().asString();
List<Map<String, String>> members = XmlParser.extractGroups(desc, "ResourceChange");
Map<String, String> apiChange = members.stream()
.filter(m -> "Api".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", apiChange.get("Action"));
assertEquals("False", apiChange.get("Replacement"));
Map<String, String> poolChange = members.stream()
.filter(m -> "Pool".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", poolChange.get("Action"));
assertEquals("False", poolChange.get("Replacement"));
deleteStack(stackName);
}
}
@@ -1,12 +1,20 @@
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 java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Covers how AWS::AutoScaling::AutoScalingGroup resolves a launch template when it is provisioned by
@@ -61,6 +69,19 @@ class CloudFormationAsgLaunchTemplateIntegrationTest {
.statusCode(200);
}
private void updateStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private String describeStacks(String stackName) {
return given()
.contentType("application/x-www-form-urlencoded")
@@ -309,4 +330,251 @@ class CloudFormationAsgLaunchTemplateIntegrationTest {
assertThat(describeStacks(stackName),
containsString("Value of property OnDemandBaseCapacity must be an integer."));
}
@Test
void asgUpdatesWhenLaunchTemplateBumpsVersionInPlace() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-lt-bump-stack-" + suffix;
String asgName = "cfn-asg-bump-" + suffix;
String ltName = "cfn-lt-bump-" + suffix;
String queueName = "cfn-q-bump-" + suffix;
String template1 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(ltName, asgName, queueName);
String template2 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {"ImageId": "ami-12345678", "InstanceType": "t3.small"}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(ltName, asgName, queueName);
createStack(stackName, template1);
assertStackCreated(stackName);
assertThat(describeAutoScalingGroup(asgName), containsString("<Version>1</Version>"));
// DescribeChangeSet must include ASG with Action=Modify, Replacement=False
String csName = "cs-" + Long.toString(System.nanoTime(), 36);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", csName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template2)
.when()
.post("/")
.then()
.statusCode(200);
String csXml = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", csName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().body().asString();
List<Map<String, String>> resourceChanges = XmlParser.extractGroups(csXml, "ResourceChange");
Map<String, String> asgChange = resourceChanges.stream()
.filter(m -> "Asg".equals(m.get("LogicalResourceId")))
.findFirst()
.orElse(null);
assertNotNull(asgChange, "DescribeChangeSet must preview ASG update when LaunchTemplate version changes");
assertEquals("Modify", asgChange.get("Action"));
assertEquals("False", asgChange.get("Replacement"));
updateStack(stackName, template2);
String describe = describeStacks(stackName);
assertThat(describe, containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"));
// ASG must have updated to version 2 because Fn::GetAtt on LatestVersionNumber changed
assertThat(describeAutoScalingGroup(asgName), containsString("<Version>2</Version>"));
// Queue was unchanged and doesn't reference Lt, so it must not have received UPDATE_COMPLETE
String events = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackEvents")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().body().asString();
List<String> asgStatuses = XmlParser.extractGroups(events, "member").stream()
.filter(m -> "Asg".equals(m.get("LogicalResourceId")))
.map(m -> m.get("ResourceStatus"))
.toList();
assertTrue(asgStatuses.contains("UPDATE_COMPLETE"));
List<String> queueStatuses = XmlParser.extractGroups(events, "member").stream()
.filter(m -> "Queue".equals(m.get("LogicalResourceId")))
.map(m -> m.get("ResourceStatus"))
.toList();
assertTrue(queueStatuses.contains("CREATE_COMPLETE"));
assertFalse(queueStatuses.contains("UPDATE_COMPLETE"));
}
@Test
void asgRollsBackWhenLaterResourceFails() {
String suffix = Long.toString(System.nanoTime(), 36);
String ltName = "cfn-lt-rb-" + suffix;
String asgName = "cfn-asg-rb-" + suffix;
String stackName = "cfn-asg-rb-stack-" + suffix;
String queueName = "cfn-rb-q-" + suffix;
String template1 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"InstanceType": "t3.micro"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"DependsOn": ["Asg"],
"Properties": {"QueueName": "%s"}
}
}
}
""".formatted(ltName, asgName, queueName);
String template2 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "%s",
"LaunchTemplateData": {
"ImageId": "ami-87654321",
"InstanceType": "t3.small"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "%s",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"],
"DesiredCapacityType": "units",
"CapacityRebalance": true,
"MaxInstanceLifetime": 86400,
"DefaultInstanceWarmup": 300
}
},
"Queue": {
"Type": "AWS::SQS::Queue",
"DependsOn": ["Asg"],
"Properties": {
"QueueName": "%s",
"FifoQueue": true
}
}
}
}
""".formatted(ltName, asgName, queueName);
createStack(stackName, template1);
assertStackCreated(stackName);
assertThat(describeAutoScalingGroup(asgName), containsString("<Version>1</Version>"));
updateStack(stackName, template2);
String describe = describeStacks(stackName);
assertThat(describe, containsString("<StackStatus>UPDATE_ROLLBACK_COMPLETE</StackStatus>"));
// ASG must have rolled back to Version 1
String asg = describeAutoScalingGroup(asgName);
assertThat(asg, containsString("<Version>1</Version>"));
assertThat(asg, containsString("<DesiredCapacityType>units</DesiredCapacityType>"));
assertThat(asg, containsString("<CapacityRebalance>false</CapacityRebalance>"));
assertThat(asg, containsString("<MaxInstanceLifetime>0</MaxInstanceLifetime>"));
assertThat(asg, not(containsString("<DefaultInstanceWarmup>")));
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
@@ -8,10 +9,13 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Covers three ways {@code computeChangeSetChanges} previously misreported a change set's diff:
@@ -708,4 +712,168 @@ class CloudFormationChangeSetDiffIntegrationTest {
.body(containsString("<LogicalResourceId>Q</LogicalResourceId>"))
.body(containsString("<Action>Remove</Action>"));
}
@Test
void inPlaceAttributeChangePullsInDependentResourceInChangeSet() {
String stackName = "cs-diff-attr-change-stack";
stacksToDelete.add(stackName);
String template1 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "cs-diff-lt",
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"InstanceType": "t3.micro"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"DefaultAsg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-default-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "DefaultVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"UnchangedQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "cs-diff-unchanged-q"
}
}
}
}
""";
String template2 = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateName": "cs-diff-lt",
"LaunchTemplateData": {
"ImageId": "ami-87654321",
"InstanceType": "t3.small"
}
}
},
"Asg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"DefaultAsg": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"AutoScalingGroupName": "cs-diff-default-asg",
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "DefaultVersionNumber"]}
},
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"AvailabilityZones": ["us-east-1a"]
}
},
"UnchangedQueue": {
"Type": "AWS::SQS::Queue",
"Properties": {
"QueueName": "cs-diff-unchanged-q"
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template1)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "attr-change-cs")
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template2)
.when()
.post("/")
.then()
.statusCode(200);
String desc = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "attr-change-cs")
.when()
.post("/")
.then()
.statusCode(200)
.extract().body().asString();
List<Map<String, String>> changes = XmlParser.extractGroups(desc, "ResourceChange");
Map<String, String> ltChange = changes.stream()
.filter(m -> "Lt".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", ltChange.get("Action"));
assertEquals("False", ltChange.get("Replacement"));
Map<String, String> asgChange = changes.stream()
.filter(m -> "Asg".equals(m.get("LogicalResourceId")))
.findFirst()
.orElseThrow();
assertEquals("Modify", asgChange.get("Action"));
assertEquals("False", asgChange.get("Replacement"));
boolean unchangedDefaultDependentIncluded = changes.stream()
.anyMatch(m -> "DefaultAsg".equals(m.get("LogicalResourceId")));
assertFalse(unchangedDefaultDependentIncluded);
boolean unchangedQueueIncluded = changes.stream()
.anyMatch(m -> "UnchangedQueue".equals(m.get("LogicalResourceId")));
assertFalse(unchangedQueueIncluded);
}
}
@@ -466,6 +466,58 @@ class CloudFormationDeletionPolicyIntegrationTest {
}
}
@Test
void updateParentStackWithUnchangedNestedStackSucceedsEvenIfTemplateUrlUnavailable() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
String functionName = "cfn-nested-keep-func-" + suffix;
String bucketName = "nested-stack-templates-" + suffix;
String templateUrl = bucketName + "/child-lambda-keep.json";
String initialParentTemplate = """
{
"Resources": {
"ChildStack": {
"Type": "AWS::CloudFormation::Stack",
"Properties": { "TemplateURL": "http://localhost/%s" }
}
}
}
""".formatted(templateUrl);
String updatedParentTemplate = """
{
"Resources": {
"ChildStack": {
"Type": "AWS::CloudFormation::Stack",
"Properties": { "TemplateURL": "http://localhost/%s" }
}
},
"Outputs": {
"ParentOut": { "Value": "static" }
}
}
""".formatted(templateUrl);
String stackName = "parent-nested-keep-" + suffix;
given().header("Authorization", CUSTOM_AUTH).contentType("application/xml").body(EU_WEST_1_BUCKET)
.when().put("/" + bucketName).then().statusCode(200);
given().header("Authorization", CUSTOM_AUTH)
.contentType("application/json").body(nestedLambdaTemplate(functionName, 3))
.when().put("/" + templateUrl).then().statusCode(200);
String parentStackId = createStack(stackName, initialParentTemplate, CUSTOM_AUTH);
try {
awaitStackStatus(parentStackId, "CREATE_COMPLETE", CUSTOM_AUTH);
// Delete the template object from S3 so TemplateURL is no longer reachable
given().header("Authorization", CUSTOM_AUTH)
.when().delete("/" + templateUrl).then().statusCode(204);
// Parent update modifying only Outputs: unchanged nested stack is skipped, so missing TemplateURL doesn't fail update
updateStack(stackName, updatedParentTemplate, CUSTOM_AUTH);
awaitStackStatus(parentStackId, "UPDATE_COMPLETE", CUSTOM_AUTH);
} finally {
deleteStack(stackName);
}
}
@Test
void nestedStackWithNonEmptyBucketFailsDeletionOnUpdate_leavesChildAsDeleteFailedAndTracksInParent() throws InterruptedException {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -734,7 +734,7 @@ class CloudFormationEventBusIntegrationTest {
callEventBridge("AWSEvents.CreateEventBus",
"{\"Name\":\"" + busName + "\",\"Description\":\"external\"}", 200);
updateStack(stackName, template);
updateStack(stackName, eventBusOnlyTemplate(busName, "updating"));
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
@@ -8,9 +9,11 @@ import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -157,6 +160,7 @@ class CloudFormationNamedResourceIdenticalUpdateIntegrationTest {
boolean noUpdates = update.statusCode() == 400 && update.asString().contains("No updates");
if (!noUpdates) {
expect(stackName, "UPDATE_COMPLETE", "UPDATE");
assertNoResourceUpdateEvents(stackName);
}
cfn("DeleteStack", stackName, null);
@@ -194,4 +198,16 @@ class CloudFormationNamedResourceIdenticalUpdateIntegrationTest {
}
return reasons.isEmpty() ? "" : " | " + String.join(" | ", reasons);
}
private static void assertNoResourceUpdateEvents(String stackName) {
String eventXml = cfn("DescribeStackEvents", stackName, null).asString();
List<Map<String, String>> events = XmlParser.extractGroups(eventXml, "member");
for (Map<String, String> event : events) {
if (event.get("LogicalResourceId") != null
&& !stackName.equals(event.get("LogicalResourceId"))) {
assertFalse(event.get("ResourceStatus").startsWith("UPDATE_"),
"Identical update should not update resource " + event.get("LogicalResourceId"));
}
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
@@ -8,6 +9,8 @@ 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;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A create that fails rolls its resources back and leaves the stack in ROLLBACK_COMPLETE, which
@@ -166,6 +169,161 @@ class CloudFormationRollbackCompleteUpdateIntegrationTest {
deleteStack(stackName);
}
@Test
void failedUpdateDoesNotRollbackUnchangedResourcesWithoutRollbackSupport() {
assertFailedUpdateDoesNotRollbackUnchangedResources(false);
}
@Test
void failedExecutedChangeSetDoesNotRollbackUnchangedResourcesWithoutRollbackSupport() {
assertFailedUpdateDoesNotRollbackUnchangedResources(true);
}
private void assertFailedUpdateDoesNotRollbackUnchangedResources(boolean executeChangeSet) {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = (executeChangeSet ? "unchanged-resource-cs-" : "unchanged-resource-update-") + suffix;
String changeSetName = "failed-update-" + suffix;
String initialTemplate = """
{"Resources":{
"LogGroup":{"Type":"AWS::Logs::LogGroup","Properties":{"LogGroupName":"/cfn/rollback-%s"}},
"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"cfn-rollback-%s"}}
}}
""".formatted(suffix, suffix);
String failingTemplate = """
{"Resources":{
"LogGroup":{"Type":"AWS::Logs::LogGroup","Properties":{"LogGroupName":"/cfn/rollback-%s"}},
"Bucket":{"Type":"AWS::S3::Bucket","Properties":{"BucketName":"cfn-rollback-%s"}},
"ZFail":{"Type":"AWS::CloudFormation::Stack","Properties":{}}
}}
""".formatted(suffix, suffix);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when()
.post("/")
.then()
.statusCode(200);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
if (executeChangeSet) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", failingTemplate)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ExecuteChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName)
.when()
.post("/")
.then()
.statusCode(200);
} else {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", failingTemplate)
.when()
.post("/")
.then()
.statusCode(200);
}
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
given()
.head("/cfn-rollback-" + suffix)
.then()
.statusCode(200);
given()
.header("X-Amz-Target", "Logs_20140328.DescribeLogGroups")
.contentType("application/x-amz-json-1.1")
.body("{\"logGroupNamePrefix\":\"/cfn/rollback-" + suffix + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("/cfn/rollback-" + suffix));
deleteStack(stackName);
}
@Test
void failedUpdateRollsBackDependentQueueWhenReferencedQueueWasReplaced() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "rollback-sqs-update-" + suffix;
String oldDlq = "dlq-old-" + suffix;
String newDlq = "dlq-new-" + suffix;
String mainQueue = "main-" + suffix;
String initialTemplate = """
{"Resources":{
"DeadLetterQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}},
"MainQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s","RedrivePolicy":{"deadLetterTargetArn":{"Fn::GetAtt":["DeadLetterQueue","Arn"]},"maxReceiveCount":3}}}
}}
""".formatted(oldDlq, mainQueue);
String failingTemplate = """
{"Resources":{
"DeadLetterQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}},
"MainQueue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s","RedrivePolicy":{"deadLetterTargetArn":{"Fn::GetAtt":["DeadLetterQueue","Arn"]},"maxReceiveCount":3}}},
"ZFail":{"Type":"AWS::CloudFormation::Stack","Properties":{}}
}}
""".formatted(newDlq, mainQueue);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", initialTemplate)
.when().post("/").then().statusCode(200);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String initialResources = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().body().asString();
String mainQueueUrl = XmlParser.extractGroups(initialResources, "member").stream()
.filter(m -> "MainQueue".equals(m.get("LogicalResourceId")))
.map(m -> m.get("PhysicalResourceId")).findFirst().orElseThrow();
String oldDlqUrl = XmlParser.extractGroups(initialResources, "member").stream()
.filter(m -> "DeadLetterQueue".equals(m.get("LogicalResourceId")))
.map(m -> m.get("PhysicalResourceId")).findFirst().orElseThrow();
// Update with replaced DLQ and a failing resource
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", failingTemplate)
.when().post("/").then().statusCode(200);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
// Verify MainQueue still has the old DLQ in its redrive policy
String mainAttrs = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueAttributes")
.formParam("QueueUrl", mainQueueUrl)
.formParam("AttributeName.1", "RedrivePolicy")
.when().post("/").then().statusCode(200).extract().body().asString();
assertTrue(mainAttrs.contains(oldDlq));
deleteStack(stackName);
}
// ── Helpers ───────────────────────────────────────────────────────────────
/** Creates a stack whose only resource fails, so it settles in ROLLBACK_COMPLETE. */
@@ -17,8 +17,10 @@ import java.util.HashMap;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -26,6 +28,8 @@ import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -250,4 +254,88 @@ class AutoScalingGroupCfnProvisionerTest {
() -> provisioner.delete("AWS::AutoScaling::ScalingPolicy", "p", REGION));
verify(autoScaling, never()).deleteAutoScalingGroup(anyString(), anyString(), anyBoolean());
}
@Test
void rollbackUpdateRestoresSnapshotWhenPresent() {
AutoScalingGroup existing = group("my-asg");
existing.setLaunchTemplateId("lt-123");
existing.setLaunchTemplateVersion("1");
existing.setMinSize(1);
existing.setMaxSize(5);
existing.setDesiredCapacity(2);
existing.setAvailabilityZones(List.of("us-east-1a"));
when(autoScaling.describeAutoScalingGroups(eq(REGION), eq(List.of("my-asg"))))
.thenReturn(List.of(existing));
StackResource r = resource(GROUP, "Asg", "my-asg");
ObjectNode props = mapper.createObjectNode();
props.put("AutoScalingGroupName", "my-asg");
ObjectNode lt = props.putObject("LaunchTemplate");
lt.put("LaunchTemplateId", "lt-123");
lt.put("Version", "2");
props.put("MinSize", 3);
props.put("MaxSize", 8);
props.put("DesiredCapacity", 4);
props.putArray("AvailabilityZones").add("us-east-1a");
provisioner.provision(r, props, ctx("my-asg"));
String snapshot = r.getAttributes().get(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR);
assertTrue(snapshot != null && !snapshot.isBlank());
clearInvocations(autoScaling);
boolean rolledBack = provisioner.rollbackUpdate(r);
assertTrue(rolledBack);
ArgumentCaptor<Integer> minSizeCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<Integer> maxSizeCaptor = ArgumentCaptor.forClass(Integer.class);
ArgumentCaptor<String> versionCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<AsgOptionalFields> optionalFieldsCaptor = ArgumentCaptor.forClass(AsgOptionalFields.class);
verify(autoScaling).updateAutoScalingGroup(
eq(REGION),
eq("my-asg"),
isNull(),
eq("lt-123"),
isNull(),
versionCaptor.capture(),
isNull(),
minSizeCaptor.capture(),
maxSizeCaptor.capture(),
anyInt(),
anyInt(),
any(),
any(),
any(),
anyInt(),
any(),
optionalFieldsCaptor.capture()
);
assertEquals("1", versionCaptor.getValue());
assertEquals(1, minSizeCaptor.getValue());
assertEquals(5, maxSizeCaptor.getValue());
AsgOptionalFields optionalFields = optionalFieldsCaptor.getValue();
assertEquals("units", optionalFields.desiredCapacityType());
assertEquals(Boolean.FALSE, optionalFields.capacityRebalance());
assertEquals(0, optionalFields.maxInstanceLifetime());
assertEquals(AsgOptionalFields.DEFAULT_INSTANCE_WARMUP_REMOVAL_SENTINEL,
optionalFields.defaultInstanceWarmup());
// Subsequent rollback should return false since snapshot is spent
assertFalse(provisioner.rollbackUpdate(r));
}
@Test
void clearUpdateRemovesSnapshotAttribute() {
StackResource r = resource(GROUP, "Asg", "my-asg");
r.getAttributes().put(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR, "{\"name\":\"my-asg\"}");
provisioner.clearUpdate(r);
assertNull(r.getAttributes().get(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR));
}
}
@@ -24,8 +24,10 @@ import java.util.Set;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -205,6 +207,40 @@ class Ec2LaunchTemplateCfnProvisionerTest {
assertEquals(List.of("sg-1", "sg-2"), captor.getValue().getSecurityGroupIds());
}
@Test
void rollbackUpdateDeletesCreatedVersionAndRestoresAttributes() {
LaunchTemplate existing = template("lt-abc123");
existing.setLaunchTemplateName("my-lt");
existing.setLatestVersionNumber("1");
existing.setDefaultVersionNumber("1");
when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-abc123")), eq(List.of()), any()))
.thenReturn(List.of(existing));
LaunchTemplate updated = template("lt-abc123");
updated.setLaunchTemplateName("my-lt");
updated.setLatestVersionNumber("2");
updated.setDefaultVersionNumber("1");
when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-abc123"), isNull(), isNull(), any()))
.thenReturn(updated);
ObjectNode props = mapper.createObjectNode().put("LaunchTemplateName", "my-lt");
props.set("LaunchTemplateData", mapper.createObjectNode().put("ImageId", "ami-v2"));
StackResource r = resource("Lt");
r.setPhysicalId("lt-abc123");
provisioner.provision(r, props, ctx());
assertEquals("2", r.getAttributes().get("LatestVersionNumber"));
boolean rolledBack = provisioner.rollbackUpdate(r);
assertTrue(rolledBack);
verify(ec2).deleteLaunchTemplateVersion("us-east-1", "lt-abc123", "2");
assertEquals("1", r.getAttributes().get("LatestVersionNumber"));
assertEquals("1", r.getAttributes().get("DefaultVersionNumber"));
// Second rollback without snapshot should return false
assertFalse(provisioner.rollbackUpdate(r));
}
@Test
void provisionedUserDataIsDecodedForInstanceLaunch() {
when(ec2.createLaunchTemplate(any(), any(), any(), any())).thenReturn(template("lt-userdata"));