fix(cloudformation): propagate tags to nested stacks (#7383)

This commit is contained in:
Rashen Anupama authored and GitHub committed 2026-11-03 16:47:32 -04:00
1 parent 08b6049de7
commit fad0493169
11 files changed
+787 -75

No files matched your search

@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
@@ -29,6 +30,7 @@ import io.github.hectorvent.floci.services.cloudformation.model.TemplateSummary;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
@@ -961,7 +963,7 @@ public class CloudFormationService implements ResourceProvider {
: !oldDef.equals(newDef)
|| referencesAnyParameter(newDef, changedParams)
|| referencesAnyCondition(newDef, changedConditions))
|| ("AWS::CloudFormation::Stack".equals(resourceType) && isNestedStackChanged(stack, logicalId, newDef, region, accountId)))) {
|| "AWS::CloudFormation::Stack".equals(resourceType))) {
boolean typeChanged = !oldDef.path("Type").asText().equals(resourceType);
boolean replacement = typeChanged
|| requiresReplacement(resourceType, oldDef.path("Properties"), newDef.path("Properties"), changedParams, changedConditions);
@@ -2037,7 +2039,14 @@ public class CloudFormationService implements ResourceProvider {
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
Map<String, String> tags,
boolean isCreate, String region, String accountId) {
Map<String, String> previousTags = stack.tagsSnapshot();
Map<String, String> operationTags = tags == null ? previousTags : new LinkedHashMap<>(tags);
boolean stackTagsChanged = !operationTags.equals(previousTags);
// Taken before the replacement below, so the snapshot carries the prior tags for a rollback.
StackUpdateSnapshot previousState = snapshotForUpdate(stack);
if (tags != null) {
stack.replaceTags(tags);
}
boolean updateCommitted = false;
Set<String> attemptedResourceIds = new LinkedHashSet<>();
try {
@@ -2093,6 +2102,13 @@ public class CloudFormationService implements ResourceProvider {
// Process resources in order
JsonNode resources = template.path("Resources");
if (!isCreate && stackTagsChanged && resources.isObject()) {
resources.fields().forEachRemaining(entry -> {
if ("AWS::CloudFormation::Stack".equals(entry.getValue().path("Type").asText())) {
changedResourceIds.add(entry.getKey());
}
});
}
Map<String, String> physicalIds = new LinkedHashMap<>();
Map<String, Map<String, String>> resourceAttrs = new LinkedHashMap<>();
@@ -2181,7 +2197,7 @@ public class CloudFormationService implements ResourceProvider {
if ("AWS::CloudFormation::Stack".equals(type)) {
resource = executeNestedStack(stack, logicalId,
props.isMissingNode() ? null : props,
engine, region, accountId, isCreate, previousResource);
engine, operationTags, region, accountId, isCreate, previousResource);
} else {
JsonNode previousDefinition = previousResources.path(logicalId);
JsonNode priorProps = type.equals(previousDefinition.path("Type").asText())
@@ -2375,12 +2391,16 @@ public class CloudFormationService implements ResourceProvider {
exportName, value, stack.getStackName());
});
if (isCreate) {
stack.replaceTags(operationTags);
}
if (!isCreate) {
updateCommitted = true;
stack.replaceTags(operationTags);
stack.getResources().values().forEach(resource -> resource.getAttributes()
.remove(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR));
refreshTemplateUses(stack, resources, conditions, physicalIds);
if (tags != null) {
stack.replaceTags(tags);
}
if (hasReplacementUpdates(stack) || hasRemovedOrConditionFalseResources(stack, resources, conditions)) {
stack.setStatus("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
stack.setLastUpdatedTime(now());
@@ -2437,8 +2457,10 @@ public class CloudFormationService implements ResourceProvider {
addEvent(stack, stack.getStackName(), stack.getStackId(),
"AWS::CloudFormation::Stack", "CREATE_FAILED", e.getMessage());
stack.setStatus("CREATE_FAILED");
stack.replaceTags(operationTags);
persistStack(stack);
} else {
stack.replaceTags(previousTags);
rollbackFailedUpdate(
stack, region, previousState, attemptedResourceIds, e.getMessage());
}
@@ -2464,36 +2486,6 @@ public class CloudFormationService implements ResourceProvider {
}
private boolean isNestedStackChanged(Stack parentStack, String logicalId, JsonNode newDef,
String region, String accountId) {
if (parentStack == null) {
return false;
}
StackResource existingResource = parentStack.getResources().get(logicalId);
if (existingResource == null || existingResource.getPhysicalId() == null) {
return true;
}
Stack childStack = resolveStack(existingResource.getPhysicalId(), region, accountId);
if (childStack == null) {
return true;
}
String templateUrl = newDef.path("Properties").path("TemplateURL").asText(null);
if (templateUrl == null || templateUrl.isBlank()) {
return false;
}
try {
String newChildTemplate = fetchTemplateFromS3(templateUrl);
String currentChildTemplate = childStack.getOriginalTemplateBody() != null
? childStack.getOriginalTemplateBody()
: childStack.getTemplateBody();
return newChildTemplate != null && !newChildTemplate.equals(currentChildTemplate);
} catch (Exception ignored) {
// Safe to ignore: if TemplateURL is inaccessible and parent definition didn't change,
// treat the nested stack as unchanged so the parent update is not blocked.
return false;
}
}
/**
* Handles a resource that failed to provision.
*
@@ -2544,6 +2536,9 @@ public class CloudFormationService implements ResourceProvider {
LOG.errorv("Stack {0} rollback failed: {1}", stack.getStackName(), rollbackReason);
}
} else {
if (previousState.tags() != null) {
stack.replaceTags(previousState.tags());
}
rollbackFailedUpdate(
stack, region, previousState, attemptedResourceIds,
reason);
@@ -2880,6 +2875,10 @@ public class CloudFormationService implements ResourceProvider {
// serving the failed update's attempted values.
stack.replaceParameters(previousState.parameters());
stack.replaceResolvedParameters(previousState.resolvedParameters());
// Older persisted snapshots have no tag state to restore. An explicit empty map still clears tags.
if (previousState.tags() != null) {
stack.replaceTags(previousState.tags());
}
if (rollbackFailures.isEmpty()) {
stack.setTemplateBody(previousState.templateBody());
// GetTemplate reads originalTemplateBody for TemplateStage=Original and templateBody
@@ -2962,7 +2961,8 @@ public class CloudFormationService implements ResourceProvider {
resource.setStatusReason(reason);
addEvent(stack, resource.getLogicalId(), resource.getPhysicalId(),
resource.getResourceType(), "UPDATE_FAILED", reason);
} else if ("true".equals(resource.getAttributes().remove(
} else if (rollbackNestedStackTags(resource, region, ownerAccount(stack))
|| "true".equals(resource.getAttributes().remove(
CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR))
|| dispatcher.rollbackUpdate(resource,
event -> addEvent(stack, resource.getLogicalId(), event.getPhysicalResourceId(),
@@ -2998,6 +2998,93 @@ public class CloudFormationService implements ResourceProvider {
return failures;
}
/**
* Restores the tags a nested stack carried before an in-flight update re-provisioned it, along
* with the inherited tags its descendants took from each changed level. The resource's saved
* record holds the child's deployment from before that call, so a template the update replaced
* in S3 cannot carry the restore unseen: a child whose template body or given parameters now
* differ from it is owed a deployment rollback this build does not implement, and reports false
* so the walker's own arms settle the stack in UPDATE_ROLLBACK_FAILED rather than claiming the
* prior deployment is live. A resource carrying no record was not touched by this update, and
* one whose child is gone cannot be compared; both fall through the same way.
*/
private boolean rollbackNestedStackTags(StackResource resource, String region, String accountId) {
JsonNode saved = CfnRollback.updateSnapshot(
resource, CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR);
if (saved == null) {
return false;
}
Stack childStack = resource.getPhysicalId() == null ? null
: resolveStack(resource.getPhysicalId(), region, accountId);
if (childStack == null) {
return false;
}
Map<String, String> priorTags;
try {
if (!savedChildDeploymentMatches(childStack, saved)) {
return false;
}
priorTags = objectMapper.convertValue(
saved.path("tags"), new TypeReference<Map<String, String>>() {});
} catch (RuntimeException e) {
LOG.warnv("Could not read the saved nested stack deployment for {0}: {1}",
resource.getLogicalId(), e.getMessage());
return false;
}
if (priorTags == null || !restoreSavedDescendantTags(saved, region, accountId)) {
return false;
}
childStack.replaceTags(priorTags);
persistStack(childStack);
resource.getAttributes().remove(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR);
return true;
}
/**
* Whether the child still runs the deployment the record saved: its template body and the
* parameter values it was given match, so only its tags moved and restoring them is the whole
* rollback owed. A saved field that will not read as the map or string this comparison needs
* throws, which the caller settles as an unrestorable record.
*/
private boolean savedChildDeploymentMatches(Stack childStack, JsonNode saved) {
if (!saved.path("templateBody").asText("").equals(childStack.getTemplateBody())) {
return false;
}
Map<String, String> savedParameters = objectMapper.convertValue(
saved.path("parameters"), new TypeReference<Map<String, String>>() {});
return savedParameters.equals(childStack.parametersSnapshot());
}
/** Restores captured tags without inferring whether an equal value was explicit or inherited. */
private boolean restoreSavedDescendantTags(JsonNode saved, String region, String accountId) {
Map<String, Map<String, String>> priorTags;
Map<String, String> priorDeployments;
try {
priorTags = objectMapper.convertValue(saved.path("descendantTags"), new TypeReference<>() {});
priorDeployments = objectMapper.convertValue(saved.path("descendantDeployments"), new TypeReference<>() {});
} catch (RuntimeException e) {
LOG.warnv("Could not read saved descendant tags: {0}", e.getMessage());
return false;
}
if (priorTags == null || priorDeployments == null || priorTags.values().stream().anyMatch(Objects::isNull)) {
return false;
}
Map<Stack, Map<String, String>> restores = new LinkedHashMap<>();
for (Map.Entry<String, Map<String, String>> entry : priorTags.entrySet()) {
Stack descendant = resolveStack(entry.getKey(), region, accountId);
if (descendant == null || "DELETE_COMPLETE".equals(descendant.getStatus())
|| !nestedDeploymentFingerprint(descendant).equals(priorDeployments.get(entry.getKey()))) {
return false;
}
restores.put(descendant, entry.getValue());
}
restores.forEach((descendant, tags) -> {
descendant.replaceTags(tags);
persistStack(descendant);
});
return true;
}
private void restoreOutputAndExportState(
Stack stack, String region, StackUpdateSnapshot previousState) {
RuntimeException storageFailure = null;
@@ -3114,7 +3201,8 @@ public class CloudFormationService implements ResourceProvider {
stack.outputsSnapshot(),
stack.exportsSnapshot(),
stack.outputExportNamesSnapshot(),
copyResources(stack.resourcesSnapshot()));
copyResources(stack.resourcesSnapshot()),
stack.tagsSnapshot());
}
private Map<String, StackResource> copyResources(
@@ -4273,7 +4361,8 @@ public class CloudFormationService implements ResourceProvider {
"CREATE_COMPLETE", "UPDATE_COMPLETE", "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
private StackResource executeNestedStack(Stack parentStack, String logicalId, JsonNode props,
CloudFormationTemplateEngine engine, String region,
CloudFormationTemplateEngine engine,
Map<String, String> inheritedTags, String region,
String accountId, boolean isCreate,
StackResource previousResource) {
StackResource resource = new StackResource();
@@ -4287,7 +4376,9 @@ public class CloudFormationService implements ResourceProvider {
return resource;
}
String childTemplate = fetchTemplateFromS3(templateUrl);
Stack childStack = previousResource == null || previousResource.getPhysicalId() == null ? null
: resolveStack(previousResource.getPhysicalId(), region, accountId);
boolean childCreate = isCreate || childStack == null;
String childStackName = parentStack.getStackName() + "-" + logicalId;
// Resolved as a property value: Parameters may be an Fn::If choosing between whole maps,
@@ -4308,6 +4399,22 @@ public class CloudFormationService implements ResourceProvider {
}
});
}
Map<String, String> childTags = new LinkedHashMap<>(inheritedTags);
childTags.putAll(ProvisionContext.resolveTags(props, "Tags", engine));
String childTemplate;
try {
childTemplate = fetchTemplateFromS3(templateUrl);
} catch (RuntimeException e) {
if (childCreate) {
throw e;
}
StackResource failedResource = copyResource(previousResource);
// The read failed before any child mutation, so its deployment needs no undo.
failedResource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
failedResource.setStatus("CREATE_FAILED");
failedResource.setStatusReason(e.getMessage());
return failedResource;
}
// CloudFormation creates or updates the child with these values, so the call fails as a
// CreateStack or UpdateStack would, before the child is created or changed: a parameter
// without a value, or a Fn::GetStackOutput where the child's template may not hold one
@@ -4321,20 +4428,18 @@ public class CloudFormationService implements ResourceProvider {
return resource;
}
Stack childStack = null;
boolean childCreate = isCreate || previousResource == null
|| previousResource.getPhysicalId() == null;
if (!childCreate) {
childStack = resolveStack(previousResource.getPhysicalId(), region, accountId);
childCreate = childStack == null;
}
if (childCreate) {
childStack = newStack(childStackName, newStackId(childStackName, region, accountId), region, accountId);
childStack.setStatus("CREATE_IN_PROGRESS");
stacks.put(stackKey(accountId, childStackName, region), childStack);
}
executeTemplate(childStack, childTemplate, childParams, null, childCreate, region, accountId);
if (!childCreate) {
resource.getAttributes().put(CfnRollback.NESTED_STACK_UPDATE_SNAPSHOT_ATTR,
savedChildDeployment(childStack, region, accountId).toString());
}
executeTemplate(childStack, childTemplate, childParams, childTags, childCreate, region, accountId);
resource.setPhysicalId(childStack.getStackId());
resource.getAttributes().put("Arn", childStack.getStackId());
@@ -4361,6 +4466,49 @@ public class CloudFormationService implements ResourceProvider {
return resource;
}
/**
* The child stack's own deployment before an update re-provisions it: the tags it ran with, its
* template body and the parameter values it was given. Descendant tags are captured separately;
* their templates, parameters and resources are not restored here.
*/
private ObjectNode savedChildDeployment(Stack stack, String region, String accountId) {
ObjectNode saved = objectMapper.createObjectNode();
saved.put("templateBody", stack.getTemplateBody());
saved.set("parameters", objectMapper.valueToTree(stack.parametersSnapshot()));
saved.set("tags", objectMapper.valueToTree(stack.tagsSnapshot()));
Map<String, Map<String, String>> descendantTags = new LinkedHashMap<>();
Map<String, String> descendantDeployments = new LinkedHashMap<>();
collectDescendantTags(stack, descendantTags, descendantDeployments, region, accountId);
saved.set("descendantTags", objectMapper.valueToTree(descendantTags));
saved.set("descendantDeployments", objectMapper.valueToTree(descendantDeployments));
return saved;
}
/** Captures tags and comparison fingerprints, never descendant state to re-provision. */
private void collectDescendantTags(Stack stack, Map<String, Map<String, String>> tags,
Map<String, String> deployments,
String region, String accountId) {
for (StackResource resource : stack.resourcesSnapshot().values()) {
if (!"AWS::CloudFormation::Stack".equals(resource.getResourceType())) {
continue;
}
Stack descendant = resource.getPhysicalId() == null ? null
: resolveStack(resource.getPhysicalId(), region, accountId);
if (descendant != null && !tags.containsKey(descendant.getStackId())) {
tags.put(descendant.getStackId(), descendant.tagsSnapshot());
deployments.put(descendant.getStackId(), nestedDeploymentFingerprint(descendant));
collectDescendantTags(descendant, tags, deployments, region, accountId);
}
}
}
private String nestedDeploymentFingerprint(Stack stack) {
ObjectNode deployment = objectMapper.createObjectNode();
deployment.put("templateBody", stack.getTemplateBody());
deployment.set("parameters", objectMapper.valueToTree(new TreeMap<>(stack.parametersSnapshot())));
return Digests.sha256Hex(deployment.toString());
}
/** Prefixes the keys {@link #recordTemplateUses} keeps, one per resource a definition names. */
private static final String TEMPLATE_USES_PREFIX = CfnRollback.USES_ATTR_PREFIX + "Resource.";
@@ -9,6 +9,8 @@ import java.util.Map;
* A stack's state from before an update, which the rollback of that update restores. A rollback
* that fails keeps it on the stack, so ContinueUpdateRollback can run the rollback again after the
* update that took it has returned, or after a restart.
*
* @param tags prior tags, or null when a legacy snapshot did not capture them
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@@ -20,5 +22,14 @@ public record StackUpdateSnapshot(
Map<String, String> outputs,
Map<String, String> exports,
Map<String, String> outputExportNames,
Map<String, StackResource> resources) {
Map<String, StackResource> resources,
Map<String, String> tags) {
public StackUpdateSnapshot(String templateBody, String originalTemplateBody,
Map<String, String> parameters, Map<String, String> resolvedParameters,
Map<String, String> outputs, Map<String, String> exports,
Map<String, String> outputExportNames, Map<String, StackResource> resources) {
this(templateBody, originalTemplateBody, parameters, resolvedParameters, outputs, exports,
outputExportNames, resources, null);
}
}
@@ -41,6 +41,17 @@ public final class CfnRollback {
*/
public static final String UPDATE_ROLLBACK_FAILURE_ATTR = "__FlociUpdateRollbackFailure";
/**
* Holds the child stack deployment a nested-stack resource carried before the update in flight
* re-provisioned it: the tags it ran with, its template body and the parameter values it was
* given. Descendant tags are captured too, without their deployment state. Written by
* {@code CloudFormationService.executeNestedStack} before it runs the child's template and
* spent once the update commits or the rollback restores the child's tags. A child whose live
* deployment no longer matches it is owed a template or parameter rollback this build defers,
* so the walker fails the stack honestly instead of restoring tags alone.
*/
public static final String NESTED_STACK_UPDATE_SNAPSHOT_ATTR = "__FlociNestedStackUpdateSnapshot";
/** The namespace, credentials, secret and attributes overwritten by a Serverless namespace update. */
public static final String REDSHIFT_SERVERLESS_NAMESPACE_UPDATE_SNAPSHOT_ATTR =
"__FlociRedshiftServerlessNamespaceUpdateSnapshot";
@@ -113,6 +113,10 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio
* "the template said nothing, leave stored tags alone" must keep that distinction themselves.
*/
public Map<String, String> resolveTags(JsonNode props, String name) {
return resolveTags(props, name, engine);
}
public static Map<String, String> resolveTags(JsonNode props, String name, CloudFormationTemplateEngine engine) {
Map<String, String> tags = new LinkedHashMap<>();
if (props == null || !props.has(name)) {
return tags;