diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 6050bdb369..e146cbee69 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -1026,6 +1026,12 @@ Lambda. floci supports two shapes:
The handler's `Data` keys resolve through `Fn::GetAtt`, except keys that begin with `__Floci`. Floci
reserves that prefix for its own resource state and ignores such keys.
+An update whose handler returned a new `PhysicalResourceId` replaced the resource. Once the update
+commits, the stack enters `UPDATE_COMPLETE_CLEANUP_IN_PROGRESS` and the id it replaced gets a
+`Delete` carrying the properties it had, with no `OldResourceProperties`, as on AWS. A `Delete` the
+handler fails is tried three times, then reported as `DELETE_FAILED`, and the update still completes.
+Under `UpdateReplacePolicy: Retain` the replaced id gets no `Delete`.
+
A failed stack update rolls back a custom resource whose handler was sent an `Update`, as
CloudFormation does. This holds whether the handler applied the update and a later resource failed,
or the handler answered `FAILED` itself. The handler is sent a second `Update` under the same
diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java
index 7fd14d1785..09fa2743be 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java
@@ -170,12 +170,8 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
LOG.debugv("Custom resource {0} has no stored ServiceToken; skipping Delete", r.getLogicalId());
return;
}
- // A resource stashed before the stack id was recorded has none, and delete() has no stack.
- String stackId = stackIdOrMinted(r.getAttributes().get(CR_STACK_ID_ATTR), region,
- accountFromArn(serviceToken), "");
try {
- JsonNode response = invokeCustomResourceHandler(serviceToken, "Delete", r.getLogicalId(),
- r.getResourceType(), r.getPhysicalId(), resourceProperties, null, region, stackId);
+ JsonNode response = invokeDelete(r, r.getPhysicalId(), resourceProperties, region);
if (!"SUCCESS".equals(response.path("Status").asText("FAILED"))) {
LOG.warnv("Custom resource {0} Delete reported FAILED: {1}",
r.getLogicalId(), response.path("Reason").asText("(no reason given)"));
@@ -186,6 +182,65 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
}
}
+ private JsonNode invokeDelete(StackResource r, String physicalId, ObjectNode resourceProperties, String region) {
+ String serviceToken = r.getAttributes().get(CR_SERVICE_TOKEN_ATTR);
+ // A resource stashed before the stack id was recorded has none, and delete() has no stack.
+ String stackId = stackIdOrMinted(r.getAttributes().get(CR_STACK_ID_ATTR), region,
+ accountFromArn(serviceToken), "");
+ return invokeCustomResourceHandler(serviceToken, "Delete", r.getLogicalId(), r.getResourceType(),
+ physicalId, resourceProperties, null, region, stackId);
+ }
+
+ /** An update whose handler answered a new PhysicalResourceId replaced the resource. */
+ @Override
+ public boolean hasReplacementUpdate(StackResource resource) {
+ return replacedPhysicalId(resource) != null;
+ }
+
+ @Override
+ public String updateCleanupPhysicalId(StackResource resource) {
+ return "Retain".equals(resource.getUpdateReplacePolicy()) ? null : replacedPhysicalId(resource);
+ }
+
+ /**
+ * Sends the id a committed update replaced a Delete with the properties it had, as CloudFormation
+ * does in UPDATE_COMPLETE_CLEANUP_IN_PROGRESS. One attempt per call: the count lives on the
+ * snapshot, and a handler that keeps failing leaves the update committed.
+ */
+ @Override
+ public UpdateCleanupResult completeUpdate(StackResource resource) {
+ JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR);
+ if (snapshot == null) {
+ return UpdateCleanupResult.notApplicable();
+ }
+ String replacedId = updateCleanupPhysicalId(resource);
+ if (replacedId == null) {
+ return new UpdateCleanupResult(true, true, null, 0, null);
+ }
+ try {
+ requireSuccess(invokeDelete(resource, replacedId, (ObjectNode) snapshot.get("properties"),
+ snapshot.path("region").asText()));
+ return new UpdateCleanupResult(true, true, replacedId, 0, null);
+ } catch (AwsException e) {
+ int attempts = snapshot.path("cleanupAttempts").asInt() + 1;
+ ((ObjectNode) snapshot).put("cleanupAttempts", attempts);
+ resource.getAttributes().put(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
+ return new UpdateCleanupResult(true, false, replacedId, attempts, e.getMessage());
+ }
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ resource.getAttributes().remove(CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR);
+ }
+
+ /** The physical id the update replaced, or null when there is no update or it kept its id. */
+ private static String replacedPhysicalId(StackResource resource) {
+ JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.CUSTOM_RESOURCE_UPDATE_SNAPSHOT_ATTR);
+ String priorPhysicalId = snapshot == null ? null : CfnRollback.snapshotText(snapshot, "physicalId");
+ return priorPhysicalId == null || priorPhysicalId.equals(resource.getPhysicalId()) ? null : priorPhysicalId;
+ }
+
@Override
public boolean rollbackUpdate(StackResource resource) {
return rollbackUpdate(resource, event -> { });
diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCustomResourceRollbackIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCustomResourceRollbackIntegrationTest.java
index 44f1fb5e2f..60f34287cd 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCustomResourceRollbackIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCustomResourceRollbackIntegrationTest.java
@@ -25,7 +25,9 @@ import static org.junit.jupiter.api.Assertions.fail;
/**
* A stack update that changes a custom resource and then fails on a later resource rolls the custom
* resource back the way CloudFormation does: the handler is sent a second {@code Update} carrying
- * the old properties, so it can undo what the first one applied.
+ * the old properties, so it can undo what the first one applied. A committed update whose handler
+ * answered a new PhysicalResourceId replaced the resource, and its cleanup phase sends the old id a
+ * {@code Delete}.
*
*
The ServiceToken Lambda is mocked, as in {@code CloudFormationCustomResourceStackIdIntegrationTest},
* so no Docker is needed. The mock answers like a real handler, by a PUT of its result to the
@@ -138,6 +140,63 @@ class CloudFormationCustomResourceRollbackIntegrationTest {
assertEquals(physicalId, probe.events().get(3).get("PhysicalResourceId").asText());
}
+ @Test
+ void committedReplacementSendsTheReplacedIdADeleteInTheCleanupPhase() throws InterruptedException {
+ probe.physicalId(event -> "probe-" + event.get("ResourceProperties").get("Revision").asText());
+ String stackName = "cr-replaced-" + Long.toString(System.nanoTime(), 36);
+ String stackId = createStack(stackName, template("1", false));
+ awaitStackStatus(stackId, "CREATE_COMPLETE");
+
+ updateStack(stackName, template("2", false));
+ awaitStackStatus(stackId, "UPDATE_COMPLETE");
+
+ assertEquals(List.of("Create:1", "Update:2", "Delete:1"), requests());
+ JsonNode delete = probe.events().get(2);
+ assertProperties(delete, "1", null);
+ assertEquals("probe-1", delete.get("PhysicalResourceId").asText());
+ assertEquals(stackId, delete.get("StackId").asText());
+ assertEquals("probe-2", physicalIdUnauthenticated(stackName, "Probe"));
+ String events = describeStackEvents(stackId);
+ assertTrue(events.contains("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"), events);
+ List probeEvents = probeEvents(stackId);
+ assertEquals(List.of("UPDATE_IN_PROGRESS:probe-1", "UPDATE_COMPLETE:probe-2",
+ "DELETE_IN_PROGRESS:probe-1", "DELETE_COMPLETE:probe-1"),
+ probeEvents.subList(probeEvents.size() - 4, probeEvents.size()));
+ }
+
+ @Test
+ void replacedIdWhoseDeleteFailsDoesNotFailTheUpdate() throws InterruptedException {
+ probe.physicalId(event -> "probe-" + event.get("ResourceProperties").get("Revision").asText());
+ failOn("Delete:1", "still in use");
+ String stackName = "cr-replaced-failed-" + Long.toString(System.nanoTime(), 36);
+ String stackId = createStack(stackName, template("1", false));
+ awaitStackStatus(stackId, "CREATE_COMPLETE");
+
+ updateStack(stackName, template("2", false));
+ awaitStackStatus(stackId, "UPDATE_COMPLETE");
+
+ assertEquals(List.of("Create:1", "Update:2", "Delete:1", "Delete:1", "Delete:1"), requests());
+ List