fix(cloudformation): update an API Gateway stage in place and delete it with the stack (#8851)

An AWS::ApiGateway::Stage was created again on every stack update, dropping stage variables set outside the stack. It is now patched in place for DeploymentId and Description and restored on rollback. A StageName change replaces it, and a RestApiId change moves it: the stage left on the old API is deleted through the lifecycle records once the update commits, with its delete events, unless UpdateReplacePolicy: Retain keeps it. A new stage whose name is already taken on the API is refused with "Stage already exists", and the stage is deleted with the stack.
This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-19 10:36:39 -04:00
1 parent 8db9542226
commit 5a0529ba31
7 files changed
+379 -14

No files matched your search

@@ -1111,7 +1111,8 @@ public class ApiGatewayService implements ResourceProvider, Resettable {
if (!"replace" .equals(opType) && !"add" .equals(opType)) continue;
if ("/description" .equals(path)) {
stage.setDescription(value);
// UpdateStage has no remove for the description, so an empty value clears it.
stage.setDescription(value == null || value.isEmpty() ? null : value);
} else if ("/deploymentId" .equals(path)) {
stage.setDeploymentId(value);
} else if ("/tracingEnabled" .equals(path)) {
@@ -1136,6 +1137,18 @@ public class ApiGatewayService implements ResourceProvider, Resettable {
return stage;
}
/**
* Writes back the deployment id and description of a stage as a stack update's snapshot held
* them, a null description included, which a patch cannot express. For the stack rollback only.
*/
public void restoreStage(String region, String apiId, Stage snapshot) {
Stage stage = getStage(region, apiId, snapshot.getStageName());
stage.setDeploymentId(snapshot.getDeploymentId());
stage.setDescription(snapshot.getDescription());
stage.setLastUpdatedDate(System.currentTimeMillis() / 1000L);
stageStore.put(stageKey(region, apiId, snapshot.getStageName()), stage);
}
private static final List<String> METHOD_SETTING_KEYS = List.of(
"metrics/enabled",
"logging/loglevel",
@@ -60,6 +60,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
/** Where a {@link Location} names an authorizer, in place of the HTTP method. */
private static final String AUTHORIZER_KIND = "AUTHORIZER";
private static final String AUTHORIZER_SNAPSHOT_ATTR = CfnRollback.APIGW_AUTHORIZER_UPDATE_SNAPSHOT_ATTR;
/** Where a {@link Location} names a stage: the stage name in place of the resource id. */
private static final String STAGE_KIND = "STAGE";
private static final String STAGE_SNAPSHOT_ATTR = CfnRollback.APIGW_STAGE_UPDATE_SNAPSHOT_ATTR;
/** The stage a RestApiId change left on the old API, owed a delete once the update commits. */
private static final String STAGE_CLEANUP_ATTR = "__FlociApiGatewayStageCleanup";
private static final String VPC_ENDPOINT_IDS_PATH = "/endpointConfiguration/vpcEndpointIds";
private final ApiGatewayService apiGatewayService;
@@ -94,12 +99,13 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
/**
* A Resource or Method can sit on an API outside the stack, where no RestApi delete cascades to
* it, so each removes its own entity, found through the location recorded for it. Deployment
* and Stage have no delete of their own yet. An Authorizer is deleted at the API recorded for it; one
* it, so each removes its own entity, found through the location recorded for it. A Deployment
* has no delete of its own yet. An Authorizer or Stage is deleted at the API recorded for it; one
* created before its location was recorded is not deleted.
*/
@Override
public void delete(StackResource resource, String region) {
deletePendingStage(resource);
deleteEntity(resource, resource.getPhysicalId(), region);
}
@@ -133,7 +139,10 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
}
private void deleteLocation(String physicalId, Location location, String region) {
if (location.authorizer()) {
if (location.stage()) {
CfnDeletes.safeDelete("API stage", physicalId, () -> apiGatewayService.deleteStage(
region, location.restApiId(), location.resourceId()), "NotFoundException");
} else if (location.authorizer()) {
CfnDeletes.safeDelete("API authorizer", physicalId, () -> apiGatewayService.deleteAuthorizer(
region, location.restApiId(), location.resourceId()), "NotFoundException");
} else if (location.httpMethod() == null) {
@@ -162,12 +171,31 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
return resource.getAttributes().containsKey(STAGE_CLEANUP_ATTR) || ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
ObjectNode movedStage = readStageCleanup(resource);
return movedStage != null ? CfnLifecycleRecords.cleanupPhysicalId(resource, movedStage)
: ReplacementCleanup.cleanupPhysicalId(resource);
}
private void deleteMovedStage(ObjectNode record) {
String name = record.path("name").asText();
deleteLocation(name, new Location(record.path("restApiId").asText(), name, STAGE_KIND),
record.path("region").asText());
}
/** Deletes the old stage a failed or unfinished cleanup still owes, {@code Retain} honoured. */
private void deletePendingStage(StackResource resource) {
CfnLifecycleRecords.deletePending(resource, STAGE_CLEANUP_ATTR, readStageCleanup(resource), true,
this::deleteMovedStage);
}
private static ObjectNode readStageCleanup(StackResource resource) {
return CfnLifecycleRecords.read(resource, STAGE_CLEANUP_ATTR,
"Invalid API Gateway stage cleanup record", "API Gateway stage cleanup record must be an object");
}
/**
@@ -177,14 +205,23 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR);
return ReplacementCleanup.complete(resource,
ObjectNode pendingStage = readStageCleanup(resource);
UpdateCleanupResult movedStage = pendingStage == null ? UpdateCleanupResult.notApplicable()
: CfnLifecycleRecords.completePending(resource, STAGE_CLEANUP_ATTR, STAGE_SNAPSHOT_ATTR,
pendingStage, true, this::deleteMovedStage);
if (!resource.getAttributes().containsKey(STAGE_CLEANUP_ATTR)) {
resource.getAttributes().remove(STAGE_SNAPSHOT_ATTR);
}
UpdateCleanupResult displaced = ReplacementCleanup.complete(resource,
(type, physicalId, region) -> deleteEntity(resource, physicalId, region));
return movedStage.applicable() && (!displaced.applicable() || displaced.complete()) ? movedStage : displaced;
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.REST_API_UPDATE_SNAPSHOT_ATTR);
resource.getAttributes().remove(AUTHORIZER_SNAPSHOT_ATTR);
resource.getAttributes().remove(STAGE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
@@ -204,9 +241,10 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Puts a replaced RestApi, Resource, Method or Authorizer back when a later resource fails the
* Puts a replaced RestApi, Resource, Method, Authorizer or Stage back when a later resource fails the
* update, a RestApi patched in place back to its snapshot, and an Authorizer patched in place, or
* created because the prior was gone, back through its own snapshot. Without a replacement, a Resource update
* created because the prior was gone, back through its own snapshot, and the same for a Stage.
* Without a replacement, a Resource update
* changed nothing, since all its properties are createOnly, so there is nothing to undo. A
* Method the update kept was written in place, with no snapshot to put back.
*/
@@ -217,6 +255,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
if (authorizerSnapshot != null) {
return rollbackAuthorizerUpdate(resource, authorizerSnapshot);
}
JsonNode stageSnapshot = STAGE.equals(resource.getResourceType())
? CfnRollback.updateSnapshot(resource, STAGE_SNAPSHOT_ATTR) : null;
if (stageSnapshot != null) {
return rollbackStageUpdate(resource, stageSnapshot);
}
if (ReplacementCleanup.rollback(resource,
(type, physicalId, region) -> deleteEntity(resource, physicalId, region))) {
return true;
@@ -256,6 +299,11 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
boolean authorizer() {
return AUTHORIZER_KIND.equals(httpMethod);
}
/** A stage, recorded with {@link #STAGE_KIND} and its name as the resource id. */
boolean stage() {
return STAGE_KIND.equals(httpMethod);
}
}
private Map<String, Location> locations(StackResource r) {
@@ -803,18 +851,144 @@ public class ApiGatewayRestApiCfnProvisioner implements CfnResourceProvisioner {
}
}
/**
* RestApiId and StageName are create-only: a change to either replaces the stage. Any other
* change patches it in place, keeping the settings the template does not model. A change to
* RestApiId that keeps the name leaves the physical id as it was, so the stage on the old API
* is recorded through {@link CfnLifecycleRecords} and deleted once the update commits, unless
* {@code UpdateReplacePolicy: Retain} keeps it ({@link ReplacementCleanup} lists one entity per
* physical id, so it cannot hold this one). A new stage is refused when its name is already
* taken on the API, so a rollback never deletes a stage the update did not create. A stage provisioned before its location was
* recorded is not deleted, and is not deleted as the old stage of a move either.
*/
private void provisionStage(StackResource r, JsonNode props, ProvisionContext ctx) {
// A snapshot describes the update in flight; one an earlier update left behind is stale.
r.getAttributes().remove(STAGE_SNAPSHOT_ATTR);
deletePendingStage(r);
if (ctx.isUpdate()) {
ReplacementCleanup.endRollbackRetry(r);
}
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
String region = ctx.region();
String apiId = ctx.resolveOptional(props, "RestApiId");
String stageName = ctx.resolveOptional(props, "StageName");
String deploymentId = ctx.resolveOptional(props, "DeploymentId");
PropertyChanges changes = ctx.isUpdate() ? ctx.changes(STAGE, props) : null;
boolean replaces = changes != null && changes.requiresReplacement();
Stage live = ctx.isUpdate() && !replaces
? findPrior("API stage", ctx.priorPhysicalId(),
() -> apiGatewayService.getStage(region, apiId, ctx.priorPhysicalId()))
: null;
if (live != null) {
updateStageInPlace(r, props, ctx, apiId, live);
return;
}
Location prior = ctx.isUpdate() ? locations(r).get(ctx.priorPhysicalId()) : null;
if (ctx.isUpdate()) {
requireStageNameFree(region, apiId, stageName);
}
Map<String, Object> req = new HashMap<>();
req.put("stageName", stageName);
req.put("deploymentId", deploymentId);
req.put("deploymentId", ctx.resolveOptional(props, "DeploymentId"));
req.put("description", ctx.resolveOptional(props, "Description"));
apiGatewayService.createStage(ctx.region(), apiId, req);
apiGatewayService.createStage(region, apiId, req);
r.setPhysicalId(stageName);
recordLocation(r, ctx, new Location(apiId, stageName, STAGE_KIND));
if (ctx.isUpdate() && !replaces) {
// The stage the update started from is gone, so this one is the update's to undo.
CfnRollback.recordCreatedByUpdate(r, ctx, STAGE_SNAPSHOT_ATTR);
} else if (replaces && stageName.equals(ctx.priorPhysicalId()) && prior != null
&& prior.stage() && !apiId.equals(prior.restApiId())) {
ObjectNode moved = objectMapper.createObjectNode();
moved.put("region", region);
moved.put("apiId", apiId);
moved.put("stageName", stageName);
moved.put("movedFromApiId", prior.restApiId());
r.getAttributes().put(STAGE_SNAPSHOT_ATTR, moved.toString());
CfnLifecycleRecords.setCleanup(r, STAGE_CLEANUP_ATTR, objectMapper.createObjectNode()
.put("name", stageName).put("restApiId", prior.restApiId()).put("region", region), true);
}
if (ctx.isUpdate()) {
ReplacementCleanup.record(r, ctx, attributesBefore, replaces);
}
}
/**
* Patches the stage to the template: a declared DeploymentId or Description is set, a dropped
* Description is cleared (the patch has no remove, so an empty value, which the service reads as
* cleared) and a dropped DeploymentId is kept, since the patch has no remove for
* it. Stage variables, method settings and the other fields are not touched.
*/
private void updateStageInPlace(StackResource r, JsonNode props, ProvisionContext ctx, String apiId,
Stage live) {
ObjectNode snapshot = objectMapper.createObjectNode();
snapshot.put("region", ctx.region());
snapshot.put("apiId", apiId);
snapshot.put("stageName", live.getStageName());
snapshot.put("deploymentId", live.getDeploymentId());
snapshot.put("description", live.getDescription());
r.getAttributes().put(STAGE_SNAPSHOT_ATTR, snapshot.toString());
String deploymentId = ctx.resolveOptional(props, "DeploymentId");
String description = ctx.resolveOptional(props, "Description");
String desiredDescription = description != null ? description
: ctx.droppedProperties(props).contains("Description") ? null : live.getDescription();
List<Map<String, String>> ops = new ArrayList<>();
if (deploymentId != null && !deploymentId.equals(live.getDeploymentId())) {
ops.add(replacePatchOp("/deploymentId", deploymentId));
}
if (!Objects.equals(live.getDescription(), desiredDescription)) {
ops.add(replacePatchOp("/description", desiredDescription == null ? "" : desiredDescription));
}
if (!ops.isEmpty()) {
apiGatewayService.updateStage(ctx.region(), apiId, live.getStageName(), ops);
}
r.setPhysicalId(live.getStageName());
recordLocation(r, ctx, new Location(apiId, live.getStageName(), STAGE_KIND));
}
/**
* CreateStage here overwrites a stage of the same name, which would make a rollback delete one
* the update did not create, so an update refuses a name already on the API.
*/
private void requireStageNameFree(String region, String apiId, String stageName) {
if (stageName != null && findPrior("API stage", stageName,
() -> apiGatewayService.getStage(region, apiId, stageName)) != null) {
throw new AwsException("ConflictException", "Stage already exists", 409);
}
}
/**
* Puts the stage back after a failed stack update: deletes the one the update created because
* the prior was gone, or the one a RestApiId change made on the new API (the stage on the old API
* was never touched), or writes the snapshot of a patched stage back whole. Spent only once it
* succeeded, so a failure can be retried.
*/
private boolean rollbackStageUpdate(StackResource resource, JsonNode snapshot) {
if (CfnRollback.undoCreatedByUpdate(resource, snapshot, STAGE_SNAPSHOT_ATTR, null,
(createdId, region) -> deleteEntity(resource, createdId, region))) {
return true;
}
String region = snapshot.path("region").asText();
String apiId = snapshot.path("apiId").asText();
String stageName = snapshot.path("stageName").asText();
String movedFrom = CfnRollback.snapshotText(snapshot, "movedFromApiId");
if (movedFrom != null) {
deleteLocation(stageName, new Location(apiId, stageName, STAGE_KIND), region);
ObjectNode recorded = objectMapper.createObjectNode();
recorded.set(stageName, locationNode(new Location(movedFrom, stageName, STAGE_KIND)));
resource.getAttributes().put(LOCATIONS_ATTR, recorded.toString());
ReplacementCleanup.rollback(resource, (type, physicalId, regionName) -> { });
} else {
Stage prior = new Stage();
prior.setStageName(stageName);
prior.setDeploymentId(CfnRollback.snapshotText(snapshot, "deploymentId"));
prior.setDescription(CfnRollback.snapshotText(snapshot, "description"));
apiGatewayService.restoreStage(region, apiId, prior);
}
resource.getAttributes().remove(STAGE_SNAPSHOT_ATTR);
resource.getAttributes().remove(STAGE_CLEANUP_ATTR);
return true;
}
/** Resolves an optional property, falling back to {@code defaultValue} when absent or blank. */
@@ -198,6 +198,14 @@ public final class CfnRollback {
*/
public static final String APIGW_AUTHORIZER_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayAuthorizerUpdateSnapshot";
/**
* The deployment id and description an API Gateway stage carried before an in-place update, the
* stage an update created because the prior was gone, or the old API of a stage a RestApiId change
* moved, so a failed stack update can undo each. Written and spent by
* {@code ApiGatewayRestApiCfnProvisioner}.
*/
public static final String APIGW_STAGE_UPDATE_SNAPSHOT_ATTR = "__FlociApiGatewayStageUpdateSnapshot";
public static final String STACK_SET_UPDATE_SNAPSHOT_ATTR = "__FlociStackSetUpdateSnapshot";
/**