fix(cloudformation): CompositeAlarm and SSM Parameter take replacement from the engine (#9654)

AWS::CloudWatch::CompositeAlarm and AWS::SSM::Parameter now take their
name and their replacement decision from ProvisionContext.changes, and
leave the change-exempt list. An update that drops an SSM parameter's
Name now replaces it under a generated name, as on AWS, where it used
to keep the old name. The composite alarm no longer stores its own
explicit-name flag, since the engine sees a dropped AlarmName itself.
This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-29 16:45:57 -04:00
1 parent 5a3bff3939
commit f1b47125de
7 files changed
+99 -51

No files matched your search

@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.provisioners.ProvisionContext.NamedChange;
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.floci.aws.services.cloudwatch.metrics.model.CompositeAlarm;
import jakarta.enterprise.context.ApplicationScoped;
@@ -14,6 +15,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
@ApplicationScoped
@@ -21,7 +23,6 @@ public class CloudWatchCompositeAlarmCfnProvisioner implements CfnResourceProvis
private static final String TYPE = "AWS::CloudWatch::CompositeAlarm";
private static final String SNAPSHOT = "FlociCompositeAlarmSnapshot";
private static final String TAG_KEYS = "FlociCompositeAlarmTagKeys";
private static final String EXPLICIT_NAME = "FlociCompositeAlarmExplicitName";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final CloudWatchMetricsService service;
@@ -45,10 +46,9 @@ public class CloudWatchCompositeAlarmCfnProvisioner implements CfnResourceProvis
if (resource.getAttributes().containsKey(SNAPSHOT)) {
throw new AwsException("ResourceConflictException", "Alarm update cleanup is still pending", 400);
}
String explicit = ctx.resolveOptional(props, "AlarmName");
boolean removedName = explicit == null && "true".equals(resource.getAttributes().get(EXPLICIT_NAME));
String name = removedName ? ctx.generatePhysicalName(resource.getLogicalId(), 255, false)
: ctx.stablePhysicalName(explicit, resource.getLogicalId(), 255, false);
NamedChange change = ctx.changes(TYPE, props, ctx.resolveOptional(props, "AlarmName"),
resource.getLogicalId(), 255, false, UnaryOperator.identity());
String name = change.name();
CompositeAlarm alarm = new CompositeAlarm();
alarm.setAlarmName(name);
alarm.setAlarmDescription(ctx.resolveOptional(props, "AlarmDescription"));
@@ -60,7 +60,7 @@ public class CloudWatchCompositeAlarmCfnProvisioner implements CfnResourceProvis
actions(props, "InsufficientDataActions", ctx, alarm.getInsufficientDataActions());
Map<String, String> desiredTags = Map.copyOf(alarm.getTags());
Map<String, String> priorAttributes = Map.copyOf(resource.getAttributes());
boolean inPlace = ctx.reusesPriorEntity(name);
boolean inPlace = ctx.isUpdate() && !change.replaces();
String updateSnapshot = null;
if (inPlace) {
ObjectNode snapshot = MAPPER.createObjectNode().put("region", ctx.region()).put("name", name);
@@ -82,8 +82,7 @@ public class CloudWatchCompositeAlarmCfnProvisioner implements CfnResourceProvis
resource.getAttributes().put(TAG_KEYS, MAPPER.valueToTree(desiredTags.keySet()).toString());
resource.setPhysicalId(name);
resource.getAttributes().put("Arn", alarm.getAlarmArn());
resource.getAttributes().put(EXPLICIT_NAME, Boolean.toString(explicit != null));
ReplacementCleanup.record(resource, ctx, priorAttributes);
ReplacementCleanup.record(resource, ctx, priorAttributes, change.replaces());
}
private static void actions(JsonNode props, String field, ProvisionContext ctx, List<String> target) {
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.provisioners.ProvisionContext.NamedChange;
import io.floci.aws.services.ssm.SsmService;
import io.floci.aws.services.ssm.model.Parameter;
import jakarta.enterprise.context.ApplicationScoped;
@@ -36,6 +37,7 @@ import java.util.TreeSet;
@ApplicationScoped
public class SsmCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::SSM::Parameter";
private static final int PARAMETER_NAME_MAX_LENGTH = 2048;
private static final String SSM_TEMPLATE_TAG_KEYS_ATTR = "FlociSsmTemplateTagKeys";
private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -48,7 +50,7 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::SSM::Parameter");
return Set.of(TYPE);
}
@Override
@@ -61,8 +63,9 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner {
ReplacementCleanup.endRollbackRetry(r);
}
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
String name = SsmService.withoutSurroundingSpaces(ctx.stablePhysicalName(
ctx.resolveOptional(props, "Name"), r.getLogicalId(), PARAMETER_NAME_MAX_LENGTH, false));
NamedChange change = ctx.changes(TYPE, props, ctx.resolveOptional(props, "Name"),
r.getLogicalId(), PARAMETER_NAME_MAX_LENGTH, false, SsmService::withoutSurroundingSpaces);
String name = change.name();
String value = ctx.resolveOptional(props, "Value");
if (value == null) {
value = "";
@@ -74,7 +77,7 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner {
Map<String, String> tags = ctx.resolveTags(props, "Tags");
SsmService.validateTagKeys(tags);
// A dispatcher stub created nothing, so a parameter that takes over its id is a create.
if (ctx.reusesPriorEntity(name) && !CfnResourceDispatcher.isStub(name, attributesBefore)) {
if (ctx.isUpdate() && !change.replaces() && !CfnResourceDispatcher.isStub(name, attributesBefore)) {
snapshotBeforeUpdate(r, name, attributesBefore, tags.keySet(), ctx.region());
ssmService.putParameter(name, value, type, null, true, ctx.region());
reconcileTags(name, templateTagKeys(attributesBefore), tags, ctx.region());
@@ -93,7 +96,7 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner {
} else {
r.getAttributes().put(SSM_TEMPLATE_TAG_KEYS_ATTR, String.join(",", new TreeSet<>(tags.keySet())));
}
ReplacementCleanup.record(r, ctx, attributesBefore);
ReplacementCleanup.record(r, ctx, attributesBefore, change.replaces());
}
/**
@@ -137,11 +137,13 @@ class CfnReplacementIntegrationTest {
static Stream<Row> rows() {
String app = appConfigApplication("replacement-orders");
String iotName = json("'Name': {'Type': 'String', 'Default': 'repl-iot-@V@'}");
String nameParam = json("'Name': {'Type': 'String', 'Default': 'repl-name-@V@'}");
String iotThingName = json("'ThingName': {'Ref': 'Name'}");
String iotPolicy = json("'PolicyName': {'Ref': 'Name'},"
+ " 'PolicyDocument': {'Version': '2012-10-17',"
+ " 'Statement': [{'Effect': 'Allow', 'Action': 'iot:Connect', 'Resource': '*'}]}");
String alarmByRef = json("'AlarmRule': 'TRUE', 'AlarmName': {'Ref': 'Name'}");
String ssmByRef = json("'Type': 'String', 'Value': 'v', 'Name': {'Ref': 'Name'}");
return Stream.of(
createOnlyRow("AppConfig profile Type", app, "", PROFILE_TYPE,
PROFILE + "\"LocationUri\": \"hosted\", \"Type\": \"AWS.Freeform\"",
@@ -190,12 +192,22 @@ class CfnReplacementIntegrationTest {
"Subject", "True", true, null),
createOnlyRow("ECR repository RepositoryName removed", "", "", "AWS::ECR::Repository",
"\"RepositoryName\": \"repl-ecr-named\"", "", "True", false, null),
createOnlyRow("IoT thing ThingName", "", iotName, "AWS::IoT::Thing",
createOnlyRow("IoT thing ThingName", "", nameParam, "AWS::IoT::Thing",
iotThingName, iotThingName, "True", false, null),
createOnlyRow("IoT policy PolicyName", "", iotName, "AWS::IoT::Policy",
createOnlyRow("IoT policy PolicyName", "", nameParam, "AWS::IoT::Policy",
iotPolicy, iotPolicy, "True", false, null),
createOnlyRow("IoT thing ThingName removed", "", "", "AWS::IoT::Thing",
"\"ThingName\": \"repl-iot-named\"", "", "True", false, null),
createOnlyRow("CloudWatch composite alarm AlarmName", "", nameParam,
"AWS::CloudWatch::CompositeAlarm", alarmByRef, alarmByRef, "True", false, null),
createOnlyRow("CloudWatch composite alarm AlarmName removed", "", "", "AWS::CloudWatch::CompositeAlarm",
json("'AlarmRule': 'TRUE', 'AlarmName': 'repl-alarm-named'"), json("'AlarmRule': 'TRUE'"),
"True", false, null),
createOnlyRow("SSM parameter Name", "", nameParam, "AWS::SSM::Parameter",
ssmByRef, ssmByRef, "True", false, null),
createOnlyRow("SSM parameter Name removed", "", "", "AWS::SSM::Parameter",
json("'Type': 'String', 'Value': 'v', 'Name': '/repl/ssm-named'"),
json("'Type': 'String', 'Value': 'v'"), "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",
@@ -3,63 +3,78 @@ package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.floci.aws.services.cloudwatch.metrics.model.CompositeAlarm;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.floci.aws.services.cloudformation.provisioners.IotCfnProvisionerTestSupport.REGION;
import static io.floci.aws.services.cloudformation.provisioners.IotCfnProvisionerTestSupport.ctx;
import static io.floci.aws.services.cloudformation.provisioners.IotCfnProvisionerTestSupport.resource;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class CloudWatchCompositeAlarmCfnProvisionerTest {
@Test
void rejectedBackingUpdateDoesNotArmRollbackToDeleteAnUnmanagedReplacement() throws Exception {
private static final String TYPE = "AWS::CloudWatch::CompositeAlarm";
@ParameterizedTest
@CsvSource({
"kept, A metric alarm now has this name, 1",
"previous, CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename kept and update the stack again., 0"
})
void rejectedUpdateDoesNotArmRollback(String previousName, String expectedMessage, int writes) {
CloudWatchMetricsService service = mock(CloudWatchMetricsService.class);
CloudWatchCompositeAlarmCfnProvisioner provisioner = new CloudWatchCompositeAlarmCfnProvisioner(service);
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(call -> {
JsonNode node = call.getArgument(0);
return node == null || node.isMissingNode() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(call -> call.getArgument(0));
StackResource resource = new StackResource();
resource.setLogicalId("Alarm");
resource.setResourceType("AWS::CloudWatch::CompositeAlarm");
StackResource resource = resource(TYPE, "Alarm");
resource.setPhysicalId("kept");
resource.getAttributes().put("Arn", "prior-arn");
AwsException collision = new AwsException("ValidationError", "A metric alarm now has this name", 400);
doThrow(collision).when(service).putCompositeAlarm(any(), eq("us-east-1"), eq(true));
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "kept");
JsonNode props = new ObjectMapper().readTree("{\"AlarmName\":\"kept\",\"AlarmRule\":\"TRUE\"}");
assertSame(collision, assertThrows(AwsException.class, () -> provisioner.provision(resource, props, context)));
doThrow(collision).when(service).putCompositeAlarm(any(), eq(REGION), eq(true));
ObjectMapper mapper = new ObjectMapper();
JsonNode previous = mapper.createObjectNode().put("AlarmName", previousName).put("AlarmRule", "FALSE");
JsonNode props = mapper.createObjectNode().put("AlarmName", "kept").put("AlarmRule", "TRUE");
ProvisionContext context = ctx("kept", previous);
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(resource, props, context));
assertEquals("ValidationError", error.getErrorCode());
assertEquals(expectedMessage, error.getMessage());
assertFalse(provisioner.retainsFailedUpdateState(resource));
assertFalse(provisioner.rollbackUpdate(resource));
assertEquals("kept", resource.getPhysicalId());
assertEquals(Map.of("Arn", "prior-arn"), resource.getAttributes());
verify(service, times(writes)).putCompositeAlarm(any(), anyString(), anyBoolean());
verify(service, never()).deleteAlarms(any(), anyString());
}
@Test
void inPlaceUpdateRetriesPreviouslyDisplacedAlarmCleanup() throws Exception {
void inPlaceUpdateRetriesPreviouslyDisplacedAlarmCleanup() {
CloudWatchMetricsService service = mock(CloudWatchMetricsService.class);
doAnswer(call -> {
CompositeAlarm alarm = call.getArgument(0);
alarm.setAlarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:" + alarm.getAlarmName());
return null;
}).when(service).putCompositeAlarm(any(), eq(REGION), anyBoolean());
CloudWatchCompositeAlarmCfnProvisioner provisioner = new CloudWatchCompositeAlarmCfnProvisioner(service);
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(call -> {
JsonNode node = call.getArgument(0);
return node == null || node.isMissingNode() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(call -> call.getArgument(0));
StackResource resource = new StackResource();
resource.setLogicalId("Alarm");
resource.setResourceType("AWS::CloudWatch::CompositeAlarm");
resource.setPhysicalId("current");
ReplacementCleanup.record(resource,
new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "displaced"), Map.of());
StackResource resource = resource(TYPE, "Alarm");
resource.setPhysicalId("displaced");
ObjectMapper mapper = new ObjectMapper();
JsonNode previous = mapper.createObjectNode().put("AlarmName", "displaced").put("AlarmRule", "TRUE");
JsonNode renamed = mapper.createObjectNode().put("AlarmName", "current").put("AlarmRule", "TRUE");
provisioner.provision(resource, renamed, ctx("displaced", previous));
assertEquals("current", resource.getPhysicalId());
assertEquals("arn:aws:cloudwatch:us-east-1:000000000000:alarm:current", resource.getAttributes().get("Arn"));
verify(service).putCompositeAlarm(argThat(alarm -> "current".equals(alarm.getAlarmName())),
eq(REGION), eq(false));
doThrow(new IllegalStateException("delete unavailable"))
.doThrow(new IllegalStateException("delete still unavailable")).doNothing()
.when(service).deleteAlarms(List.of("displaced"), "us-east-1");
@@ -67,9 +82,10 @@ class CloudWatchCompositeAlarmCfnProvisionerTest {
provisioner.clearUpdate(resource);
assertEquals(Set.of("displaced"), ReplacementCleanup.owedPhysicalIds(resource));
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "000000000000", "stack", "current");
JsonNode props = new ObjectMapper().readTree("{\"AlarmName\":\"current\",\"AlarmRule\":\"TRUE\"}");
provisioner.provision(resource, props, context);
JsonNode props = mapper.createObjectNode().put("AlarmName", "current").put("AlarmRule", "FALSE");
provisioner.provision(resource, props, ctx("current", renamed));
verify(service).putCompositeAlarm(argThat(alarm -> "current".equals(alarm.getAlarmName())),
eq(REGION), eq(true));
assertTrue(provisioner.retainsFailedUpdateState(resource));
UpdateCleanupResult retry = provisioner.completeUpdate(resource);
assertFalse(retry.complete());
@@ -16,7 +16,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* What the three {@link IotCfnProvisioner} unit tests share: a mocked template engine that behaves
* What the {@link IotCfnProvisioner} and CompositeAlarm unit tests share: a mocked template engine that behaves
* like the real one for the shapes these templates use, and the resource and error factories.
*/
final class IotCfnProvisionerTestSupport {
@@ -230,6 +230,7 @@ class SsmCfnProvisionerTest {
order.verify(ssm).putParameter(NAME, "v", "String", null, true, REGION);
assertTrue(provisioner.retainsFailedUpdateState(r));
assertFalse(provisioner.hasReplacementUpdate(r));
assertEquals(NAME, r.getPhysicalId());
assertEquals(Map.of("Name", NAME, "Type", "String", "Value", "v", "Arn", ARN), visibleAttributes(r));
}
@@ -427,6 +428,25 @@ class SsmCfnProvisionerTest {
assertNull(provisioner.updateCleanupPhysicalId(r));
}
@Test
void aReplacingUpdateCannotKeepThePriorParameterName() {
StackResource r = parameter(NAME, null);
ProvisionContext current = updateCtx();
ProvisionContext update = new ProvisionContext(current.engine(), REGION, current.accountId(),
current.stackName(), NAME, event -> {}, props().put("Name", RENAMED).put("Value", "old"));
AwsException error = assertThrows(AwsException.class, () -> provisioner.provision(r, props(), update));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename " + NAME + " and update the stack again.", error.getMessage());
assertEquals(NAME, r.getPhysicalId());
verify(ssm, never()).putParameter(anyString(), anyString(), anyString(), any(), anyBoolean(), anyString());
verify(ssm, never()).putParameter(anyString(), anyString(), anyString(), any(), anyBoolean(), anyMap(),
anyString());
verify(ssm, never()).deleteParameter(anyString(), anyString());
}
@Test
void deleteToleratesOnlyAParameterThatIsAlreadyGone() {
doThrow(new AwsException("ParameterNotFound", "gone", 400)).when(ssm).deleteParameter(NAME, REGION);
@@ -55,7 +55,6 @@ AWS::CloudFront::PublicKey update not yet on the engine's changes (#6606)
AWS::CloudFront::ResponseHeadersPolicy update not yet on the engine's changes (#6606)
AWS::CloudTrail::Trail reads only droppedProperties; not yet on ctx.changes
AWS::CloudWatch::Alarm update not yet on the engine's changes (#6606)
AWS::CloudWatch::CompositeAlarm prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
AWS::CloudWatch::Dashboard prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
AWS::CodeBuild::Project wholesale request builder: the whole property node goes to the service
AWS::CodePipeline::CustomActionType wholesale request builder: the whole property node goes to the service
@@ -177,7 +176,6 @@ AWS::SES::EmailIdentity prior entity found by reusesPriorEntity; moves to the en
AWS::SES::ReceiptRule update not yet on the engine's changes (#6606)
AWS::SNS::TopicPolicy update not yet on the engine's changes (#6606)
AWS::SQS::QueuePolicy update not yet on the engine's changes (#6606)
AWS::SSM::Parameter prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
AWS::Scheduler::Schedule prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
AWS::Scheduler::ScheduleGroup prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
AWS::SecretsManager::Secret reads only droppedProperties; not yet on ctx.changes
1 AWS::ApiGateway::Account update not yet on the engine's changes (#6606)
55 AWS::CloudFront::ResponseHeadersPolicy update not yet on the engine's changes (#6606)
56 AWS::CloudTrail::Trail reads only droppedProperties; not yet on ctx.changes
57 AWS::CloudWatch::Alarm update not yet on the engine's changes (#6606)
AWS::CloudWatch::CompositeAlarm prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
58 AWS::CloudWatch::Dashboard prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
59 AWS::CodeBuild::Project wholesale request builder: the whole property node goes to the service
60 AWS::CodePipeline::CustomActionType wholesale request builder: the whole property node goes to the service
176 AWS::SES::ReceiptRule update not yet on the engine's changes (#6606)
177 AWS::SNS::TopicPolicy update not yet on the engine's changes (#6606)
178 AWS::SQS::QueuePolicy update not yet on the engine's changes (#6606)
AWS::SSM::Parameter prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
179 AWS::Scheduler::Schedule prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
180 AWS::Scheduler::ScheduleGroup prior entity found by reusesPriorEntity; moves to the engine's decision with the create-only work
181 AWS::SecretsManager::Secret reads only droppedProperties; not yet on ctx.changes