mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cloudformation): refuse an update that has nothing to change (#5849)
* fix(cloudformation): refuse an update that has nothing to change UpdateStack ran a full update for a stack resubmitted as it was, ending UPDATE_COMPLETE, and CreateChangeSet created an AVAILABLE change set for it. CloudFormation refuses the update with "No updates are to be performed." and creates the change set FAILED, UNAVAILABLE, with "The submitted information didn't contain changes. Submit different information to create a change set."; the CDK and aws cloudformation deploy read that reason as "no changes". What CloudFormation compares was measured in eu-west-1: each active resource's Type, Properties, Metadata, DeletionPolicy, UpdateReplacePolicy and UpdatePolicy, and each active output's Value, Description and Export, with whatever does not depend on a resource resolved first, and the tags as a set (absent Tags keep the stack's). ComparedTemplate brings a template to that form: a new Description, an unused parameter, a DependsOn or a literal written as Fn::Join is no change, while a used mapping value, a Ref of a resource rewritten as Fn::Sub, or a dynamic reference whose stored value moved is one. Templates are compared as processed, AWS::Include fragments read again and the SAM transform applied with the stack's parameter values, and a stack with a nested stack is always updated. The change set diff uses the same form. The CDK deletes the FAILED change set and deletes it again by name before its next deploy, so DeleteChangeSet now answers success for a change set the stack does not have, as CloudFormation does. A stack set instance whose stack has nothing to change is left as it is. Tests that resubmitted an identical template to exercise an update add an output through CfnUpdates.forceUpdate, which is an update on AWS too. * fix(cloudformation): record dynamic reference values when an operation commits Answers the review of #5849. The value each dynamic reference resolved to is now recorded when the stack's operation commits, from the template the stack then has and keyed as ComparedTemplate hands the references over, instead of while the engine provisioned each resource. Recording and comparison so see the same strings, an Fn::Sub that also reads a resource included; an update that fails and rolls back records nothing and keeps the last deployment's values; a reference the template dropped is dropped; and AWS::RDS::DBInstance's master credentials, which its provisioner resolves itself with ssm-secure, are compared like any other reference. The values are kept as an HMAC-SHA256 under a random key of the stack's own rather than a bare SHA-256. ComparedTemplate keeps an AWS::NoValue inside a function it compares as written, and gives the array form of Fn::Sub the static variable substitution the string form has, its own variables left as written. A stack set instance with nothing to change succeeds whatever status an earlier rolled-back update left its stack in, and the change set that found it so is deleted. DeleteChangeSet by a change set's ARN alone succeeds when the change set is gone, as measured on CloudFormation in eu-west-1 on 2026-10-17. The comparison now catches only what it can meet: a template that does not parse, and the AwsException an AWS::Include, the SAM transform or an SSM parameter raises, which the update itself then reports.
This commit is contained in:
1 parent
c8de16ffc7
commit
197ccb5fb7
19 files changed
+1408
-40
No files matched your search
+6
@@ -159,6 +159,12 @@ public class CloudFormationQueryHandler {
|
||||
parameters, capabilities, tags, region)
|
||||
: cfnService.createChangeSet(stackName, changeSetName,
|
||||
"UPDATE", templateBody, templateUrl, parameters, capabilities, tags, region);
|
||||
// An update that submits what the stack already has is refused, and leaves no change set
|
||||
// behind, as UpdateStack does on AWS.
|
||||
if (CloudFormationService.NO_CHANGES_REASON.equals(cs.getStatusReason())) {
|
||||
cfnService.deleteChangeSet(stackName, cs.getChangeSetName(), region);
|
||||
return xmlError("ValidationError", "No updates are to be performed.", 400);
|
||||
}
|
||||
awaitExecution(cfnService.executeChangeSet(stackName, cs.getChangeSetName(), region));
|
||||
|
||||
Stack stack = cfnService.describeStacks(stackName, region).get(0);
|
||||
|
||||
+250
-12
@@ -36,7 +36,11 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
@@ -52,6 +56,7 @@ import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -64,6 +69,13 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationService.class);
|
||||
|
||||
/**
|
||||
* The reason CloudFormation gives a change set that submits what the stack already has, and
|
||||
* the condition under which UpdateStack answers "No updates are to be performed."
|
||||
*/
|
||||
static final String NO_CHANGES_REASON =
|
||||
"The submitted information didn't contain changes. Submit different information to create a change set.";
|
||||
|
||||
private static final int MAX_OPERATION_THREADS = 16;
|
||||
private static final int MAX_QUEUED_OPERATIONS = 128;
|
||||
|
||||
@@ -456,7 +468,14 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// persistStack() stays outside: it is storage I/O, and compute()'s contract is that the
|
||||
// remapping function does short, non-blocking work.
|
||||
String canonicalStackName = live == null ? stackName : live.getStackName();
|
||||
// Whether the update has nothing to change is decided here, outside compute(): it reads
|
||||
// AWS::Include fragments from S3, runs the SAM transform and resolves SSM parameters. Inside,
|
||||
// the verdict stands only if the stack still holds what it was reached against.
|
||||
DeployedState checked = isCreateType || live == null ? null : DeployedState.of(live);
|
||||
boolean unchangedWhenChecked = checked != null
|
||||
&& submitsWhatTheStackHas(live, resolvedTemplate, parameters, tags, region);
|
||||
ChangeSet[] created = new ChangeSet[1];
|
||||
boolean[] unchanged = new boolean[1];
|
||||
Stack stack = stacks.compute(stackKey(accountId, canonicalStackName, region), (k, existing) -> {
|
||||
Stack target;
|
||||
if (existing == null) {
|
||||
@@ -500,6 +519,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return existing;
|
||||
}
|
||||
target = existing;
|
||||
unchanged[0] = unchangedWhenChecked && existing == live
|
||||
&& checked.equals(DeployedState.of(existing));
|
||||
}
|
||||
|
||||
ChangeSet cs = new ChangeSet();
|
||||
@@ -516,6 +537,10 @@ public class CloudFormationService implements ResourceProvider {
|
||||
cs.setStatus("FAILED");
|
||||
cs.setExecutionStatus("UNAVAILABLE");
|
||||
cs.setStatusReason(samTransformFailureReason);
|
||||
} else if (unchanged[0]) {
|
||||
cs.setStatus("FAILED");
|
||||
cs.setExecutionStatus("UNAVAILABLE");
|
||||
cs.setStatusReason(NO_CHANGES_REASON);
|
||||
} else {
|
||||
cs.setStatus("CREATE_COMPLETE");
|
||||
cs.setExecutionStatus("AVAILABLE");
|
||||
@@ -531,6 +556,15 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return created[0];
|
||||
}
|
||||
|
||||
/** What {@link #submitsWhatTheStackHas} compares an update against. */
|
||||
private record DeployedState(String template, Map<String, String> parameters,
|
||||
Map<String, String> resolvedParameters, Map<String, String> tags) {
|
||||
static DeployedState of(Stack stack) {
|
||||
return new DeployedState(stack.getTemplateBody(), stack.parametersSnapshot(),
|
||||
stack.resolvedParametersSnapshot(), stack.tagsSnapshot());
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException cannotBeUpdated(String stackId, String status) {
|
||||
return new AwsException("ValidationError", UPDATE_REFUSED.formatted(stackId, status), 400);
|
||||
}
|
||||
@@ -545,6 +579,158 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return new AwsException("ValidationError", "Stack with id " + stackName + " does not exist", 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an UPDATE has nothing to change: the template it submits comes to the same
|
||||
* {@link ComparedTemplate} as the stack's, with the values each is given, the stack's own tags
|
||||
* or none are sent, and the stack has no nested stack. CloudFormation then answers "No updates
|
||||
* are to be performed." A new Description, Metadata, Rules or an unused parameter, mapping or
|
||||
* condition is therefore not an update, while a change to an active output is, as on AWS.
|
||||
*/
|
||||
private boolean submitsWhatTheStackHas(Stack stack, String templateBody, Map<String, String> parameters,
|
||||
Map<String, String> tags, String region) {
|
||||
if (stack.getTemplateBody() == null || templateBody == null) {
|
||||
return false;
|
||||
}
|
||||
// Tags are compared as a set. An update that sends none keeps the stack's, and so has
|
||||
// nothing to change; an empty set removes them, which is a change only for a tagged stack.
|
||||
if (tags != null && !tags.equals(stack.tagsSnapshot())) {
|
||||
return false;
|
||||
}
|
||||
JsonNode submittedTemplate = parsedOrNull(templateBody);
|
||||
JsonNode deployedTemplate = parsedOrNull(stack.getTemplateBody());
|
||||
if (submittedTemplate == null || deployedTemplate == null) {
|
||||
return false;
|
||||
}
|
||||
Map<String, String> given = parameters == null ? Map.of() : parameters;
|
||||
try {
|
||||
// Compared as execution stores it: AWS::Include fragments read again and merged, then
|
||||
// the SAM transform applied with the stack's parameter values, which it can resolve
|
||||
// into the expansion. A fragment that changed in S3 is a change.
|
||||
JsonNode template = awsIncludeProcessor.mergeIncludes(submittedTemplate);
|
||||
if (samTransformProcessor.hasSamTransform(template)) {
|
||||
template = samTransformProcessor.expandSamTemplate(template,
|
||||
samTransformParameters(template, given, region));
|
||||
}
|
||||
// A nested stack is always updated, whether or not its template changed: AWS reads the
|
||||
// child template again and reports the nested stack as a change on every update.
|
||||
for (JsonNode resource : template.path("Resources")) {
|
||||
if ("AWS::CloudFormation::Stack".equals(resource.path("Type").asText())) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Map<String, String> submitted = resolveSsmParameters(template,
|
||||
resolveDefaultParameters(template, given), region);
|
||||
return comparedDeployedTemplate(stack, deployedTemplate, region)
|
||||
.equals(comparedTemplate(template, submitted, stack, region, currentDynamicReferences(stack, region)));
|
||||
} catch (AwsException e) {
|
||||
// An AWS::Include fragment, the SAM transform or an SSM parameter the update cannot
|
||||
// process fails the update itself, which reports it as AWS does: it goes ahead rather
|
||||
// than being refused as having nothing to change.
|
||||
LOG.debugv("Treating an update as a change; its template did not process: {0}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code templateBody} parsed, or {@code null} when it does not parse: as for
|
||||
* validateResourceDependencies, the operation that processes it reports the parser's error.
|
||||
*/
|
||||
private JsonNode parsedOrNull(String templateBody) {
|
||||
try {
|
||||
return parseTemplate(templateBody);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Not comparing a template that did not parse: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The stack's deployed template as {@link ComparedTemplate} compares it, with the parameter
|
||||
* values and the dynamic reference values it was deployed with. A stack persisted before
|
||||
* resolved parameter values or dynamic reference digests were kept compares as different from
|
||||
* any update, which converges it and records them for the next time.
|
||||
*/
|
||||
private ObjectNode comparedDeployedTemplate(Stack stack, JsonNode deployedTemplate, String region) {
|
||||
Map<String, String> digests = stack.dynamicReferenceDigestsSnapshot();
|
||||
return comparedTemplate(deployedTemplate, deployedParameters(stack), stack, region,
|
||||
value -> digests.getOrDefault(value, "unrecorded " + UUID.randomUUID()));
|
||||
}
|
||||
|
||||
/** The parameter values the stack's template was deployed with. */
|
||||
private static Map<String, String> deployedParameters(Stack stack) {
|
||||
return stack.resolvedParametersSnapshot().isEmpty()
|
||||
? stack.parametersSnapshot() : stack.resolvedParametersSnapshot();
|
||||
}
|
||||
|
||||
/**
|
||||
* What each dynamic reference resolves to now, as the stack keeps it. An ssm-secure reference
|
||||
* resolves too, wherever it is, since only the digest is kept: AWS::RDS::DBInstance resolves its
|
||||
* master credentials with them.
|
||||
*/
|
||||
private UnaryOperator<String> currentDynamicReferences(Stack stack, String region) {
|
||||
return value -> {
|
||||
try {
|
||||
return dynamicReferenceDigest(stack, dynamicReferences.resolveDynamicReferences(value, region, true));
|
||||
} catch (AwsException | IllegalStateException e) {
|
||||
// What CfnDynamicReferences cannot resolve fails the operation when it runs; until
|
||||
// then it is something to change.
|
||||
return "unresolvable " + UUID.randomUUID();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps, for the next update to compare against, what each dynamic reference in the template
|
||||
* the stack now has resolves to, keyed as {@link ComparedTemplate} hands them over. Run when an
|
||||
* operation commits, so one that fails and rolls back records nothing and the stack keeps what
|
||||
* its last deployment recorded; a reference the template no longer has is dropped.
|
||||
*/
|
||||
private void recordDynamicReferenceDigests(Stack stack, JsonNode template, String region) {
|
||||
UnaryOperator<String> current = currentDynamicReferences(stack, region);
|
||||
Map<String, String> digests = new LinkedHashMap<>();
|
||||
try {
|
||||
comparedTemplate(template, deployedParameters(stack), stack, region, value -> {
|
||||
String digest = current.apply(value);
|
||||
digests.put(value, digest);
|
||||
return digest;
|
||||
});
|
||||
} catch (AwsException e) {
|
||||
// Nothing recorded compares as a change, which the next update converges and records.
|
||||
LOG.debugv("Recording no dynamic reference values for stack {0}: {1}", stack.getStackName(),
|
||||
e.getMessage());
|
||||
digests.clear();
|
||||
}
|
||||
stack.replaceDynamicReferenceDigests(digests);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a dynamic reference resolved to, as the stack keeps it: an HMAC-SHA256 under a random
|
||||
* key of the stack's own, so no value is stored, and the same value on two stacks does not
|
||||
* compare equal.
|
||||
*/
|
||||
private static String dynamicReferenceDigest(Stack stack, String resolved) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(stack.dynamicReferenceKey().getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
return HexFormat.of().formatHex(mac.doFinal(resolved.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("HmacSHA256 is not available", e);
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode comparedTemplate(JsonNode template, Map<String, String> params, Stack stack,
|
||||
String region, UnaryOperator<String> dynamicReferenceValue) {
|
||||
String accountId = ownerAccount(stack);
|
||||
Map<String, Boolean> conditions = resolveConditions(template, params, stack, region, accountId);
|
||||
Map<String, JsonNode> mappings = new HashMap<>();
|
||||
template.path("Mappings").fields().forEachRemaining(e -> mappings.put(e.getKey(), e.getValue()));
|
||||
// No dynamic reference resolver: ComparedTemplate hands each reference to dynamicReferenceValue.
|
||||
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(accountId, region,
|
||||
stack.getStackName(), stack.getStackId(), params, Map.of(), Map.of(), conditions, mappings,
|
||||
objectMapper, name -> null);
|
||||
return ComparedTemplate.of(template, objectMapper, engine, conditions, dynamicReferenceValue);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the change set's {@code StatusReason} when {@code templateBody} declares the SAM
|
||||
* transform and that transform fails, {@code null} when the transform is absent or succeeds.
|
||||
@@ -701,6 +887,25 @@ public class CloudFormationService implements ResourceProvider {
|
||||
});
|
||||
Set<String> deployedIds = stack.resourcesSnapshot().keySet();
|
||||
|
||||
// A resource is modified when what CloudFormation compares of it differs (see
|
||||
// ComparedTemplate): a DependsOn, or a literal rewritten as a function, is no change,
|
||||
// while a used mapping value or a dynamic reference whose stored value moved is. A
|
||||
// template that cannot be brought to that form falls back to its definitions as written
|
||||
// and the parameters and conditions they read.
|
||||
JsonNode[] compared = new JsonNode[2];
|
||||
if (oldTemplate != null) {
|
||||
try {
|
||||
compared[0] = comparedDeployedTemplate(stack, oldTemplate, region).path("Resources");
|
||||
compared[1] = comparedTemplate(newTemplate, newResolvedParams, stack, region,
|
||||
currentDynamicReferences(stack, region)).path("Resources");
|
||||
} catch (AwsException e) {
|
||||
// A condition or a mapping the comparison cannot resolve fails the execution
|
||||
// with its own error; the preview diffs the definitions as written until then.
|
||||
LOG.debugv("Diffing a change set as written; a template did not resolve: {0}", e.getMessage());
|
||||
compared[0] = null;
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> replacedResourceIds = new HashSet<>();
|
||||
List<ResourceChange> changes = new ArrayList<>();
|
||||
newResources.fields().forEachRemaining(e -> {
|
||||
@@ -728,10 +933,12 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// it now.
|
||||
changes.add(new ResourceChange("Add", logicalId, null, resourceType, null));
|
||||
} else if (newActive
|
||||
&& (!oldDef.equals(newDef)
|
||||
|| ("AWS::CloudFormation::Stack".equals(resourceType) && isNestedStackChanged(stack, logicalId, newDef, region, accountId))
|
||||
|| referencesAnyParameter(newDef, changedParams)
|
||||
|| referencesAnyCondition(newDef, changedConditions))) {
|
||||
&& ((compared[0] != null
|
||||
? !compared[0].path(logicalId).equals(compared[1].path(logicalId))
|
||||
: !oldDef.equals(newDef)
|
||||
|| referencesAnyParameter(newDef, changedParams)
|
||||
|| referencesAnyCondition(newDef, changedConditions))
|
||||
|| ("AWS::CloudFormation::Stack".equals(resourceType) && isNestedStackChanged(stack, logicalId, newDef, region, accountId)))) {
|
||||
boolean typeChanged = !oldDef.path("Type").asText().equals(resourceType);
|
||||
boolean replacement = typeChanged
|
||||
|| requiresReplacement(resourceType, oldDef.path("Properties"), newDef.path("Properties"), changedParams, changedConditions);
|
||||
@@ -1052,8 +1259,20 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
public void deleteChangeSet(String stackName, String changeSetName, String region) {
|
||||
String accountId = currentAccount();
|
||||
Stack stack = getStackForChangeSet(stackName, changeSetName, region, accountId);
|
||||
ChangeSet cs = getChangeSetOrThrow(stack, changeSetName, region, accountId);
|
||||
boolean byArnAlone = (stackName == null || stackName.isBlank())
|
||||
&& changeSetName != null && changeSetName.startsWith("arn:");
|
||||
Stack stack = byArnAlone
|
||||
? findStackForChangeSetArn(changeSetName, region, accountId)
|
||||
: getStackForChangeSet(stackName, changeSetName, region, accountId);
|
||||
ChangeSet cs = stack == null ? null : findChangeSet(stack, changeSetName, region, accountId);
|
||||
if (cs == null) {
|
||||
// CloudFormation answers success for a change set the stack does not have, whatever
|
||||
// the stack's status, named by its stack and name or by its ARN alone (measured,
|
||||
// eu-west-1, 2026-10-04 and 2026-10-17). The AWS CDK deletes its
|
||||
// change set by name before every deploy and relies on it, since it deletes the one
|
||||
// that had nothing to change.
|
||||
return;
|
||||
}
|
||||
stack.getChangeSets().remove(cs.getChangeSetName());
|
||||
persistStack(stack);
|
||||
}
|
||||
@@ -1978,6 +2197,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
stack.replaceOutputs(newOutputs);
|
||||
stack.replaceExports(newExports);
|
||||
stack.replaceOutputExportNames(newOutputExportNames);
|
||||
recordDynamicReferenceDigests(stack, template, region);
|
||||
newExports.forEach((exportName, value) -> {
|
||||
String logicalKey = region + ":" + exportName;
|
||||
String exportKey = accountExportKey(accountId, logicalKey);
|
||||
@@ -3582,30 +3802,48 @@ public class CloudFormationService implements ResourceProvider {
|
||||
if (changeSetNameOrArn == null || !changeSetNameOrArn.startsWith("arn:")) {
|
||||
throw new AwsException("ValidationError", "StackName is required when ChangeSetName is not an ARN", 400);
|
||||
}
|
||||
Stack stack = findStackForChangeSetArn(changeSetNameOrArn, region, accountId);
|
||||
if (stack == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetNameOrArn + "] does not exist", 400);
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
/** The stack holding the change set {@code changeSetArn} names, or {@code null}. */
|
||||
private Stack findStackForChangeSetArn(String changeSetArn, String region, String accountId) {
|
||||
// A change-set ARN contains its name and UUID, but not its stack name. Search only
|
||||
// stacks in the caller's account and region, and match the complete ARN so another
|
||||
// stack's change set with the same short name cannot be selected accidentally.
|
||||
String changeSetName = resolveChangeSetName(changeSetNameOrArn, region, accountId);
|
||||
String changeSetName = resolveChangeSetName(changeSetArn, region, accountId);
|
||||
for (Stack stack : stacks.values()) {
|
||||
if (accountId.equals(ownerAccount(stack)) && region.equals(stack.getRegion())) {
|
||||
ChangeSet changeSet = stack.getChangeSets().get(changeSetName);
|
||||
if (changeSet != null && changeSetNameOrArn.equals(changeSet.getChangeSetId())) {
|
||||
if (changeSet != null && changeSetArn.equals(changeSet.getChangeSetId())) {
|
||||
return stack;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetNameOrArn + "] does not exist", 400);
|
||||
return null;
|
||||
}
|
||||
|
||||
private ChangeSet getChangeSetOrThrow(Stack stack, String changeSetNameOrArn,
|
||||
String region, String accountId) {
|
||||
ChangeSet changeSet = findChangeSet(stack, changeSetNameOrArn, region, accountId);
|
||||
if (changeSet == null) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetNameOrArn + "] does not exist", 400);
|
||||
}
|
||||
return changeSet;
|
||||
}
|
||||
|
||||
private ChangeSet findChangeSet(Stack stack, String changeSetNameOrArn,
|
||||
String region, String accountId) {
|
||||
ChangeSet changeSet = stack.getChangeSets().get(
|
||||
resolveChangeSetName(changeSetNameOrArn, region, accountId));
|
||||
if (changeSet == null || (changeSetNameOrArn != null && changeSetNameOrArn.startsWith("arn:")
|
||||
&& !changeSetNameOrArn.equals(changeSet.getChangeSetId()))) {
|
||||
throw new AwsException("ChangeSetNotFoundException",
|
||||
"ChangeSet [" + changeSetNameOrArn + "] does not exist", 400);
|
||||
return null;
|
||||
}
|
||||
return changeSet;
|
||||
}
|
||||
|
||||
+262
@@ -0,0 +1,262 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A template in the form CloudFormation compares when it decides what an update changes. Measured
|
||||
* against CloudFormation (eu-west-1, 2026-10-16): of each active resource it compares the Type,
|
||||
* Properties, Metadata, DeletionPolicy, UpdateReplacePolicy and UpdatePolicy, and of each active
|
||||
* output the Value, Description and Export. Whatever does not depend on a resource is resolved
|
||||
* first, so a literal written as {@code Fn::Join}, a parameter written as {@code Fn::Sub} or an
|
||||
* {@code Fn::If} whose other branch changed compares equal, while a {@code Ref} or
|
||||
* {@code Fn::GetAtt} of a resource, {@code Fn::ImportValue} and {@code Fn::GetStackOutput} compare
|
||||
* as written: {@code Ref A} rewritten as {@code Fn::Sub "${A}"} is a change. A dynamic reference
|
||||
* compares as the value it resolves to, through the function given. DependsOn, CreationPolicy, the
|
||||
* name of a resource's Condition, an output whose Condition is false and every section but
|
||||
* Resources and Outputs are not compared.
|
||||
*/
|
||||
final class ComparedTemplate {
|
||||
|
||||
private static final List<String> RESOURCE_KEYS = List.of(
|
||||
"Type", "Properties", "Metadata", "DeletionPolicy", "UpdateReplacePolicy", "UpdatePolicy");
|
||||
private static final List<String> OUTPUT_KEYS = List.of("Value", "Description", "Export");
|
||||
private static final Pattern SUB_VARIABLE = Pattern.compile("\\$\\{([^}]*)}");
|
||||
private static final String DYNAMIC_REFERENCE = "{{resolve:";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final CloudFormationTemplateEngine engine;
|
||||
private final Map<String, Boolean> conditions;
|
||||
private final Set<String> resourceIds = new HashSet<>();
|
||||
private final UnaryOperator<String> dynamicReferenceValue;
|
||||
|
||||
/**
|
||||
* @param engine resolves what does not depend on a resource: built with the
|
||||
* template's parameter values, mappings and conditions, and without
|
||||
* a dynamic reference resolver, so a dynamic reference reaches
|
||||
* {@code dynamicReferenceValue} as written
|
||||
* @param dynamicReferenceValue the value a string holding a dynamic reference compares as
|
||||
*/
|
||||
private ComparedTemplate(ObjectMapper objectMapper, CloudFormationTemplateEngine engine,
|
||||
Map<String, Boolean> conditions, UnaryOperator<String> dynamicReferenceValue) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.engine = engine;
|
||||
this.conditions = conditions;
|
||||
this.dynamicReferenceValue = dynamicReferenceValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* The compared form of {@code template}: an object with a {@code Resources} and an
|
||||
* {@code Outputs} member, each keyed by logical id. Two deployments of a stack change nothing
|
||||
* when their forms are equal; one resource changes when its member differs.
|
||||
*/
|
||||
static ObjectNode of(JsonNode template, ObjectMapper objectMapper, CloudFormationTemplateEngine engine,
|
||||
Map<String, Boolean> conditions, UnaryOperator<String> dynamicReferenceValue) {
|
||||
ComparedTemplate compared = new ComparedTemplate(objectMapper, engine, conditions, dynamicReferenceValue);
|
||||
template.path("Resources").fieldNames().forEachRemaining(compared.resourceIds::add);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.set("Resources", compared.section(template.path("Resources"), RESOURCE_KEYS));
|
||||
result.set("Outputs", compared.section(template.path("Outputs"), OUTPUT_KEYS));
|
||||
return result;
|
||||
}
|
||||
|
||||
private ObjectNode section(JsonNode entries, List<String> keys) {
|
||||
ObjectNode section = objectMapper.createObjectNode();
|
||||
entries.fields().forEachRemaining(entry -> {
|
||||
JsonNode definition = entry.getValue();
|
||||
String condition = definition.path("Condition").asText(null);
|
||||
if (condition != null && !conditions.getOrDefault(condition, false)) {
|
||||
return;
|
||||
}
|
||||
ObjectNode compared = objectMapper.createObjectNode();
|
||||
for (String key : keys) {
|
||||
JsonNode value = definition.get(key);
|
||||
if (value != null) {
|
||||
compared.set(key, compared(value, false));
|
||||
}
|
||||
}
|
||||
section.set(entry.getKey(), compared);
|
||||
});
|
||||
return section;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param asWritten whether {@code node} is inside a function compared as written, where an
|
||||
* {@code AWS::NoValue} is part of what is written rather than an absent value
|
||||
*/
|
||||
private JsonNode compared(JsonNode node, boolean asWritten) {
|
||||
if (node.isTextual()) {
|
||||
return dynamicReferencesIn(node);
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode array = objectMapper.createArrayNode();
|
||||
node.forEach(element -> {
|
||||
JsonNode compared = compared(element, asWritten);
|
||||
if (asWritten || !isNoValue(compared)) {
|
||||
array.add(compared);
|
||||
}
|
||||
});
|
||||
return array;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
return node;
|
||||
}
|
||||
String function = intrinsicName(node);
|
||||
if (function != null) {
|
||||
JsonNode argument = node.get(function);
|
||||
if ("Fn::If".equals(function) && argument.isArray() && argument.size() == 3) {
|
||||
return compared(conditions.getOrDefault(argument.get(0).asText(), false)
|
||||
? argument.get(1) : argument.get(2), asWritten);
|
||||
}
|
||||
if (isNoValue(node)) {
|
||||
return node;
|
||||
}
|
||||
if (!dependsOnResource(node)) {
|
||||
return dynamicReferencesIn(engine.resolveNode(node));
|
||||
}
|
||||
if ("Fn::Sub".equals(function) && argument.isTextual()) {
|
||||
ObjectNode sub = objectMapper.createObjectNode();
|
||||
sub.put("Fn::Sub", substituteStaticVariables(argument.asText(), objectMapper.createObjectNode()));
|
||||
return sub;
|
||||
}
|
||||
if ("Fn::Sub".equals(function) && argument.isArray() && argument.size() == 2
|
||||
&& argument.get(0).isTextual()) {
|
||||
ObjectNode sub = objectMapper.createObjectNode();
|
||||
sub.putArray("Fn::Sub")
|
||||
.add(substituteStaticVariables(argument.get(0).asText(), argument.get(1)))
|
||||
.add(compared(argument.get(1), true));
|
||||
return sub;
|
||||
}
|
||||
ObjectNode kept = objectMapper.createObjectNode();
|
||||
kept.set(function, compared(argument, true));
|
||||
return kept;
|
||||
}
|
||||
ObjectNode object = objectMapper.createObjectNode();
|
||||
node.fields().forEachRemaining(field -> {
|
||||
JsonNode compared = compared(field.getValue(), asWritten);
|
||||
if (asWritten || !isNoValue(compared)) {
|
||||
object.set(field.getKey(), compared);
|
||||
}
|
||||
});
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether {@code node} reads a resource, an export or another stack's output, which are
|
||||
* compared as written. An {@code Fn::If} depends only on the branch its condition chooses.
|
||||
*/
|
||||
private boolean dependsOnResource(JsonNode node) {
|
||||
if (node.isArray()) {
|
||||
for (JsonNode element : node) {
|
||||
if (dependsOnResource(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (!node.isObject()) {
|
||||
return false;
|
||||
}
|
||||
String function = intrinsicName(node);
|
||||
JsonNode argument = function == null ? null : node.get(function);
|
||||
if ("Ref".equals(function)) {
|
||||
return resourceIds.contains(argument.asText());
|
||||
}
|
||||
if ("Fn::GetAtt".equals(function) || "Fn::ImportValue".equals(function)
|
||||
|| "Fn::GetStackOutput".equals(function)) {
|
||||
return true;
|
||||
}
|
||||
if ("Fn::If".equals(function) && argument.isArray() && argument.size() == 3) {
|
||||
return dependsOnResource(conditions.getOrDefault(argument.get(0).asText(), false)
|
||||
? argument.get(1) : argument.get(2));
|
||||
}
|
||||
if ("Fn::Sub".equals(function)) {
|
||||
JsonNode variables = argument.isArray() ? argument.path(1) : objectMapper.createObjectNode();
|
||||
String text = (argument.isArray() ? argument.path(0) : argument).asText();
|
||||
return subReadsResource(text, variables) || dependsOnResource(variables);
|
||||
}
|
||||
for (JsonNode child : node) {
|
||||
if (dependsOnResource(child)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean subReadsResource(String text, JsonNode variables) {
|
||||
Matcher matcher = SUB_VARIABLE.matcher(text);
|
||||
while (matcher.find()) {
|
||||
String name = matcher.group(1);
|
||||
if (!name.startsWith("!") && !variables.has(name)) {
|
||||
int dot = name.indexOf('.');
|
||||
if (resourceIds.contains(dot < 0 ? name : name.substring(0, dot))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@code Fn::Sub} string that reads a resource, with every other variable (a parameter, a
|
||||
* pseudo parameter) replaced by its value, so only the resource reads remain as written. A
|
||||
* variable its own map defines stays as written: the map is compared beside it.
|
||||
*/
|
||||
private String substituteStaticVariables(String text, JsonNode variables) {
|
||||
Matcher matcher = SUB_VARIABLE.matcher(text);
|
||||
StringBuilder result = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
String name = matcher.group(1);
|
||||
int dot = name.indexOf('.');
|
||||
boolean readsResource = !name.startsWith("!")
|
||||
&& resourceIds.contains(dot < 0 ? name : name.substring(0, dot));
|
||||
String replacement = name.startsWith("!") || readsResource || variables.has(name)
|
||||
? matcher.group()
|
||||
: engine.resolve(objectMapper.createObjectNode().put("Ref", name));
|
||||
matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(result);
|
||||
return dynamicReferencesIn(TextNode.valueOf(result.toString())).asText();
|
||||
}
|
||||
|
||||
private JsonNode dynamicReferencesIn(JsonNode node) {
|
||||
if (node.isTextual()) {
|
||||
String text = node.asText();
|
||||
return text.contains(DYNAMIC_REFERENCE) ? TextNode.valueOf(dynamicReferenceValue.apply(text)) : node;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode array = objectMapper.createArrayNode();
|
||||
node.forEach(element -> array.add(dynamicReferencesIn(element)));
|
||||
return array;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
ObjectNode object = objectMapper.createObjectNode();
|
||||
node.fields().forEachRemaining(field -> object.set(field.getKey(), dynamicReferencesIn(field.getValue())));
|
||||
return object;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private static String intrinsicName(JsonNode node) {
|
||||
if (node.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
String name = node.fieldNames().next();
|
||||
return "Ref".equals(name) || name.startsWith("Fn::") ? name : null;
|
||||
}
|
||||
|
||||
private static boolean isNoValue(JsonNode node) {
|
||||
return node.isObject() && node.size() == 1 && "AWS::NoValue".equals(node.path("Ref").asText(null));
|
||||
}
|
||||
}
|
||||
+20
-5
@@ -4,9 +4,11 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.Stack;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackInstance;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackSet;
|
||||
@@ -644,9 +646,18 @@ public class StackSetService {
|
||||
// Preflight the change set in the target account so AWS::AccountId-based conditions are
|
||||
// evaluated against the same account the instance executes in (createChangeSet otherwise runs
|
||||
// in the administrator request scope).
|
||||
cfnService.createChangeSet(stackName, changeSetName, changeSetType, ss.getTemplateBody(), null,
|
||||
ss.getParameters(), ss.getCapabilities(), ss.getTags(), region, account);
|
||||
await(cfnService.executeChangeSet(stackName, changeSetName, region, account));
|
||||
ChangeSet changeSet = cfnService.createChangeSet(stackName, changeSetName, changeSetType,
|
||||
ss.getTemplateBody(), null, ss.getParameters(), ss.getCapabilities(), ss.getTags(), region, account);
|
||||
// An instance whose stack already has what the stack set describes is left as it is, as on
|
||||
// AWS: executing its change set, which has nothing to change, would update the stack anyway.
|
||||
// That change set is the engine's own and is not left behind.
|
||||
boolean nothingToChange = changeSet != null && "FAILED".equals(changeSet.getStatus())
|
||||
&& CloudFormationService.NO_CHANGES_REASON.equals(changeSet.getStatusReason());
|
||||
if (nothingToChange) {
|
||||
RequestScopes.runAs(account, region, () -> cfnService.deleteChangeSet(stackName, changeSetName, region));
|
||||
} else {
|
||||
await(cfnService.executeChangeSet(stackName, changeSetName, region, account));
|
||||
}
|
||||
|
||||
StackInstance inst = new StackInstance();
|
||||
inst.setStackSetId(ss.getStackSetId());
|
||||
@@ -659,8 +670,12 @@ public class StackSetService {
|
||||
String stackStatus = stacks.isEmpty() ? null : stacks.get(0).getStatus();
|
||||
// Only a clean create/update is a success. A failed resource rolls the stack back, so its
|
||||
// terminal status is ROLLBACK_COMPLETE (not *_FAILED) — treat anything that is not COMPLETE
|
||||
// as a failed instance so the operation status reflects it.
|
||||
if (!"CREATE_COMPLETE".equals(stackStatus) && !"UPDATE_COMPLETE".equals(stackStatus)) {
|
||||
// as a failed instance so the operation status reflects it. A stack with nothing to change
|
||||
// accepted the preflight and already has what the stack set describes, whatever status an
|
||||
// earlier rolled-back update left it in.
|
||||
if (nothingToChange) {
|
||||
inst.setDetailedStatus("SUCCEEDED");
|
||||
} else if (!"CREATE_COMPLETE".equals(stackStatus) && !"UPDATE_COMPLETE".equals(stackStatus)) {
|
||||
inst.setStatus("INOPERABLE");
|
||||
inst.setDetailedStatus("FAILED");
|
||||
inst.setStatusReason(stacks.isEmpty() ? null : stacks.get(0).getStatusReason());
|
||||
|
||||
@@ -11,6 +11,7 @@ import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/**
|
||||
@@ -55,6 +56,13 @@ public class Stack {
|
||||
// executeTemplate — used to detect drift in the live SSM value between deploys even when the
|
||||
// referencing parameter (name) is unchanged, so change-set previews agree with execution.
|
||||
private Map<String, String> resolvedParameters = orderedMap();
|
||||
// A keyed digest of what each string holding a dynamic reference resolved to when the stack's
|
||||
// last operation committed, keyed by the string as the comparison of an update sees it. An
|
||||
// update compares what the string resolves to now against it, so a stored value that moved is a
|
||||
// change, as on AWS; the digest keeps a secret the reference resolves to out of the stored stack.
|
||||
private Map<String, String> dynamicReferenceDigests = orderedMap();
|
||||
// The stack's own random key for those digests.
|
||||
private String dynamicReferenceKey;
|
||||
private Map<String, String> outputs = orderedMap();
|
||||
private Map<String, String> exports = orderedMap();
|
||||
// Maps output key to its export name (when Export.Name is defined on an output)
|
||||
@@ -109,6 +117,25 @@ public class Stack {
|
||||
public void setResolvedParameters(Map<String, String> resolvedParameters) { this.resolvedParameters = orderedMap(resolvedParameters); }
|
||||
@JsonProperty("resolvedParameters")
|
||||
public Map<String, String> resolvedParametersSnapshot() { return snapshot(resolvedParameters); }
|
||||
public void replaceDynamicReferenceDigests(Map<String, String> source) { replace(dynamicReferenceDigests, source); }
|
||||
@JsonProperty("dynamicReferenceDigests")
|
||||
public void setDynamicReferenceDigests(Map<String, String> dynamicReferenceDigests) {
|
||||
this.dynamicReferenceDigests = orderedMap(dynamicReferenceDigests);
|
||||
}
|
||||
@JsonProperty("dynamicReferenceDigests")
|
||||
public Map<String, String> dynamicReferenceDigestsSnapshot() { return snapshot(dynamicReferenceDigests); }
|
||||
/** The key of the stack's dynamic reference digests, made the first time one is needed. */
|
||||
@JsonProperty("dynamicReferenceKey")
|
||||
public synchronized String dynamicReferenceKey() {
|
||||
if (dynamicReferenceKey == null) {
|
||||
dynamicReferenceKey = UUID.randomUUID().toString();
|
||||
}
|
||||
return dynamicReferenceKey;
|
||||
}
|
||||
@JsonProperty("dynamicReferenceKey")
|
||||
public synchronized void setDynamicReferenceKey(String dynamicReferenceKey) {
|
||||
this.dynamicReferenceKey = dynamicReferenceKey;
|
||||
}
|
||||
@JsonIgnore
|
||||
public Map<String, String> getOutputs() { return outputs; }
|
||||
@JsonProperty("outputs")
|
||||
|
||||
Reference in new issue
Block a user