fix(cloudformation): an update that adds a create-only value replaces the resource (#8471)

This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-16 15:00:11 -04:00
1 parent 95fa805590
commit b2def4f421
6 files changed
+124 -39

No files matched your search

@@ -75,9 +75,8 @@ public final class CfnCreateOnlyProperties {
/**
* True when the value at any create-only pointer of the type differs between the old and the new
* properties. A top-level name compares the whole value (a value added where none existed is not a
* change, as before). A nested pointer {@code A/B/C} compares the values at that path: present on
* one side only is a change, absent on both is not. A {@code *} segment compares every array
* properties. A pointer compares the values at that path, a top-level name included: a value added, removed or
* changed is a change, absent on both sides is not. A {@code *} segment compares every array
* element's subtree.
*/
public static boolean createOnlyValueChanged(String resourceType, JsonNode oldProps, JsonNode newProps) {
@@ -92,7 +91,7 @@ public final class CfnCreateOnlyProperties {
/** {@link #createOnlyValueChanged} for one pointer of the type's table. */
public static boolean createOnlyPointerChanged(String pointer, JsonNode oldProps, JsonNode newProps) {
String[] segments = pointer.split("/");
return pointerChanged(oldProps, newProps, segments, 0, segments.length == 1);
return pointerChanged(oldProps, newProps, segments, 0);
}
/** The subtrees of the properties that sit under one create-only pointer. */
@@ -111,12 +110,8 @@ public final class CfnCreateOnlyProperties {
return out;
}
private static boolean pointerChanged(JsonNode oldNode, JsonNode newNode, String[] segments, int index,
boolean topLevel) {
private static boolean pointerChanged(JsonNode oldNode, JsonNode newNode, String[] segments, int index) {
if (index == segments.length) {
if (topLevel) {
return oldNode != null && !oldNode.equals(newNode);
}
return oldNode == null ? newNode != null : !oldNode.equals(newNode);
}
if (oldNode == null && newNode == null) {
@@ -135,7 +130,7 @@ public final class CfnCreateOnlyProperties {
for (int i = 0; i < size; i++) {
JsonNode o = oldNode != null && oldNode.isArray() ? oldNode.get(i) : null;
JsonNode n = newNode != null && newNode.isArray() ? newNode.get(i) : null;
if (pointerChanged(o, n, segments, index + 1, false)) {
if (pointerChanged(o, n, segments, index + 1)) {
return true;
}
}
@@ -143,7 +138,7 @@ public final class CfnCreateOnlyProperties {
}
JsonNode o = oldNode != null && oldNode.isObject() ? oldNode.get(segments[index]) : null;
JsonNode n = newNode != null && newNode.isObject() ? newNode.get(segments[index]) : null;
return pointerChanged(o, n, segments, index + 1, segments.length == 1);
return pointerChanged(o, n, segments, index + 1);
}
private static void collect(JsonNode node, String[] segments, int index, List<JsonNode> out) {
@@ -1520,8 +1520,10 @@ public class CloudFormationService implements ResourceProvider {
}
boolean decide(String resourceType, String logicalId, JsonNode oldDef, JsonNode newDef) {
JsonNode oldProps = oldDef.path("Properties");
JsonNode newProps = newDef.path("Properties");
JsonNode oldBlock = withoutMissing(oldDef.path("Properties"), newDef.path("Properties"));
JsonNode newBlock = withoutMissing(newDef.path("Properties"), oldDef.path("Properties"));
JsonNode oldProps = withoutNoValue(logicalId, oldBlock, oldParams, oldConditions, oldTemplate);
JsonNode newProps = withoutNoValue(logicalId, newBlock, newParams, newConditions, newTemplate);
boolean asWritten = requiresReplacement(resourceType, oldProps, newProps, changedParams,
changedConditions);
if (!CfnCreateOnlyProperties.hasSchema(resourceType) || !oldProps.isObject() || !newProps.isObject()) {
@@ -1540,6 +1542,30 @@ public class CloudFormationService implements ResourceProvider {
return resolved;
}
/** The block as written with every AWS::NoValue member left out, by the side's own conditions. */
private JsonNode withoutNoValue(String logicalId, JsonNode block, Map<String, String> params,
Map<String, Boolean> conditions, JsonNode template) {
try {
JsonNode omitted = engineOver(ownerAccount(stack), params, Map.of(), Map.of(), conditions, template)
.omitNoValue(block);
return omitted.isMissingNode() ? block : omitted;
} catch (RuntimeException e) {
if (warned.add(logicalId)) {
LOG.warnv("AWS::NoValue members of {0} could not be left out for the diff; the preview "
+ "compares the block as written: {1}", logicalId, e.getMessage());
}
return block;
}
}
/**
* A missing Properties block counts as an empty one when the other side has a block, as adding or
* dropping every property in it does.
*/
private JsonNode withoutMissing(JsonNode block, JsonNode other) {
return block.isMissingNode() && other.isObject() ? objectMapper.createObjectNode() : block;
}
private static boolean holdsDynamicReference(JsonNode subtree) {
return CfnDynamicReferences.holdsDynamicReference(subtree.toString());
}
@@ -1557,6 +1583,9 @@ public class CloudFormationService implements ResourceProvider {
}
JsonNode before = compared[0].path(logicalId).path("Properties");
JsonNode after = compared[1].path(logicalId).path("Properties");
JsonNode comparedBefore = withoutMissing(before, after);
after = withoutMissing(after, before);
before = comparedBefore;
if (!before.isObject() || !after.isObject()) {
return false;
}
@@ -1633,9 +1662,9 @@ public class CloudFormationService implements ResourceProvider {
String accountId = ownerAccount(stack);
return CfnCreateOnlyProperties.createOnlyValueChanged(resourceType,
engineOver(accountId, oldParams, physicalIds, attributes, oldConditions, oldTemplate)
.resolveNode(oldProps),
.resolveNodeOmittingNoValue(oldProps),
engineOver(accountId, newParams, physicalIds, attributes, newConditions, newTemplate)
.resolveNode(newProps));
.resolveNodeOmittingNoValue(newProps));
} catch (RuntimeException e) {
if (warned.add(logicalId)) {
LOG.warnv("Create-only values of {0} ({1}) could not be resolved for the diff; "
@@ -1681,7 +1710,8 @@ public class CloudFormationService implements ResourceProvider {
}
try {
return CfnCreateOnlyProperties.createOnlyValueChanged(resourceType,
previous.resolveNode(priorProps), current.resolveNode(props));
previous.resolveNodeOmittingNoValue(priorProps),
current.resolveNodeOmittingNoValue(props));
} catch (RuntimeException e) {
LOG.warnv("Resolved create-only values of {0} ({1}) could not be compared; the update adds no "
+ "replacement beyond the engine's own decision: {2}", logicalId, resourceType, e.getMessage());
@@ -1691,16 +1721,11 @@ public class CloudFormationService implements ResourceProvider {
private boolean requiresReplacement(String resourceType, JsonNode oldProps, JsonNode newProps,
Set<String> changedParams, Set<String> changedConditions) {
if (oldProps == null || oldProps.isMissingNode()) {
// The caller reads a dropped or an added Properties block as an empty one, so only a resource
// without a block on either side reaches here with a missing node.
if (oldProps == null || oldProps.isMissingNode() || newProps == null || newProps.isMissingNode()) {
return false;
}
if (newProps == null || newProps.isMissingNode()) {
// A dropped Properties block removes every property in it, as removing them one by one does.
if (!oldProps.isObject()) {
return false;
}
newProps = objectMapper.createObjectNode();
}
if (CfnCreateOnlyProperties.hasSchema(resourceType)) {
// The registry table names the exact pointers; only a value at one of them replaces.
if (CfnCreateOnlyProperties.createOnlyValueChanged(resourceType, oldProps, newProps)) {
@@ -1718,10 +1743,10 @@ public class CloudFormationService implements ResourceProvider {
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field)) {
JsonNode oldVal = oldProps.get(field);
JsonNode newVal = newProps.get(field);
if (oldVal != null && !oldVal.equals(newVal)) {
if (!newVal.equals(oldVal)) {
return true;
}
if (newVal != null && (referencesAnyParameter(newVal, changedParams) || referencesAnyCondition(newVal, changedConditions))) {
if (referencesAnyParameter(newVal, changedParams) || referencesAnyCondition(newVal, changedConditions)) {
return true;
}
}
@@ -159,13 +159,13 @@ class CfnReplacementIntegrationTest {
SUBNET_GROUP_REPLACED,
createOnlyRow("SQS queue explicit QueueName removed", "", "", SQS_TYPE,
"\"QueueName\": \"repl-q-removed\"", "\"VisibilityTimeout\": 30", "True", false, null),
new Row("SQS queue QueueName dropped by Fn::If choosing AWS::NoValue",
new Row("SQS queue QueueName dropped by Fn::If choosing AWS::NoValue, beside an updatable change",
namedByCondition(SQS_TYPE, "QueueName", "repl-q-if", "[\"x\", \"x\"]"),
namedByCondition(SQS_TYPE, "QueueName", "repl-q-if", "[\"x\", \"y\"]"),
"Subject", "True", true, null),
createOnlyRow("S3 bucket explicit BucketName removed", "", "", S3_TYPE,
"\"BucketName\": \"repl-s3-removed\"", "", "True", false, null),
new Row("S3 bucket BucketName dropped by Fn::If choosing AWS::NoValue",
new Row("S3 bucket BucketName dropped by Fn::If choosing AWS::NoValue, beside an updatable change",
namedByCondition(S3_TYPE, "BucketName", "repl-s3-if", "[\"x\", \"x\"]"),
namedByCondition(S3_TYPE, "BucketName", "repl-s3-if", "[\"x\", \"y\"]"),
"Subject", "True", true, null),
@@ -178,6 +178,45 @@ class CfnReplacementIntegrationTest {
"\"RepositoryName\": \"repl-ecr-named\"", "", "True", false, null),
createOnlyRow("DynamoDB table explicit TableName removed", "", "", "AWS::DynamoDB::Table",
DDB_KEYS + ", \"TableName\": \"repl-ddb-removed\"", DDB_KEYS, "True", false, null),
new Row("log group given a Properties block that sets its name",
"{\"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\"}}}",
"{\"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"LogGroupName\": \"repl-added-properties\"}}}}",
"Subject", "True", true, null),
new Row("log group given a Properties block with only an updatable property",
"{\"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\"}}}",
"{\"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"RetentionInDays\": 7}}}}",
"Subject", "False", false, null),
new Row("log group whose existing Properties block gains its name",
"{\"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"RetentionInDays\": 7}}}}",
"{\"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"RetentionInDays\": 7,"
+ " \"LogGroupName\": \"repl-added-name\"}}}}",
"Subject", "True", true, null),
new Row("log group whose added LogGroupName is an Fn::If choosing AWS::NoValue, beside an updatable change",
"{\"Conditions\": {\"Named\": {\"Fn::Equals\": [\"x\", \"y\"]}},"
+ " \"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"RetentionInDays\": 7}}}}",
"{\"Conditions\": {\"Named\": {\"Fn::Equals\": [\"x\", \"y\"]}},"
+ " \"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"RetentionInDays\": 14,"
+ " \"LogGroupName\": {\"Fn::If\": [\"Named\", \"repl-if-novalue\","
+ " {\"Ref\": \"AWS::NoValue\"}]}}}}}",
"Subject", "False", false, null),
new Row("log group whose added LogGroupName is an Fn::If choosing AWS::NoValue while a tag reads another stack's output",
"{\"Conditions\": {\"Named\": {\"Fn::Equals\": [\"x\", \"y\"]}},"
+ " \"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"RetentionInDays\": 7}}}}",
"{\"Conditions\": {\"Named\": {\"Fn::Equals\": [\"x\", \"y\"]}},"
+ " \"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\","
+ " \"Properties\": {\"RetentionInDays\": 14,"
+ " \"Tags\": [{\"Key\": \"source\", \"Value\": {\"Fn::GetStackOutput\":"
+ " {\"StackName\": \"" + OUTPUT_SOURCE + "\", \"OutputName\": \"Out\"}}}],"
+ " \"LogGroupName\": {\"Fn::If\": [\"Named\", \"repl-if-output\","
+ " {\"Ref\": \"AWS::NoValue\"}]}}}}}",
"Subject", "False", false, stack -> createOutputSource()),
new Row("deployed parameter renamed, same value",
locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"),
locationStack(stringParameter("NameB", HOSTED), "", REF_B, "e"),
@@ -193,6 +232,7 @@ class CfnReplacementIntegrationTest {
"Subject", "True", true, null));
}
private static final String OUTPUT_SOURCE = "repl-output-source";
private static final String HOSTED = "hosted";
private static final String REF_A = "{\"Ref\": \"NameA\"}";
private static final String REF_B = "{\"Ref\": \"NameB\"}";
@@ -208,6 +248,9 @@ class CfnReplacementIntegrationTest {
CloudFormationClient.builder(), "test", Region.US_EAST_1)) {
CfnStackWaits.createStack(client, stack, row.before(), "CREATE_COMPLETE");
String before = physicalId(client, stack, "Subject");
if (row.afterCreate() != null) {
row.afterCreate().accept(stack);
}
createUpdateChangeSet(client, stack, "change", row.after());
assertEquals(List.of(row.preview()), replacement(client, stack, "change", "Subject"), row.label());
@@ -226,6 +269,18 @@ class CfnReplacementIntegrationTest {
}
} finally {
CfnStackWaits.deleteStack(stack);
if (row.afterCreate() != null) {
CfnStackWaits.deleteStack(OUTPUT_SOURCE);
}
}
}
private static void createOutputSource() {
try (CloudFormationClient client = AwsTestClients.create(
CloudFormationClient.builder(), "test", Region.US_EAST_1)) {
CfnStackWaits.createStack(client, OUTPUT_SOURCE, "{\"Resources\": {\"Source\": {\"Type\":"
+ " \"AWS::SSM::Parameter\", \"Properties\": {\"Type\": \"String\", \"Value\": \"v\"}}},"
+ " \"Outputs\": {\"Out\": {\"Value\": \"output-value\"}}}", "CREATE_COMPLETE");
}
}
@@ -19,6 +19,7 @@ import java.time.Duration;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudFormationSesConfigurationSetIntegrationTest {
@@ -97,11 +98,20 @@ class CloudFormationSesConfigurationSetIntegrationTest {
}
@Test
void addingTheExistingGeneratedNameRollsBackAfterADependentResourceFails() {
void addingTheExistingGeneratedNameIsRefusedAndRollsBack() {
String generated = createUnnamedConfigurationSet();
updateWithDependentFailure(generated);
String updatedTemplate = """
{
"Resources": {
"ConfigurationSet": {"Type": "AWS::SES::ConfigurationSet", "Properties": {"Name": "%s"}}
},
"Outputs": {"ConfigurationSetRef": {"Value": {"Ref": "ConfigurationSet"}}}
}
""".formatted(generated);
cfn.updateStack(request -> request.stackName(stackName).templateBody(updatedTemplate));
Stack rolledBack = CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_ROLLBACK_COMPLETE");
assertTrue(CfnStackWaits.failedResourceReason(stackName).contains("custom-named resource requires"));
assertEquals(generated, rolledBack.outputs().getFirst().outputValue());
assertEquals(generated, configurationSets.get(generated, "us-east-1").getName());
}
@@ -16,8 +16,10 @@ class PropertyChangesReplacementTest {
}
@Test
void aChangedOrDroppedCreateOnlyPropertyReplaces() throws Exception {
void aChangedAddedOrDroppedCreateOnlyPropertyReplaces() throws Exception {
assertTrue(between("{\"Name\":\"a.example.\"}", "{\"Name\":\"b.example.\"}").requiresReplacement());
assertTrue(between("{\"Name\":\"a.example.\"}",
"{\"Name\":\"a.example.\",\"DelegationSetId\":\"N1\"}").requiresReplacement());
assertTrue(between("{\"Name\":\"a.example.\",\"DelegationSetId\":\"N1\"}",
"{\"Name\":\"a.example.\"}").requiresReplacement());
assertTrue(PropertyChanges.between(TYPE, true, MAPPER.readTree("{\"Name\":\"a.example.\"}"), null)
@@ -25,9 +27,7 @@ class PropertyChangesReplacementTest {
}
@Test
void anAddedOrNonCreateOnlyChangeDoesNotReplace() throws Exception {
assertFalse(between("{\"Name\":\"a.example.\"}",
"{\"Name\":\"a.example.\",\"DelegationSetId\":\"N1\"}").requiresReplacement());
void aNonCreateOnlyChangeDoesNotReplace() throws Exception {
assertFalse(between("{\"Name\":\"a.example.\",\"HostedZoneConfig\":{\"Comment\":\"x\"}}",
"{\"Name\":\"a.example.\",\"HostedZoneConfig\":{\"Comment\":\"y\"}}").requiresReplacement());
}
@@ -608,17 +608,17 @@ class SesCfnProvisionerTest {
}
@Test
void declaringTheExistingGeneratedNameNeedsNoReplacementOrRollbackWork() throws Exception {
void declaringTheExistingGeneratedNameIsACustomNameThatCannotBeReplaced() throws Exception {
StackResource resource = configurationSetResource(null);
JsonNode previous = props("{}");
provisioner.provision(resource, previous, context(null));
String generated = resource.getPhysicalId();
provisioner.provision(resource, props("{\"Name\":\"" + generated + "\"}"),
configurationSetUpdateContext(generated, previous));
AwsException error = assertThrows(AwsException.class,
() -> provisioner.provision(resource, props("{\"Name\":\"" + generated + "\"}"),
configurationSetUpdateContext(generated, previous)));
assertFalse(provisioner.hasReplacementUpdate(resource));
assertTrue(provisioner.rollbackUpdate(resource));
assertTrue(error.getMessage().contains("custom-named resource requires replacing"));
assertEquals(generated, resource.getPhysicalId());
verify(ses, never()).deleteConfigurationSet(any(), any());
}