mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): replace exactly what the change set says for AppConfig profiles and ElastiCache clusters (#8204)
This commit is contained in:
1 parent
a827daebfc
commit
b4b659bd88
15 files changed
+1272
-125
No files matched your search
@@ -117,11 +117,14 @@ An update that changes only mutable properties keeps the ID and changes the reso
|
||||
description of an application, environment or configuration profile, an environment's `Monitors`, an application's
|
||||
`Tags`, and a deployment strategy's description, duration, final bake time, growth factor and growth type. A property
|
||||
the template drops is cleared, or set back to its default (`FinalBakeTimeInMinutes` 0, `GrowthType` `LINEAR`). A
|
||||
change to a createOnly property (`ApplicationId` on an environment or configuration profile, `LocationUri` or `Type`
|
||||
on a configuration profile, `Name` or `ReplicateTo` on a deployment strategy) replaces the resource: the new one is
|
||||
change to a createOnly property (`ApplicationId` on an environment or configuration profile, `LocationUri` on a
|
||||
configuration profile, `Name` or `ReplicateTo` on a deployment strategy) replaces the resource: the new one is
|
||||
created and the old one is deleted once the stack update completes. A failed stack update puts back what it changed in
|
||||
place and deletes what it created.
|
||||
|
||||
A change to a configuration profile's `Type` is accepted on update and not applied: the profile keeps its ID and the
|
||||
type it was created with, as `UpdateConfigurationProfile` has no `Type` member.
|
||||
|
||||
Deleting an environment deletes its deployments, and deleting a configuration profile deletes its hosted configuration
|
||||
versions. Floci keeps tags on applications only, so `Tags` on the other three types are accepted and not stored, as
|
||||
`TagResource` treats them; so are a configuration profile's `KmsKeyIdentifier`, `RetrievalRoleArn` and `Validators`,
|
||||
|
||||
@@ -449,6 +449,17 @@ HMAC-SHA256 under a random key of the stack's own, so no resolved value is store
|
||||
fails and rolls back keeps the values of the last deployment. A stack set instance whose stack has
|
||||
nothing to change is left as it is and succeeds, and the change set that found it so is not kept.
|
||||
|
||||
For a resource type in the create-only table, the `Replacement` of a modified resource comes from
|
||||
the resolved values, not the template text. A dynamic reference on either side is compared through
|
||||
its digest, and a plain value on the other side is digested the same way, so
|
||||
`{{resolve:ssm:/p}}` holding `hosted` and the literal `hosted` are one value. A reference whose old
|
||||
value the stack never recorded (a stack persisted before digests were kept) gives no evidence about
|
||||
the old value: its `Replacement` follows the template text, while the update still converges the
|
||||
stack and records the digests. A resource whose create-only property reads an attribute that changes
|
||||
in place gets `Replacement: Conditional`, as on AWS, and `ExecuteChangeSet` replaces it only if
|
||||
the resolved value changed. A property that cannot be resolved is logged at `WARN` with its
|
||||
logical id, and the preview falls back to the template text.
|
||||
|
||||
A `CreateChangeSet` for such an update is created `FAILED`, `UNAVAILABLE`, with `The submitted
|
||||
information didn't contain changes. Submit different information to create a change set.`, which is
|
||||
what the AWS CLI's `deploy` and the CDK read as "no changes".
|
||||
|
||||
@@ -82,14 +82,26 @@ public final class CfnCreateOnlyProperties {
|
||||
*/
|
||||
public static boolean createOnlyValueChanged(String resourceType, JsonNode oldProps, JsonNode newProps) {
|
||||
for (String pointer : getCreateOnlyProperties(resourceType)) {
|
||||
String[] segments = pointer.split("/");
|
||||
if (pointerChanged(oldProps, newProps, segments, 0, segments.length == 1)) {
|
||||
if (createOnlyPointerChanged(pointer, oldProps, newProps)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** {@link #createOnlyValueChanged} for one pointer of the type's table. */
|
||||
public static boolean createOnlyPointerChanged(String pointer, JsonNode oldProps, JsonNode newProps) {
|
||||
String[] segments = pointer.split("/");
|
||||
return pointerChanged(oldProps, newProps, segments, 0, segments.length == 1);
|
||||
}
|
||||
|
||||
/** The subtrees of the properties that sit under one create-only pointer. */
|
||||
public static List<JsonNode> subtreesAt(String pointer, JsonNode props) {
|
||||
List<JsonNode> out = new ArrayList<>();
|
||||
collect(props, pointer.split("/"), 0, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The subtrees of the new properties that sit under a create-only pointer of the type. */
|
||||
public static List<JsonNode> createOnlySubtrees(String resourceType, JsonNode props) {
|
||||
List<JsonNode> out = new ArrayList<>();
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.fasterxml.jackson.databind.node.TextNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
@@ -64,7 +65,9 @@ import java.util.concurrent.Future;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.UnaryOperator;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -863,11 +866,39 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* 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()));
|
||||
return comparedDeployedTemplate(stack, deployedTemplate, region, new HashSet<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* As above, collecting into {@code noEvidenceForms} every form made up for a reference the stack
|
||||
* holds no digest for. They are told apart by identity, never by their text, which a value could
|
||||
* share.
|
||||
*/
|
||||
private ObjectNode comparedDeployedTemplate(Stack stack, JsonNode deployedTemplate, String region,
|
||||
Set<String> noEvidenceForms) {
|
||||
Map<String, String> digests = stack.dynamicReferenceDigestsSnapshot();
|
||||
return comparedTemplate(deployedTemplate, deployedParameters(stack), stack, region, value -> {
|
||||
String digest = digests.get(value);
|
||||
// A digest of "unresolvable" is what an older record may hold; it is no evidence either.
|
||||
if (digest == null || digest.startsWith(UNRESOLVABLE_PREFIX)) {
|
||||
digest = UNRECORDED_DIGEST_PREFIX + UUID.randomUUID();
|
||||
noEvidenceForms.add(digest);
|
||||
}
|
||||
return digest;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the compared form made up for a dynamic reference whose value the stack never recorded
|
||||
* (or could not resolve when it recorded). Such a form differs from any update by construction,
|
||||
* so it is no evidence about the old value. It only builds the text; the forms are recognised by
|
||||
* the set {@code comparedDeployedTemplate} fills.
|
||||
*/
|
||||
private static final String UNRECORDED_DIGEST_PREFIX = "unrecorded ";
|
||||
|
||||
/** Starts the compared form made up for a dynamic reference that did not resolve. */
|
||||
private static final String UNRESOLVABLE_PREFIX = "unresolvable ";
|
||||
|
||||
/** The parameter values the stack's template was deployed with. */
|
||||
private static Map<String, String> deployedParameters(Stack stack) {
|
||||
return stack.resolvedParametersSnapshot().isEmpty()
|
||||
@@ -880,13 +911,22 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* master credentials with them.
|
||||
*/
|
||||
private UnaryOperator<String> currentDynamicReferences(Stack stack, String region) {
|
||||
return currentDynamicReferences(stack, region, new HashSet<>());
|
||||
}
|
||||
|
||||
/** As above, collecting into {@code unresolvable} the forms made up for references that did not resolve. */
|
||||
private UnaryOperator<String> currentDynamicReferences(Stack stack, String region, Set<String> unresolvable) {
|
||||
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();
|
||||
// then it is something to change. Only the reference text is logged, never a value.
|
||||
LOG.warnv("Stack {0}: a dynamic reference did not resolve ({1}): {2}", stack.getStackName(),
|
||||
String.join(", ", CfnDynamicReferences.referencesIn(value)), e.getMessage());
|
||||
String form = UNRESOLVABLE_PREFIX + UUID.randomUUID();
|
||||
unresolvable.add(form);
|
||||
return form;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -898,18 +938,22 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* 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);
|
||||
Set<String> unresolvable = new HashSet<>();
|
||||
UnaryOperator<String> current = currentDynamicReferences(stack, region, unresolvable);
|
||||
Map<String, String> digests = new LinkedHashMap<>();
|
||||
try {
|
||||
comparedTemplate(template, deployedParameters(stack), stack, region, value -> {
|
||||
String digest = current.apply(value);
|
||||
digests.put(value, digest);
|
||||
// A reference that did not resolve is recorded as nothing, so it reads as unrecorded.
|
||||
if (!unresolvable.contains(digest)) {
|
||||
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());
|
||||
LOG.warnv("Stack {0}: recording no dynamic reference digests; the template did not resolve: {1}",
|
||||
stack.getStackName(), e.getMessage());
|
||||
digests.clear();
|
||||
}
|
||||
stack.replaceDynamicReferenceDigests(digests);
|
||||
@@ -1116,11 +1160,18 @@ public class CloudFormationService implements ResourceProvider {
|
||||
// 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];
|
||||
Set<String> currentReferenceForms = new HashSet<>();
|
||||
Set<String> noEvidenceForms = new HashSet<>();
|
||||
if (oldTemplate != null) {
|
||||
try {
|
||||
compared[0] = comparedDeployedTemplate(stack, oldTemplate, region).path("Resources");
|
||||
compared[1] = comparedTemplate(newTemplate, newResolvedParams, stack, region,
|
||||
currentDynamicReferences(stack, region)).path("Resources");
|
||||
compared[0] = comparedDeployedTemplate(stack, oldTemplate, region, noEvidenceForms)
|
||||
.path("Resources");
|
||||
UnaryOperator<String> currentReferences = currentDynamicReferences(stack, region);
|
||||
compared[1] = comparedTemplate(newTemplate, newResolvedParams, stack, region, value -> {
|
||||
String form = currentReferences.apply(value);
|
||||
currentReferenceForms.add(form);
|
||||
return form;
|
||||
}).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.
|
||||
@@ -1129,6 +1180,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
ReplacementDecider replacementDecider = new ReplacementDecider(stack, region, compared, oldResolvedParams,
|
||||
newResolvedParams, oldConditions, newConditions, oldTemplate, newTemplate, changedParams,
|
||||
changedConditions, currentReferenceForms, noEvidenceForms);
|
||||
Set<String> replacedResourceIds = new HashSet<>();
|
||||
List<ResourceChange> changes = new ArrayList<>();
|
||||
newResources.fields().forEachRemaining(e -> {
|
||||
@@ -1164,7 +1218,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|| "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);
|
||||
|| replacementDecider.decide(resourceType, logicalId, oldDef, newDef);
|
||||
if (replacement) {
|
||||
replacedResourceIds.add(logicalId);
|
||||
}
|
||||
@@ -1175,7 +1229,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
changes.add(new ResourceChange("Modify", logicalId,
|
||||
resourcePhysicalId(stack, logicalId), resourceType,
|
||||
replacement ? "True" : "False"));
|
||||
replacement ? REPLACEMENT_TRUE : REPLACEMENT_FALSE));
|
||||
}
|
||||
});
|
||||
oldResources.fields().forEachRemaining(e -> {
|
||||
@@ -1248,44 +1302,33 @@ public class CloudFormationService implements ResourceProvider {
|
||||
JsonNode oldDef = oldResources.get(logicalId);
|
||||
boolean typeChanged = oldDef != null && !oldDef.path("Type").asText().equals(resourceType);
|
||||
|
||||
boolean createOnlyReferencesReplaced = false;
|
||||
JsonNode props = newDef.path("Properties");
|
||||
if (props != null && props.isObject()) {
|
||||
if (CfnCreateOnlyProperties.hasSchema(resourceType)) {
|
||||
for (JsonNode subtree : CfnCreateOnlyProperties.createOnlySubtrees(resourceType, props)) {
|
||||
Set<String> fieldDeps = new LinkedHashSet<>();
|
||||
collectDependencies(subtree, allResourceIds, fieldDeps, newConditions);
|
||||
if (fieldDeps.stream().anyMatch(replacedResourceIds::contains)) {
|
||||
createOnlyReferencesReplaced = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (Iterator<String> it = props.fieldNames(); it.hasNext(); ) {
|
||||
String field = it.next();
|
||||
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field)) {
|
||||
Set<String> fieldDeps = new LinkedHashSet<>();
|
||||
collectDependencies(props.get(field), allResourceIds, fieldDeps, newConditions);
|
||||
if (fieldDeps.stream().anyMatch(replacedResourceIds::contains)) {
|
||||
createOnlyReferencesReplaced = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
boolean createOnlyReferencesReplaced = anyCreateOnlyValue(resourceType, props, subtree -> {
|
||||
Set<String> fieldDeps = new LinkedHashSet<>();
|
||||
collectDependencies(subtree, allResourceIds, fieldDeps, newConditions);
|
||||
return fieldDeps.stream().anyMatch(replacedResourceIds::contains);
|
||||
});
|
||||
|
||||
boolean replacement = typeChanged
|
||||
|| (oldDef != null && requiresReplacement(resourceType, oldDef.path("Properties"), newDef.path("Properties"), changedParams, changedConditions))
|
||||
|| (oldDef != null && replacementDecider.decide(resourceType, logicalId, oldDef, newDef))
|
||||
|| createOnlyReferencesReplaced;
|
||||
// A create-only value that reads an attribute the update changes in place may
|
||||
// or may not move: only the update knows, as AWS's Conditional says.
|
||||
boolean conditional = !replacement && anyCreateOnlyValue(resourceType, props,
|
||||
subtree -> inPlaceChangedAttributes.entrySet().stream().anyMatch(entry ->
|
||||
referencesAnyAttribute(subtree, entry.getKey(), entry.getValue(),
|
||||
newConditions, dependencyEngine)));
|
||||
String replacementState = replacement ? REPLACEMENT_TRUE
|
||||
: conditional ? REPLACEMENT_CONDITIONAL : REPLACEMENT_FALSE;
|
||||
if (replacement && replacedResourceIds.add(logicalId)) {
|
||||
anyNewChange = true;
|
||||
}
|
||||
if (!alreadyChangedIds.contains(logicalId)) {
|
||||
if (alreadyChangedIds.contains(logicalId)) {
|
||||
raiseReplacement(changes, logicalId, replacementState);
|
||||
} else {
|
||||
alreadyChangedIds.add(logicalId);
|
||||
changes.add(new ResourceChange("Modify", logicalId,
|
||||
resourcePhysicalId(stack, logicalId), resourceType,
|
||||
replacement ? "True" : "False"));
|
||||
resourcePhysicalId(stack, logicalId), resourceType, replacementState));
|
||||
anyNewChange = true;
|
||||
Set<String> attrs = expectedChangedAttributes(resourceType, oldDef, newDef);
|
||||
if (!attrs.isEmpty()) {
|
||||
@@ -1306,6 +1349,47 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** The values of {@code ResourceChange.Replacement} that AWS defines. */
|
||||
private static final String REPLACEMENT_TRUE = "True";
|
||||
private static final String REPLACEMENT_FALSE = "False";
|
||||
private static final String REPLACEMENT_CONDITIONAL = "Conditional";
|
||||
|
||||
/**
|
||||
* Raises the Replacement of a change already in the list when a later pass of the dependency
|
||||
* walk proves more: False to Conditional or True, Conditional to True. It never lowers one.
|
||||
*/
|
||||
private static void raiseReplacement(List<ResourceChange> changes, String logicalId, String replacement) {
|
||||
for (int i = 0; i < changes.size(); i++) {
|
||||
ResourceChange change = changes.get(i);
|
||||
if (change.logicalResourceId().equals(logicalId)
|
||||
&& replacementRank(replacement) > replacementRank(change.replacement())) {
|
||||
changes.set(i, new ResourceChange(change.action(), change.logicalResourceId(),
|
||||
change.physicalResourceId(), change.resourceType(), replacement));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int replacementRank(String replacement) {
|
||||
return REPLACEMENT_TRUE.equals(replacement) ? 2 : REPLACEMENT_CONDITIONAL.equals(replacement) ? 1 : 0;
|
||||
}
|
||||
|
||||
/** Whether the test holds for any create-only value of the properties: a registry pointer, or a table field. */
|
||||
private static boolean anyCreateOnlyValue(String resourceType, JsonNode props, Predicate<JsonNode> test) {
|
||||
if (props == null || !props.isObject()) {
|
||||
return false;
|
||||
}
|
||||
if (CfnCreateOnlyProperties.hasSchema(resourceType)) {
|
||||
return CfnCreateOnlyProperties.createOnlySubtrees(resourceType, props).stream().anyMatch(test);
|
||||
}
|
||||
for (Iterator<String> it = props.fieldNames(); it.hasNext(); ) {
|
||||
String field = it.next();
|
||||
if (CfnCreateOnlyProperties.isCreateOnly(resourceType, field) && test.test(props.get(field))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** True if a resource's definition references any of the given (changed) parameter names. */
|
||||
private boolean referencesAnyParameter(JsonNode resourceDef, Set<String> parameterNames) {
|
||||
if (parameterNames.isEmpty()) {
|
||||
@@ -1336,6 +1420,239 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether a modified resource's change replaces it, for the change set. For a type in the
|
||||
* create-only table the values decide, not the template text: both property sets are resolved
|
||||
* against the state the stack is in (parameters, conditions, mappings, imports, the ids and
|
||||
* attributes of its resources), so {@code !Ref App} and {@code !Join ['', [!Ref App]]} are one
|
||||
* value. A dynamic reference is compared through the forms the diff kept, which hold a digest
|
||||
* of the value it resolved to when the stack was last deployed. The template text is the answer only where a
|
||||
* value cannot be resolved. A value that reads a resource replaced in the same update has no id
|
||||
* to compare yet, and stays a replacement through the dependency pass of the diff.
|
||||
*
|
||||
* <p>A dynamic reference on either side of a create-only property sends the decision to the
|
||||
* compared forms. Those hold an HMAC digest of what a reference resolved to, never the value,
|
||||
* so a plain value on the other side is digested under the same key before the two are compared.
|
||||
* A form made up for a reference whose old value the stack never recorded is no evidence about
|
||||
* it (it is recognised by identity, not by its text): that property alone is decided by its
|
||||
* template text, the others by the compared forms. The diff itself still reports such a resource
|
||||
* as changed, which converges it.
|
||||
*
|
||||
* <p>The dependency pass marks a resource whose create-only value reads an attribute that changes
|
||||
* in place as {@code Conditional}, as AWS does for a replacement that depends on a value known
|
||||
* only during the update. {@code ExecuteChangeSet} then decides from the resolved values.
|
||||
*/
|
||||
private final class ReplacementDecider {
|
||||
private final Stack stack;
|
||||
private final String region;
|
||||
private final JsonNode[] compared;
|
||||
private final Map<String, String> oldParams;
|
||||
private final Map<String, String> newParams;
|
||||
private final Map<String, Boolean> oldConditions;
|
||||
private final Map<String, Boolean> newConditions;
|
||||
private final JsonNode oldTemplate;
|
||||
private final JsonNode newTemplate;
|
||||
private final Set<String> changedParams;
|
||||
private final Set<String> changedConditions;
|
||||
/** The compared forms that stand for a resolved dynamic reference, not for a plain value. */
|
||||
private final Set<String> referenceForms;
|
||||
/** The compared forms of the deployed template that carry no evidence about the old value. */
|
||||
private final Set<String> noEvidenceForms;
|
||||
/** Logical ids whose resolution failure was logged in this computation. */
|
||||
private final Set<String> warned = new HashSet<>();
|
||||
|
||||
ReplacementDecider(Stack stack, String region, JsonNode[] compared, Map<String, String> oldParams,
|
||||
Map<String, String> newParams, Map<String, Boolean> oldConditions,
|
||||
Map<String, Boolean> newConditions, JsonNode oldTemplate, JsonNode newTemplate,
|
||||
Set<String> changedParams, Set<String> changedConditions,
|
||||
Set<String> currentReferenceForms, Set<String> noEvidenceForms) {
|
||||
this.stack = stack;
|
||||
this.region = region;
|
||||
this.compared = compared;
|
||||
this.oldParams = oldParams;
|
||||
this.newParams = newParams;
|
||||
this.oldConditions = oldConditions;
|
||||
this.newConditions = newConditions;
|
||||
this.oldTemplate = oldTemplate;
|
||||
this.newTemplate = newTemplate;
|
||||
this.changedParams = changedParams;
|
||||
this.changedConditions = changedConditions;
|
||||
this.referenceForms = new HashSet<>(stack.dynamicReferenceDigestsSnapshot().values());
|
||||
this.referenceForms.addAll(currentReferenceForms);
|
||||
this.referenceForms.addAll(noEvidenceForms);
|
||||
this.noEvidenceForms = noEvidenceForms;
|
||||
}
|
||||
|
||||
boolean decide(String resourceType, String logicalId, JsonNode oldDef, JsonNode newDef) {
|
||||
JsonNode oldProps = oldDef.path("Properties");
|
||||
JsonNode newProps = newDef.path("Properties");
|
||||
boolean asWritten = requiresReplacement(resourceType, oldProps, newProps, changedParams,
|
||||
changedConditions);
|
||||
if (!CfnCreateOnlyProperties.hasSchema(resourceType) || !oldProps.isObject() || !newProps.isObject()) {
|
||||
return asWritten || comparedChanged(resourceType, logicalId, oldProps, newProps);
|
||||
}
|
||||
boolean dynamic = anyCreateOnlyValue(resourceType, oldProps, ReplacementDecider::holdsDynamicReference)
|
||||
|| anyCreateOnlyValue(resourceType, newProps, ReplacementDecider::holdsDynamicReference);
|
||||
Boolean resolved = resolvedChange(resourceType, logicalId, oldProps, newProps);
|
||||
if (resolved == null) {
|
||||
return asWritten || comparedChanged(resourceType, logicalId, oldProps, newProps);
|
||||
}
|
||||
if (dynamic) {
|
||||
return compared == null || compared[0] == null
|
||||
? asWritten : comparedChanged(resourceType, logicalId, oldProps, newProps);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
private static boolean holdsDynamicReference(JsonNode subtree) {
|
||||
return CfnDynamicReferences.holdsDynamicReference(subtree.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a create-only property differs, decided per property: between the compared forms
|
||||
* (a reference's digest against a plain value's), or, where the old form carries no evidence,
|
||||
* by the template text of that property alone.
|
||||
*/
|
||||
private boolean comparedChanged(String resourceType, String logicalId, JsonNode oldProps,
|
||||
JsonNode newProps) {
|
||||
if (compared == null || compared[0] == null || compared[1] == null
|
||||
|| !CfnCreateOnlyProperties.hasSchema(resourceType)) {
|
||||
return false;
|
||||
}
|
||||
JsonNode before = compared[0].path(logicalId).path("Properties");
|
||||
JsonNode after = compared[1].path(logicalId).path("Properties");
|
||||
if (!before.isObject() || !after.isObject()) {
|
||||
return false;
|
||||
}
|
||||
JsonNode digestedBefore = digested(before);
|
||||
JsonNode digestedAfter = digested(after);
|
||||
for (String pointer : CfnCreateOnlyProperties.getCreateOnlyProperties(resourceType)) {
|
||||
boolean changed = noEvidence(pointer, before)
|
||||
? writtenPointerChanged(pointer, oldProps, newProps)
|
||||
: CfnCreateOnlyProperties.createOnlyPointerChanged(pointer, digestedBefore, digestedAfter);
|
||||
if (changed) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether the old compared form under the pointer holds a form made up for a missing digest. */
|
||||
private boolean noEvidence(String pointer, JsonNode oldCompared) {
|
||||
return CfnCreateOnlyProperties.subtreesAt(pointer, oldCompared).stream()
|
||||
.anyMatch(subtree -> holdsText(subtree, noEvidenceForms::contains));
|
||||
}
|
||||
|
||||
/** The answer of the template text for one pointer, as {@code requiresReplacement} gives it for all. */
|
||||
private boolean writtenPointerChanged(String pointer, JsonNode oldProps, JsonNode newProps) {
|
||||
return CfnCreateOnlyProperties.createOnlyPointerChanged(pointer, oldProps, newProps)
|
||||
|| CfnCreateOnlyProperties.subtreesAt(pointer, newProps).stream().anyMatch(subtree ->
|
||||
referencesAnyParameter(subtree, changedParams)
|
||||
|| referencesAnyCondition(subtree, changedConditions));
|
||||
}
|
||||
|
||||
private static boolean holdsText(JsonNode node, Predicate<String> test) {
|
||||
if (node.isTextual()) {
|
||||
return test.test(node.textValue());
|
||||
}
|
||||
for (JsonNode child : node) {
|
||||
if (holdsText(child, test)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The node with every plain text value replaced by the digest the stack would keep for it. */
|
||||
private JsonNode digested(JsonNode node) {
|
||||
if (node.isTextual()) {
|
||||
return referenceForms.contains(node.textValue()) ? node
|
||||
: TextNode.valueOf(dynamicReferenceDigest(stack, node.textValue()));
|
||||
}
|
||||
if (node.isObject()) {
|
||||
ObjectNode out = objectMapper.createObjectNode();
|
||||
node.fields().forEachRemaining(e -> out.set(e.getKey(), digested(e.getValue())));
|
||||
return out;
|
||||
}
|
||||
if (node.isArray()) {
|
||||
ArrayNode out = objectMapper.createArrayNode();
|
||||
node.forEach(child -> out.add(digested(child)));
|
||||
return out;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Whether a create-only value differs once both sides are resolved; null when one cannot be. */
|
||||
private Boolean resolvedChange(String resourceType, String logicalId, JsonNode oldProps,
|
||||
JsonNode newProps) {
|
||||
try {
|
||||
Map<String, String> physicalIds = new HashMap<>();
|
||||
Map<String, Map<String, String>> attributes = new HashMap<>();
|
||||
for (StackResource resource : stack.resourcesSnapshot().values()) {
|
||||
if (resource.getPhysicalId() != null) {
|
||||
physicalIds.put(resource.getLogicalId(), resource.getPhysicalId());
|
||||
attributes.put(resource.getLogicalId(), resource.getAttributes());
|
||||
}
|
||||
}
|
||||
String accountId = ownerAccount(stack);
|
||||
return CfnCreateOnlyProperties.createOnlyValueChanged(resourceType,
|
||||
engineOver(accountId, oldParams, physicalIds, attributes, oldConditions, oldTemplate)
|
||||
.resolveNode(oldProps),
|
||||
engineOver(accountId, newParams, physicalIds, attributes, newConditions, newTemplate)
|
||||
.resolveNode(newProps));
|
||||
} catch (RuntimeException e) {
|
||||
if (warned.add(logicalId)) {
|
||||
LOG.warnv("Create-only values of {0} ({1}) could not be resolved for the diff; "
|
||||
+ "the preview falls back to the template text: {2}", logicalId, resourceType,
|
||||
e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engineOver(String accountId, Map<String, String> params,
|
||||
Map<String, String> physicalIds,
|
||||
Map<String, Map<String, String>> attributes,
|
||||
Map<String, Boolean> conditions, JsonNode template) {
|
||||
return new CloudFormationTemplateEngine(accountId, region, stack.getStackName(), stack.getStackId(),
|
||||
params, physicalIds, attributes, conditions, templateMappings(template), objectMapper,
|
||||
name -> exports.get(accountExportKey(accountId, exportKey(region, name))), value -> value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a create-only property resolves differently now than the previous template resolved
|
||||
* to under the previous deployment: its own parameters, conditions and mappings, and the ids
|
||||
* and attributes the update started from ({@code previous}). The preview cannot see this for a
|
||||
* resource the update itself changed after the preview was computed. A value that cannot be
|
||||
* resolved, or a previous deployment that is not known ({@code previous} null), is no evidence
|
||||
* of a change.
|
||||
*/
|
||||
private static boolean resolvedCreateOnlyChanged(String resourceType, String logicalId, JsonNode priorProps,
|
||||
JsonNode props, CloudFormationTemplateEngine current,
|
||||
CloudFormationTemplateEngine previous) {
|
||||
if (previous == null || priorProps == null || props == null
|
||||
|| !CfnCreateOnlyProperties.hasSchema(resourceType)) {
|
||||
return false;
|
||||
}
|
||||
boolean dynamic = false;
|
||||
for (JsonNode subtree : CfnCreateOnlyProperties.createOnlySubtrees(resourceType, props)) {
|
||||
String text = subtree.toString();
|
||||
dynamic |= text.contains("\"Ref\"") || text.contains("\"Fn::");
|
||||
}
|
||||
if (!dynamic) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return CfnCreateOnlyProperties.createOnlyValueChanged(resourceType,
|
||||
previous.resolveNode(priorProps), current.resolveNode(props));
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv("Resolved create-only values of {0} ({1}) could not be compared; the update adds no "
|
||||
+ "replacement beyond the engine's own decision: {2}", logicalId, resourceType, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean requiresReplacement(String resourceType, JsonNode oldProps, JsonNode newProps,
|
||||
Set<String> changedParams, Set<String> changedConditions) {
|
||||
if (oldProps == null || newProps == null || oldProps.isMissingNode() || newProps.isMissingNode()) {
|
||||
@@ -2352,12 +2669,20 @@ public class CloudFormationService implements ResourceProvider {
|
||||
Set<String> attemptedResourceIds = new LinkedHashSet<>();
|
||||
try {
|
||||
Map<String, JsonNode[]> comparedProperties = new HashMap<>();
|
||||
Set<String> replacedResourceIds = new HashSet<>();
|
||||
Set<String> changedResourceIds = isCreate
|
||||
? Set.of()
|
||||
: changedResourceIds(stack, templateBody, params, region, comparedProperties);
|
||||
JsonNode previousResources = isCreate
|
||||
? objectMapper.missingNode()
|
||||
: previousResources(stack, previousState, region, accountId);
|
||||
: changedResourceIds(stack, templateBody, params, region, comparedProperties,
|
||||
replacedResourceIds);
|
||||
// The previous deployment: its template, parameters (as the change-set preview takes
|
||||
// them: raw ones for a stack persisted before resolvedParameters existed) and conditions.
|
||||
Map<String, String> previousParams = previousState.deployedParameters();
|
||||
JsonNode parsedPrevious = isCreate ? objectMapper.missingNode()
|
||||
: parsePreviousTemplate(stack, previousState.templateBody());
|
||||
Map<String, Boolean> previousConditions = parsedPrevious.isMissingNode() ? null
|
||||
: previousConditions(stack, parsedPrevious, previousParams, region, accountId);
|
||||
JsonNode previousTemplate = previousConditions == null ? objectMapper.missingNode() : parsedPrevious;
|
||||
JsonNode previousResources = previousResources(previousTemplate, previousConditions);
|
||||
JsonNode template = parseTemplate(templateBody);
|
||||
stack.setOriginalTemplateBody(templateBody);
|
||||
|
||||
@@ -2399,8 +2724,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
Map<String, Boolean> conditions = resolveConditions(template, resolvedParams, stack, region, accountId);
|
||||
|
||||
// Mappings
|
||||
Map<String, JsonNode> mappings = new HashMap<>();
|
||||
template.path("Mappings").fields().forEachRemaining(e -> mappings.put(e.getKey(), e.getValue()));
|
||||
Map<String, JsonNode> mappings = templateMappings(template);
|
||||
|
||||
// Process resources in order
|
||||
JsonNode resources = template.path("Resources");
|
||||
@@ -2422,6 +2746,22 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
// The state the update started from, so a resolved value can be compared with what the
|
||||
// previous template resolved to while the loop below changes ids and attributes.
|
||||
Map<String, String> startPhysicalIds = new LinkedHashMap<>(physicalIds);
|
||||
Map<String, Map<String, String>> startResourceAttrs = new LinkedHashMap<>();
|
||||
resourceAttrs.forEach((id, attrs) -> startResourceAttrs.put(id, new HashMap<>(attrs)));
|
||||
|
||||
BiFunction<Map<String, String>, Map<String, Map<String, String>>, CloudFormationTemplateEngine> engineFor =
|
||||
(ids, attributes) -> deploymentEngine(stack, region, accountId, resolvedParams, ids, attributes,
|
||||
conditions, mappings, parameterTypes, resources);
|
||||
// What the previous template resolved to under the deployment it ran in, over the state
|
||||
// the update started from; null when that deployment is not known.
|
||||
CloudFormationTemplateEngine previousEngine = previousTemplate.isMissingNode() ? null
|
||||
: deploymentEngine(stack, region, accountId, previousParams, startPhysicalIds,
|
||||
startResourceAttrs, previousConditions, templateMappings(previousTemplate),
|
||||
parameterTypes(previousTemplate), previousTemplate.path("Resources"));
|
||||
|
||||
StackResource failedResource = null;
|
||||
if (resources.isObject()) {
|
||||
List<String> sortedLogicalIds = topologicalSort(resources, conditions);
|
||||
@@ -2450,16 +2790,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
String type = resDef.path("Type").asText();
|
||||
String deletionPolicy = resDef.path("DeletionPolicy").asText(null);
|
||||
|
||||
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(
|
||||
accountId, region, stack.getStackName(),
|
||||
stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper,
|
||||
name -> exports.get(accountExportKey(accountId, exportKey(region, name))),
|
||||
value -> dynamicReferences.resolveDynamicReferences(value, region, false),
|
||||
(name, output, outputRegion, roleArn) ->
|
||||
resolveStackOutput(accountId, name, output, outputRegion, roleArn),
|
||||
parameterTypes,
|
||||
(id, attribute, value) -> dispatcher.attributeValue(
|
||||
resources.path(id).path("Type").asText(), attribute, value));
|
||||
CloudFormationTemplateEngine engine = engineFor.apply(physicalIds, resourceAttrs);
|
||||
// AWS::NoValue removes the property, wherever the template puts it, so no
|
||||
// provisioner sees it: not a member, a list item or a whole property.
|
||||
JsonNode props = engine.omitNoValue(resDef.path("Properties"));
|
||||
@@ -2507,11 +2838,19 @@ public class CloudFormationService implements ResourceProvider {
|
||||
? previousDefinition.path("Properties") : null;
|
||||
JsonNode provisionProps = props.isMissingNode() ? null : props;
|
||||
JsonNode[] comparedForms = comparedProperties.get(logicalId);
|
||||
boolean updating = ProvisionContext.isUpdate(resource.getPhysicalId());
|
||||
// The preview's Replacement, or a create-only value that resolves differently now
|
||||
// than it did when the stack was last updated: a resource this update changed
|
||||
// after the preview was computed (a GetAtt of a resource whose attributes moved).
|
||||
boolean replaces = replacedResourceIds.contains(logicalId)
|
||||
|| (updating && resolvedCreateOnlyChanged(type, logicalId, priorProps, provisionProps, engine,
|
||||
previousEngine));
|
||||
PropertyChanges changes = PropertyChanges.between(type,
|
||||
ProvisionContext.isUpdate(resource.getPhysicalId()), priorProps,
|
||||
updating, priorProps,
|
||||
provisionProps,
|
||||
comparedForms != null ? comparedForms[0] : null,
|
||||
comparedForms != null ? comparedForms[1] : null);
|
||||
comparedForms != null ? comparedForms[1] : null,
|
||||
updating ? replaces : null);
|
||||
resource = dispatcher.provision(logicalId, type, provisionProps,
|
||||
engine, region, accountId, stack.getStackName(),
|
||||
resource.getPhysicalId(), resource.getAttributes(),
|
||||
@@ -2784,10 +3123,13 @@ public class CloudFormationService implements ResourceProvider {
|
||||
/**
|
||||
* The ids of the resources an update adds or modifies. {@code comparedProperties} receives, for
|
||||
* the modified ones the diff compared, the {@code Properties} of the compared forms, previous
|
||||
* then current; see the change-set diff it comes from.
|
||||
* then current; see the change-set diff it comes from. {@code replacedIds} receives the modified
|
||||
* ones whose change says {@code Replacement: True}, so an update replaces exactly what the
|
||||
* preview said it would.
|
||||
*/
|
||||
private Set<String> changedResourceIds(Stack stack, String templateBody, Map<String, String> params,
|
||||
String region, Map<String, JsonNode[]> comparedProperties) {
|
||||
String region, Map<String, JsonNode[]> comparedProperties,
|
||||
Set<String> replacedIds) {
|
||||
ChangeSet changeSet = new ChangeSet();
|
||||
changeSet.setStackName(stack.getStackName());
|
||||
changeSet.setStackId(stack.getStackId());
|
||||
@@ -2799,6 +3141,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
for (ResourceChange change : computeChangeSetChanges(changeSet, region, comparedProperties)) {
|
||||
if ("Add".equals(change.action()) || "Modify".equals(change.action())) {
|
||||
changedResourceIds.add(change.logicalResourceId());
|
||||
if (REPLACEMENT_TRUE.equals(change.replacement())) {
|
||||
replacedIds.add(change.logicalResourceId());
|
||||
}
|
||||
}
|
||||
}
|
||||
return changedResourceIds;
|
||||
@@ -3472,29 +3817,29 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* was never applied and is left out. Missing when there is no previous template, and when it no
|
||||
* longer parses: the update then proceeds as if nothing had been declared.
|
||||
*/
|
||||
private JsonNode previousResources(Stack stack, StackUpdateSnapshot previousState, String region,
|
||||
String accountId) {
|
||||
if (previousState.templateBody() == null) {
|
||||
private JsonNode previousResources(JsonNode previousTemplate, Map<String, Boolean> conditions) {
|
||||
if (previousTemplate.isMissingNode()) {
|
||||
return previousTemplate;
|
||||
}
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
for (Map.Entry<String, JsonNode> entry : previousTemplate.path("Resources").properties()) {
|
||||
JsonNode definition = entry.getValue();
|
||||
ObjectNode applied = resources.putObject(entry.getKey());
|
||||
applied.set("Type", definition.path("Type"));
|
||||
if (definition.path("Properties").isObject()) {
|
||||
applied.set("Properties", appliedProperties(definition.path("Properties"), conditions));
|
||||
}
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
/** The previous template, or a missing node when the stack has none or it no longer parses. */
|
||||
private JsonNode parsePreviousTemplate(Stack stack, String body) {
|
||||
if (body == null) {
|
||||
return objectMapper.missingNode();
|
||||
}
|
||||
try {
|
||||
JsonNode previousTemplate = parseTemplate(previousState.templateBody());
|
||||
// As the change-set preview does: raw parameters for a stack persisted before
|
||||
// resolvedParameters existed.
|
||||
Map<String, String> previousParams = previousState.resolvedParameters().isEmpty()
|
||||
? previousState.parameters() : previousState.resolvedParameters();
|
||||
Map<String, Boolean> conditions = resolveConditions(previousTemplate, previousParams, stack, region,
|
||||
accountId);
|
||||
ObjectNode resources = objectMapper.createObjectNode();
|
||||
for (Map.Entry<String, JsonNode> entry : previousTemplate.path("Resources").properties()) {
|
||||
JsonNode definition = entry.getValue();
|
||||
ObjectNode applied = resources.putObject(entry.getKey());
|
||||
applied.set("Type", definition.path("Type"));
|
||||
if (definition.path("Properties").isObject()) {
|
||||
applied.set("Properties", appliedProperties(definition.path("Properties"), conditions));
|
||||
}
|
||||
}
|
||||
return resources;
|
||||
return parseTemplate(body);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Previous template of stack {0} could not be evaluated ({1}); its updated resources see no prior properties",
|
||||
stack.getStackName(), e.getMessage());
|
||||
@@ -3502,6 +3847,46 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/** The previous template's conditions under its own parameters; null when they do not evaluate. */
|
||||
private Map<String, Boolean> previousConditions(Stack stack, JsonNode previousTemplate,
|
||||
Map<String, String> previousParams, String region,
|
||||
String accountId) {
|
||||
try {
|
||||
return resolveConditions(previousTemplate, previousParams, stack, region, accountId);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Conditions of the previous template of stack {0} could not be resolved ({1}); its updated "
|
||||
+ "resources see no prior properties", stack.getStackName(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, JsonNode> templateMappings(JsonNode template) {
|
||||
Map<String, JsonNode> mappings = new HashMap<>();
|
||||
if (template != null) {
|
||||
template.path("Mappings").fields().forEachRemaining(e -> mappings.put(e.getKey(), e.getValue()));
|
||||
}
|
||||
return mappings;
|
||||
}
|
||||
|
||||
/** An engine for one deployment's template: its parameters, conditions, mappings and resource types. */
|
||||
private CloudFormationTemplateEngine deploymentEngine(Stack stack, String region, String accountId,
|
||||
Map<String, String> params, Map<String, String> ids,
|
||||
Map<String, Map<String, String>> attributes,
|
||||
Map<String, Boolean> conditions,
|
||||
Map<String, JsonNode> mappings,
|
||||
Map<String, String> parameterTypes, JsonNode resources) {
|
||||
return new CloudFormationTemplateEngine(
|
||||
accountId, region, stack.getStackName(),
|
||||
stack.getStackId(), params, ids, attributes, conditions, mappings, objectMapper,
|
||||
name -> exports.get(accountExportKey(accountId, exportKey(region, name))),
|
||||
value -> dynamicReferences.resolveDynamicReferences(value, region, false),
|
||||
(name, output, outputRegion, roleArn) ->
|
||||
resolveStackOutput(accountId, name, output, outputRegion, roleArn),
|
||||
parameterTypes,
|
||||
(id, attribute, value) -> dispatcher.attributeValue(
|
||||
resources.path(id).path("Type").asText(), attribute, value));
|
||||
}
|
||||
|
||||
/**
|
||||
* The top-level properties left after each one's {@code Fn::If} is decided, without those that
|
||||
* chose {@code AWS::NoValue}. Decided as the template engine decides it: a condition the
|
||||
|
||||
@@ -32,4 +32,9 @@ public record StackUpdateSnapshot(
|
||||
this(templateBody, originalTemplateBody, parameters, resolvedParameters, outputs, exports,
|
||||
outputExportNames, resources, null);
|
||||
}
|
||||
|
||||
/** The parameter values the template was deployed with: the resolved ones, else the raw ones of an older stack. */
|
||||
public Map<String, String> deployedParameters() {
|
||||
return resolvedParameters.isEmpty() ? parameters : resolvedParameters;
|
||||
}
|
||||
}
|
||||
+3
-6
@@ -173,11 +173,9 @@ public class AppConfigCfnProvisioner implements CfnResourceProvisioner {
|
||||
String description = optionalText(PROFILE, props, "Description", DESCRIPTION_MAX_LENGTH, ctx);
|
||||
allowed(PROFILE, "DeletionProtectionCheck", text(props, "DeletionProtectionCheck", ctx),
|
||||
DELETION_PROTECTION_CHECKS);
|
||||
ObjectNode createOnly = MAPPER.createObjectNode()
|
||||
.put("ApplicationId", applicationId)
|
||||
.put("LocationUri", locationUri)
|
||||
.put("Type", type);
|
||||
if (updating && madeFrom(r, createOnly)) {
|
||||
// The engine's change decides: ApplicationId and LocationUri are create-only in the registry.
|
||||
// A Type change is accepted and not applied: UpdateConfigurationProfile has no Type member.
|
||||
if (updating && !ctx.changes(PROFILE, props).requiresReplacement()) {
|
||||
ConfigurationProfile current = service.findConfigurationProfile(ctx.priorPhysicalId())
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Configuration profile not found", 404));
|
||||
@@ -194,7 +192,6 @@ public class AppConfigCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.setPhysicalId(profile.getId());
|
||||
r.getAttributes().put("ConfigurationProfileId", profile.getId());
|
||||
r.getAttributes().put(APPLICATION_ATTR, profile.getApplicationId());
|
||||
r.getAttributes().put(CREATE_ONLY_ATTR, createOnly.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+13
-1
@@ -11,6 +11,8 @@ import io.floci.aws.services.ssm.model.ParameterHistory;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.MatchResult;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -39,6 +41,16 @@ public class CfnDynamicReferences {
|
||||
}
|
||||
|
||||
private static final Pattern DYNAMIC_REF = Pattern.compile("\\{\\{resolve:([a-z-]+):(.*?)\\}\\}");
|
||||
/** Whether a string holds the start of a dynamic reference, closed or not. */
|
||||
public static boolean holdsDynamicReference(String value) {
|
||||
return value.contains("{{resolve:");
|
||||
}
|
||||
|
||||
/** The dynamic reference texts a string holds, without the text around them; never a resolved value. */
|
||||
public static List<String> referencesIn(String value) {
|
||||
return DYNAMIC_REF.matcher(value).results().map(MatchResult::group).toList();
|
||||
}
|
||||
|
||||
private static final Pattern SSM_DYNAMIC_REF_BODY =
|
||||
Pattern.compile("([a-zA-Z0-9_.\\-/]+)(?::([0-9]+))?");
|
||||
|
||||
@@ -50,7 +62,7 @@ public class CfnDynamicReferences {
|
||||
* MasterUserPassword sourced from a generated secret). Unsupported services are left verbatim.
|
||||
*/
|
||||
public String resolveDynamicReferences(String value, String region, boolean allowSsmSecure) {
|
||||
if (value == null || !value.contains("{{resolve:")) {
|
||||
if (value == null || !holdsDynamicReference(value)) {
|
||||
return value;
|
||||
}
|
||||
Matcher m = DYNAMIC_REF.matcher(value);
|
||||
|
||||
+5
-14
@@ -22,7 +22,6 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
@@ -46,7 +45,6 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
|
||||
private static final List<String> UNSUPPORTED_CLUSTER_PROPERTIES = List.of("CacheSecurityGroupNames",
|
||||
"NotificationTopicArn", "AZMode", "PreferredAvailabilityZones", "LogDeliveryConfigurations",
|
||||
"SnapshotArns", "SnapshotName");
|
||||
private static final String DEFAULT_NETWORK_TYPE = "ipv4";
|
||||
private static final int CLUSTER_ID_MAX_LENGTH = 50;
|
||||
private static final int SUBNET_GROUP_NAME_MAX_LENGTH = 255;
|
||||
|
||||
@@ -178,18 +176,11 @@ public class ElastiCacheCfnProvisioner implements CfnResourceProvisioner {
|
||||
Integer port = optionalInt(ctx.resolveOptional(props, "Port"));
|
||||
|
||||
CacheCluster prior = ctx.isUpdate() ? findCluster(ctx.priorPhysicalId()) : null;
|
||||
// Engine, CacheSubnetGroupName and NetworkType are create-only in AWS: a change replaces the
|
||||
// cluster, so an unnamed one gets a fresh generated id. Port is not compared, because the
|
||||
// emulator reports its own host proxy port rather than the requested one.
|
||||
String networkType = ctx.resolveOptional(props, "NetworkType");
|
||||
String desiredNetworkType = networkType == null || networkType.isBlank() ? DEFAULT_NETWORK_TYPE : networkType;
|
||||
// A cluster stored before the type was recorded reads as the default, which is what it was created with.
|
||||
String storedNetworkType = prior == null || prior.getNetworkType() == null
|
||||
? DEFAULT_NETWORK_TYPE : prior.getNetworkType();
|
||||
boolean createOnlyChanged = prior != null
|
||||
&& (!engine.equalsIgnoreCase(prior.getEngine())
|
||||
|| !Objects.equals(subnetGroup, prior.getCacheSubnetGroupName())
|
||||
|| !desiredNetworkType.equals(storedNetworkType));
|
||||
// The engine's change decides, as it does for the change set's Replacement: Port, SnapshotArns,
|
||||
// SnapshotName, Engine, CacheSubnetGroupName, NetworkType and ClusterName are create-only in the
|
||||
// registry. Port is read from the template, not the live cluster: the emulator reports its own
|
||||
// host proxy port rather than the requested one. An unnamed cluster gets a fresh generated id.
|
||||
boolean createOnlyChanged = prior != null && ctx.changes(CACHE_CLUSTER, props).requiresReplacement();
|
||||
if (createOnlyChanged && explicitName != null && explicitName.equals(ctx.priorPhysicalId())) {
|
||||
throw new AwsException("InvalidParameterValue", "Updating a create-only property of cache cluster "
|
||||
+ explicitName + " requires a new ClusterName", 400);
|
||||
|
||||
+27
-3
@@ -26,7 +26,7 @@ import java.util.Set;
|
||||
* {@code Fn::GetAtt} reads a resource this update replaces still reads UNCHANGED, so UNCHANGED
|
||||
* alone is no reason to skip a write.
|
||||
*/
|
||||
public record PropertyChanges(Map<String, PropertyChange> byName) {
|
||||
public record PropertyChanges(Map<String, PropertyChange> byName, boolean requiresReplacement) {
|
||||
|
||||
public enum Kind { ADDED, CHANGED, DROPPED, UNCHANGED }
|
||||
|
||||
@@ -43,6 +43,11 @@ public record PropertyChanges(Map<String, PropertyChange> byName) {
|
||||
: Collections.unmodifiableMap(new LinkedHashMap<>(byName));
|
||||
}
|
||||
|
||||
/** Changes that do not replace the resource. */
|
||||
public PropertyChanges(Map<String, PropertyChange> byName) {
|
||||
this(byName, false);
|
||||
}
|
||||
|
||||
/** What the provisioner's own inputs say, values compared as written. */
|
||||
public static PropertyChanges between(String resourceType, boolean update,
|
||||
JsonNode priorProperties, JsonNode properties) {
|
||||
@@ -56,6 +61,25 @@ public record PropertyChanges(Map<String, PropertyChange> byName) {
|
||||
public static PropertyChanges between(String resourceType, boolean update,
|
||||
JsonNode priorProperties, JsonNode properties,
|
||||
JsonNode comparedPrior, JsonNode comparedCurrent) {
|
||||
return between(resourceType, update, priorProperties, properties, comparedPrior, comparedCurrent, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The same, with the engine's own decision whether the update replaces the resource: the
|
||||
* change set's {@code Replacement}, which sees resolved values and the resources replaced
|
||||
* earlier in the same update. Without it, the decision is
|
||||
* {@link CfnCreateOnlyProperties#createOnlyValueChanged} on the two property sets, the rule
|
||||
* the change set applies to a template diff.
|
||||
*/
|
||||
public static PropertyChanges between(String resourceType, boolean update,
|
||||
JsonNode priorProperties, JsonNode properties,
|
||||
JsonNode comparedPrior, JsonNode comparedCurrent,
|
||||
Boolean engineReplacement) {
|
||||
boolean replaces = engineReplacement != null
|
||||
? engineReplacement
|
||||
: update && resourceType != null && priorProperties != null && priorProperties.isObject()
|
||||
&& properties != null && properties.isObject()
|
||||
&& CfnCreateOnlyProperties.createOnlyValueChanged(resourceType, priorProperties, properties);
|
||||
Map<String, PropertyChange> changes = new LinkedHashMap<>();
|
||||
boolean currentIsObject = properties != null && properties.isObject();
|
||||
if (!update || priorProperties == null || !priorProperties.isObject()) {
|
||||
@@ -63,7 +87,7 @@ public record PropertyChanges(Map<String, PropertyChange> byName) {
|
||||
properties.fieldNames().forEachRemaining(name -> changes.put(name,
|
||||
change(resourceType, name, Kind.ADDED, null, properties.get(name))));
|
||||
}
|
||||
return new PropertyChanges(changes);
|
||||
return new PropertyChanges(changes, replaces);
|
||||
}
|
||||
priorProperties.fieldNames().forEachRemaining(name -> {
|
||||
JsonNode before = priorProperties.get(name);
|
||||
@@ -86,7 +110,7 @@ public record PropertyChanges(Map<String, PropertyChange> byName) {
|
||||
}
|
||||
});
|
||||
}
|
||||
return new PropertyChanges(changes);
|
||||
return new PropertyChanges(changes, replaces);
|
||||
}
|
||||
|
||||
private static PropertyChange change(String resourceType, String name, Kind kind,
|
||||
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.services.cloudformation.model.Stack;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Parameter;
|
||||
import software.amazon.awssdk.services.elasticache.ElastiCacheClient;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.ParameterType;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.PROFILE_TYPE;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.appConfigApplication;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.createUpdateChangeSet;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.executeAndAwaitUpdate;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.json;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.physicalId;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.profileProperties;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.profileStack;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.replacement;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.subjectStack;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.subnetGroup;
|
||||
import static io.floci.aws.services.cloudformation.CfnStackTestSupport.vpcAndSubnet;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* An update replaces a resource exactly when its change set said {@code Replacement: True}, and the
|
||||
* change set's {@code Replacement} is the one AWS documents for the changed property ("Update
|
||||
* requires"). Covered: AppConfig profiles and ElastiCache clusters changed in a create-only and in
|
||||
* another property; a create-only value that is not plain template text (a dynamic reference
|
||||
* rewritten as the literal it resolves to, a value known only during the update, a value read from
|
||||
* a resource replaced in the same update, an attribute another resource moves while the update
|
||||
* runs); and a stack that holds no record of what its dynamic references resolved to.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CfnReplacementIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String APP_REF = "{\"Ref\": \"App\"}";
|
||||
private static final String CLUSTER = "\"Engine\": \"redis\", \"NumCacheNodes\": 1, ";
|
||||
|
||||
/** One update: its templates, what the change set says for {@code subject}, and whether it is replaced. */
|
||||
private record Row(String label, String before, String after, String subject, String preview,
|
||||
boolean replaced, Consumer<String> afterCreate, boolean needsDocker,
|
||||
String clusterSubnetGroupAfter) {
|
||||
|
||||
Row(String label, String before, String after, String subject, String preview, boolean replaced,
|
||||
Consumer<String> afterCreate) {
|
||||
this(label, before, after, subject, preview, replaced, afterCreate, false, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
@Inject
|
||||
CloudFormationService cloudFormationService;
|
||||
|
||||
/** A create-only row: {@code @V@} in the parameters becomes a before the update and b after it. */
|
||||
private static Row createOnlyRow(String label, String extraResources, String parameters, String type,
|
||||
String before, String after, String preview, boolean needsDocker,
|
||||
String clusterSubnetGroupAfter) {
|
||||
return new Row(label, subjectStack(extraResources, parameters, type, before).replace("@V@", "a"),
|
||||
subjectStack(extraResources, parameters, type, after).replace("@V@", "b"), "Subject", preview,
|
||||
"True".equals(preview), null, needsDocker, clusterSubnetGroupAfter);
|
||||
}
|
||||
|
||||
private static final String PROFILE = profileProperties(APP_REF, "");
|
||||
|
||||
/** The cluster names a subnet group whose own name comes from a parameter that changes in the update. */
|
||||
private static final Row SUBNET_GROUP_REPLACED = createOnlyRow("ElastiCache cluster in a replaced subnet group",
|
||||
json(vpcAndSubnet("10.73")
|
||||
+ "'SubnetGroup': {'Type': 'AWS::ElastiCache::SubnetGroup',"
|
||||
+ " 'Properties': {'CacheSubnetGroupName': {'Ref': 'Sg'}, 'Description': 'example',"
|
||||
+ " 'SubnetIds': [{'Ref': 'Subnet'}]}}"),
|
||||
"\"Sg\": {\"Type\": \"String\", \"Default\": \"repl-sng-@V@\"}",
|
||||
"AWS::ElastiCache::CacheCluster",
|
||||
CLUSTER + "\"CacheNodeType\": \"cache.t3.micro\", \"CacheSubnetGroupName\": {\"Ref\": \"SubnetGroup\"}",
|
||||
CLUSTER + "\"CacheNodeType\": \"cache.t3.micro\", \"CacheSubnetGroupName\": {\"Ref\": \"SubnetGroup\"}",
|
||||
"True", true, "repl-sng-b");
|
||||
|
||||
static Stream<Row> rows() {
|
||||
String app = appConfigApplication("replacement-orders");
|
||||
return Stream.of(
|
||||
createOnlyRow("AppConfig profile Type", app, "", PROFILE_TYPE,
|
||||
PROFILE + "\"LocationUri\": \"hosted\", \"Type\": \"AWS.Freeform\"",
|
||||
PROFILE + "\"LocationUri\": \"hosted\", \"Type\": \"AWS.AppConfig.FeatureFlags\"",
|
||||
"False", false, null),
|
||||
createOnlyRow("AppConfig profile LocationUri", app, "", PROFILE_TYPE,
|
||||
PROFILE + "\"LocationUri\": \"hosted\", \"Type\": \"AWS.Freeform\"",
|
||||
PROFILE + "\"LocationUri\": \"ssm-parameter://replacement-settings\","
|
||||
+ " \"Type\": \"AWS.Freeform\"",
|
||||
"True", false, null),
|
||||
createOnlyRow("ElastiCache cluster Port", "", "", "AWS::ElastiCache::CacheCluster",
|
||||
CLUSTER + "\"CacheNodeType\": \"cache.t3.micro\", \"Port\": 6379",
|
||||
CLUSTER + "\"CacheNodeType\": \"cache.t3.micro\", \"Port\": 6380",
|
||||
"True", true, null),
|
||||
createOnlyRow("ElastiCache cluster CacheNodeType", "", "", "AWS::ElastiCache::CacheCluster",
|
||||
CLUSTER + "\"CacheNodeType\": \"cache.t3.micro\"",
|
||||
CLUSTER + "\"CacheNodeType\": \"cache.t3.small\"",
|
||||
"False", true, null),
|
||||
SUBNET_GROUP_REPLACED,
|
||||
new Row("deployed parameter renamed, same value",
|
||||
locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"),
|
||||
locationStack(stringParameter("NameB", HOSTED), "", REF_B, "e"),
|
||||
"Subject", "False", false, null),
|
||||
new Row("deployed parameter value moved into a mapping",
|
||||
locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"),
|
||||
locationStack("", "\"M\": {\"k\": {\"v\": \"" + HOSTED + "\"}}",
|
||||
"{\"Fn::FindInMap\": [\"M\", \"k\", \"v\"]}", "e"),
|
||||
"Subject", "False", false, null),
|
||||
new Row("deployed parameter renamed, another value",
|
||||
locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"),
|
||||
locationStack(stringParameter("NameB", "ssm-parameter://deployed-other"), "", REF_B, "e"),
|
||||
"Subject", "True", true, null));
|
||||
}
|
||||
|
||||
private static final String HOSTED = "hosted";
|
||||
private static final String REF_A = "{\"Ref\": \"NameA\"}";
|
||||
private static final String REF_B = "{\"Ref\": \"NameB\"}";
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("rows")
|
||||
void aChangeSetReportsReplacementExactlyWhenTheUpdateChangesThePhysicalId(Row row) throws Exception {
|
||||
if (row.needsDocker()) {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the cache data plane");
|
||||
}
|
||||
String stack = "repl-" + Long.toString(System.nanoTime(), 36);
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1)) {
|
||||
CfnStackWaits.createStack(client, stack, row.before(), "CREATE_COMPLETE");
|
||||
String before = physicalId(client, stack, "Subject");
|
||||
|
||||
createUpdateChangeSet(client, stack, "change", row.after());
|
||||
assertEquals(List.of(row.preview()), replacement(client, stack, "change", "Subject"), row.label());
|
||||
|
||||
executeAndAwaitUpdate(client, stack, "change");
|
||||
String after = physicalId(client, stack, "Subject");
|
||||
|
||||
assertEquals(row.replaced(), !before.equals(after),
|
||||
row.label() + ": physical id " + before + " then " + after);
|
||||
if (row.clusterSubnetGroupAfter() != null) {
|
||||
try (ElastiCacheClient cache = AwsTestClients.create(
|
||||
ElastiCacheClient.builder(), "test", Region.US_EAST_1)) {
|
||||
assertEquals(row.clusterSubnetGroupAfter(), cache.describeCacheClusters(request ->
|
||||
request.cacheClusterId(after)).cacheClusters().getFirst().cacheSubnetGroupName());
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreateOnlyValueFromADynamicReferenceThatChangesReplacesTheResource() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stack = "repl-dynamic-" + suffix;
|
||||
String parameter = "/repl/location-" + suffix;
|
||||
String profile = "\"LocationUri\": \"{{resolve:ssm:" + parameter + "}}\", \"Type\": \"AWS.Freeform\"";
|
||||
String before = profileStack("replacement-orders", APP_REF, profile);
|
||||
String afterUpdate = profileStack("replacement-orders", APP_REF, profile + ", \"Description\": \"edited\"");
|
||||
try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
SsmClient ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1)) {
|
||||
ssm.putParameter(request -> request.name(parameter).type("String").value("ssm-parameter://orders-a"));
|
||||
CfnStackWaits.createStack(cfn, stack, before, "CREATE_COMPLETE");
|
||||
String profileBefore = physicalId(cfn, stack, "Subject");
|
||||
|
||||
ssm.putParameter(request -> request.name(parameter).type("String").value("ssm-parameter://orders-b")
|
||||
.overwrite(true));
|
||||
createUpdateChangeSet(cfn, stack, "change", afterUpdate);
|
||||
assertEquals(List.of("True"), replacement(cfn, stack, "change", "Subject"));
|
||||
|
||||
executeAndAwaitUpdate(cfn, stack, "change");
|
||||
String profileAfter = physicalId(cfn, stack, "Subject");
|
||||
|
||||
assertNotEquals(profileBefore, profileAfter, "the changed SSM value replaces the profile");
|
||||
String application = physicalId(cfn, stack, "App");
|
||||
given().contentType(ContentType.JSON)
|
||||
.get("/applications/" + application + "/configurationprofiles/" + profileAfter)
|
||||
.then().statusCode(200).body("LocationUri", equalTo("ssm-parameter://orders-b"));
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
private static String resolvedProfile(String locationUri, String description) {
|
||||
return profileStack("resolved-app", APP_REF, "\"LocationUri\": " + locationUri
|
||||
+ ", \"Type\": \"AWS.Freeform\", \"Description\": \"" + description + "\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDynamicReferenceWhoseStoredValueMovedReplacesTheProfile() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stack = "resolved-ssm-" + suffix;
|
||||
String parameter = "/resolved/" + suffix + "/location";
|
||||
String reference = "\"{{resolve:ssm:" + parameter + "}}\"";
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
SsmClient ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1)) {
|
||||
ssm.putParameter(request -> request.name(parameter).value("ssm-parameter://one")
|
||||
.type(ParameterType.STRING).overwrite(true));
|
||||
CfnStackWaits.createStack(client, stack, resolvedProfile(reference, "first"), "CREATE_COMPLETE");
|
||||
String before = physicalId(client, stack, "Subject");
|
||||
|
||||
ssm.putParameter(request -> request.name(parameter).value("ssm-parameter://two")
|
||||
.type(ParameterType.STRING).overwrite(true));
|
||||
createUpdateChangeSet(client, stack, "move", resolvedProfile(reference, "second"));
|
||||
assertEquals(List.of("True"), replacement(client, stack, "move", "Subject"));
|
||||
|
||||
executeAndAwaitUpdate(client, stack, "move");
|
||||
assertNotEquals(before, physicalId(client, stack, "Subject"), "the profile is replaced, as the preview said");
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefWrittenAsAJoinOfTheSameValueIsNotAChange() throws Exception {
|
||||
String stack = "resolved-join-" + Long.toString(System.nanoTime(), 36);
|
||||
String asRef = "{\"Ref\": \"App\"}";
|
||||
String asJoin = "{\"Fn::Join\": [\"\", [{\"Ref\": \"App\"}]]}";
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1)) {
|
||||
CfnStackWaits.createStack(client, stack, applicationTemplate(asRef, "first"), "CREATE_COMPLETE");
|
||||
String before = physicalId(client, stack, "Subject");
|
||||
|
||||
createUpdateChangeSet(client, stack, "rewrite", applicationTemplate(asJoin, "second"));
|
||||
assertEquals(List.of("False"), replacement(client, stack, "rewrite", "Subject"));
|
||||
|
||||
executeAndAwaitUpdate(client, stack, "rewrite");
|
||||
assertEquals(before, physicalId(client, stack, "Subject"), "the same ApplicationId keeps the profile");
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
private static String applicationTemplate(String applicationId, String description) {
|
||||
return profileStack("resolved-join-app", applicationId,
|
||||
"\"LocationUri\": \"hosted\", \"Description\": \"" + description + "\"");
|
||||
}
|
||||
|
||||
private static String launchTemplateFeedingProfile(String instanceType) {
|
||||
return subjectStack("\"Template\": {\"Type\": \"AWS::EC2::LaunchTemplate\", \"Properties\": {"
|
||||
+ "\"LaunchTemplateName\": \"at-execution\", \"LaunchTemplateData\": {\"InstanceType\": \""
|
||||
+ instanceType + "\"}}}," + appConfigApplication("at-exec"),
|
||||
"", PROFILE_TYPE, profileProperties(APP_REF, "\"LocationUri\":"
|
||||
+ " {\"Fn::Sub\": \"ssm-parameter://version-${Template.LatestVersionNumber}\"}"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreateOnlyPropertyReadingAnAttributeThatMovedReplacesTheResource() throws Exception {
|
||||
String stack = "at-exec-" + Long.toString(System.nanoTime(), 36);
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1)) {
|
||||
CfnStackWaits.createStack(client, stack, launchTemplateFeedingProfile("t3.micro"), "CREATE_COMPLETE");
|
||||
String before = physicalId(client, stack, "Subject");
|
||||
|
||||
CfnStackWaits.updateStack(client, stack, launchTemplateFeedingProfile("t3.small"), "UPDATE_COMPLETE");
|
||||
|
||||
assertNotEquals(before, physicalId(client, stack, "Subject"),
|
||||
"the profile's LocationUri resolves to another version, so it is replaced");
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
private static final String GROUP_NAME_TEMPLATE = """
|
||||
{"Parameters": {"GroupName": {"Type": "String"}},
|
||||
"Resources": {
|
||||
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.74.0.0/16"}},
|
||||
"Subnet": {"Type": "AWS::EC2::Subnet",
|
||||
"Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.74.0.0/24"}},
|
||||
"SubnetGroup": {"Type": "AWS::ElastiCache::SubnetGroup",
|
||||
"Properties": {"CacheSubnetGroupName": {"Ref": "GroupName"}, "Description": "example",
|
||||
"SubnetIds": [{"Ref": "Subnet"}]}},
|
||||
"Cluster": {"Type": "AWS::ElastiCache::CacheCluster",
|
||||
"Properties": {"Engine": "redis", "CacheNodeType": "cache.t3.micro", "NumCacheNodes": 1,
|
||||
"CacheSubnetGroupName": {"Ref": "SubnetGroup"}}}
|
||||
}}
|
||||
""";
|
||||
|
||||
@Test
|
||||
void aClusterReadingAReplacedSubnetGroupIsReplacedAsThePreviewSaid() throws Exception {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the cache data plane");
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stack = "repl-sng-" + suffix;
|
||||
String first = "sng-a-" + suffix;
|
||||
String second = "sng-b-" + suffix;
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
ElastiCacheClient cache = AwsTestClients.create(ElastiCacheClient.builder(), "test", Region.US_EAST_1)) {
|
||||
client.createStack(request -> request.stackName(stack).templateBody(GROUP_NAME_TEMPLATE)
|
||||
.parameters(Parameter.builder().parameterKey("GroupName").parameterValue(first).build()));
|
||||
CfnStackWaits.awaitStatus(client, stack, "CREATE_COMPLETE");
|
||||
String before = physicalId(client, stack, "Cluster");
|
||||
|
||||
createUpdateChangeSet(client, stack, "rename", GROUP_NAME_TEMPLATE,
|
||||
Parameter.builder().parameterKey("GroupName").parameterValue(second).build());
|
||||
assertEquals(List.of("True"), replacement(client, stack, "rename", "Cluster"));
|
||||
|
||||
executeAndAwaitUpdate(client, stack, "rename");
|
||||
|
||||
String after = physicalId(client, stack, "Cluster");
|
||||
assertNotEquals(before, after, "the cluster is replaced, as the preview said");
|
||||
assertEquals(second, cache.describeCacheClusters(request -> request.cacheClusterId(after))
|
||||
.cacheClusters().get(0).cacheSubnetGroupName());
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
private static String previewProfile(String locationUri, String description) {
|
||||
return profileStack("preview-app", APP_REF, json("\"LocationUri\": " + locationUri
|
||||
+ ", \"Type\": \"AWS.Freeform\", \"Description\": \"" + description + "\""));
|
||||
}
|
||||
|
||||
private static String tags(String value) {
|
||||
return "'Tags': [{'Key': 'owner', 'Value': '" + value + "'}]";
|
||||
}
|
||||
|
||||
/** Group names are {@code <prefix>-1} and {@code <prefix>-2}; the cluster picks one by the template's latest version. */
|
||||
private static String versionedCluster(String prefix, String instanceType, String tag) {
|
||||
return json("{'Resources': {" + vpcAndSubnet("10.81") + subnetGroup("Group1", prefix + "-1")
|
||||
+ subnetGroup("Group2", prefix + "-2")
|
||||
+ "'Template': {'Type': 'AWS::EC2::LaunchTemplate', 'Properties': {'LaunchTemplateName': '" + prefix
|
||||
+ "', 'LaunchTemplateData': {'InstanceType': '" + instanceType + "'}}},"
|
||||
+ "'Cluster': {'Type': 'AWS::ElastiCache::CacheCluster', 'DependsOn': ['Group1', 'Group2'],"
|
||||
+ " 'Properties': {'Engine': 'redis', 'CacheNodeType': 'cache.t3.micro', 'NumCacheNodes': 1,"
|
||||
+ " 'CacheSubnetGroupName': {'Fn::Join': ['', ['" + prefix + "-',"
|
||||
+ " {'Fn::GetAtt': ['Template', 'LatestVersionNumber']}]]}, " + tags(tag) + "}}}}");
|
||||
}
|
||||
|
||||
/** A cluster whose engine is {@code engine} (template text) and whose subnet group is the literal {@code group}. */
|
||||
private static String clusterInGroup(String engine, String group, String prefix) {
|
||||
return json("{'Resources': {" + vpcAndSubnet("10.83") + subnetGroup("Group1", prefix + "-1")
|
||||
+ subnetGroup("Group2", prefix + "-2")
|
||||
+ "'Cluster': {'Type': 'AWS::ElastiCache::CacheCluster', 'DependsOn': ['Group1', 'Group2'],"
|
||||
+ " 'Properties': {'Engine': " + engine + ", 'CacheNodeType': 'cache.t3.micro', 'NumCacheNodes': 1,"
|
||||
+ " 'CacheSubnetGroupName': '" + group + "'}}}}");
|
||||
}
|
||||
|
||||
private static String clusterReadingGroup(String groupName, String tag) {
|
||||
return json("{'Resources': {" + vpcAndSubnet("10.82") + subnetGroup("R0", groupName)
|
||||
+ "'R1': {'Type': 'AWS::ElastiCache::CacheCluster', 'Properties': {'Engine': 'redis',"
|
||||
+ " 'CacheNodeType': 'cache.t3.micro', 'NumCacheNodes': 1,"
|
||||
+ " 'CacheSubnetGroupName': {'Ref': 'R0'}, " + tags(tag) + "}}}}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDynamicReferenceRewrittenAsALiteralReplacesOnlyWhenTheValueDiffers() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String parameter = "/preview/" + suffix + "/location";
|
||||
String reference = "'{{resolve:ssm:" + parameter + "}}'";
|
||||
List<Row> rows = List.of(
|
||||
new Row("reference to the literal it resolves to", previewProfile(reference, "d"),
|
||||
previewProfile("'hosted'", "d"), "Subject", "False", false, null),
|
||||
new Row("reference to another literal", previewProfile(reference, "d"),
|
||||
previewProfile("'s3://b/k'", "d"), "Subject", "True", true, null));
|
||||
try (SsmClient ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1)) {
|
||||
ssm.putParameter(request -> request.name(parameter).value("hosted")
|
||||
.type(ParameterType.STRING).overwrite(true));
|
||||
assertAll(rows.stream().map(row -> () -> update(row, "a-" + rows.indexOf(row) + "-" + suffix)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValueKnownOnlyDuringTheUpdateIsConditionalAndADependentIsReplacedWithItsDependency() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String prefix = "lt" + suffix;
|
||||
String parameter = "/preview/" + suffix + "/unrecorded";
|
||||
String reference = "'{{resolve:ssm:" + parameter + "}}'";
|
||||
String engineParameter = "/preview/" + suffix + "/engine";
|
||||
String engineReference = "'{{resolve:ssm:" + engineParameter + "}}'";
|
||||
List<Row> rows = List.of(
|
||||
new Row("launch template changed in place", versionedCluster(prefix, "t3.micro", "1"),
|
||||
versionedCluster(prefix, "t3.small", "1"), "Cluster", "Conditional", true, null),
|
||||
new Row("launch template unchanged, tags only", versionedCluster(prefix + "x", "t3.micro", "1"),
|
||||
versionedCluster(prefix + "x", "t3.micro", "2"), "Cluster", "False", false, null),
|
||||
new Row("group replaced, cluster tags changed", clusterReadingGroup("sa-" + suffix, "1"),
|
||||
clusterReadingGroup("sb-" + suffix, "2"), "R1", "True", true, null),
|
||||
new Row("no recorded digests, only a description changes",
|
||||
previewProfile(reference, "d"), previewProfile(reference, "e"),
|
||||
"Subject", "False", false, this::forgetDigests),
|
||||
new Row("no record for one create-only property does not hide another one that changed",
|
||||
clusterInGroup(json(engineReference), "e" + suffix + "-1", "e" + suffix),
|
||||
clusterInGroup(json(engineReference), "e" + suffix + "-2", "e" + suffix),
|
||||
"Cluster", "True", true, this::forgetDigests),
|
||||
new Row("a digest of an unresolvable reference, only a description changes",
|
||||
previewProfile(reference, "d"), previewProfile(reference, "e"),
|
||||
"Subject", "False", false, this::storeUnresolvableDigests),
|
||||
new Row("a literal that starts with the unrecorded marker changes to another literal",
|
||||
previewProfile("'unrecorded one'", "d"), previewProfile("'unrecorded two'", "d"),
|
||||
"Subject", "True", true, null));
|
||||
try (SsmClient ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1)) {
|
||||
ssm.putParameter(request -> request.name(parameter).value("hosted")
|
||||
.type(ParameterType.STRING).overwrite(true));
|
||||
ssm.putParameter(request -> request.name(engineParameter).value("redis")
|
||||
.type(ParameterType.STRING).overwrite(true));
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the cache data plane");
|
||||
assertAll(rows.stream().map(row -> () -> update(row, "b-" + rows.indexOf(row) + "-" + suffix)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDigestSeamReallyEmptiesTheStackRecord() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stack = "seam-" + suffix;
|
||||
String parameter = "/preview/" + suffix + "/seam";
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
SsmClient ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1)) {
|
||||
ssm.putParameter(request -> request.name(parameter).value("hosted")
|
||||
.type(ParameterType.STRING).overwrite(true));
|
||||
CfnStackWaits.createStack(client, stack,
|
||||
previewProfile("'{{resolve:ssm:" + parameter + "}}'", "d"), "CREATE_COMPLETE");
|
||||
assertFalse(digests(stack).isEmpty(), "a stack created with a dynamic reference records its digest");
|
||||
forgetDigests(stack);
|
||||
assertTrue(digests(stack).isEmpty(), "the record is gone when read back");
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, String> digests(String stack) {
|
||||
return cloudFormationService.describeStacks(stack, REGION).getFirst().dynamicReferenceDigestsSnapshot();
|
||||
}
|
||||
|
||||
private void forgetDigests(String stack) {
|
||||
cloudFormationService.describeStacks(stack, REGION).getFirst().replaceDynamicReferenceDigests(Map.of());
|
||||
}
|
||||
|
||||
/** What an older stack may hold: a digest that stands for a reference that did not resolve. */
|
||||
private void storeUnresolvableDigests(String stack) {
|
||||
Stack current = cloudFormationService.describeStacks(stack, REGION).getFirst();
|
||||
Map<String, String> unresolvable = new LinkedHashMap<>();
|
||||
current.dynamicReferenceDigestsSnapshot().keySet()
|
||||
.forEach(key -> unresolvable.put(key, "unresolvable " + UUID.randomUUID()));
|
||||
current.replaceDynamicReferenceDigests(unresolvable);
|
||||
}
|
||||
|
||||
/** A profile whose create-only LocationUri is {@code locationUri}, read from {@code parameters} and {@code mappings}. */
|
||||
private static String locationStack(String parameters, String mappings, String locationUri, String description) {
|
||||
String template = subjectStack(appConfigApplication("deployed-app"), parameters, PROFILE_TYPE,
|
||||
profileProperties(APP_REF, "\"LocationUri\": " + locationUri + ", \"Description\": \""
|
||||
+ description + "\""));
|
||||
return mappings.isEmpty() ? template : "{\"Mappings\": {" + mappings + "}, " + template.substring(1);
|
||||
}
|
||||
|
||||
private static String stringParameter(String name, String value) {
|
||||
return "\"" + name + "\": {\"Type\": \"String\", \"Default\": \"" + value + "\"}";
|
||||
}
|
||||
|
||||
private static void update(Row row, String stack) throws Exception {
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1)) {
|
||||
CfnStackWaits.createStack(client, stack, row.before(), "CREATE_COMPLETE");
|
||||
String before = physicalId(client, stack, row.subject());
|
||||
if (row.afterCreate() != null) {
|
||||
row.afterCreate().accept(stack);
|
||||
}
|
||||
|
||||
createUpdateChangeSet(client, stack, "move", row.after());
|
||||
assertEquals(List.of(row.preview()), replacement(client, stack, "move", row.subject()), row.label());
|
||||
|
||||
executeAndAwaitUpdate(client, stack, "move");
|
||||
String after = physicalId(client, stack, row.subject());
|
||||
if (row.replaced()) {
|
||||
assertNotEquals(before, after, row.label() + ": the update replaces the resource");
|
||||
} else {
|
||||
assertEquals(before, after, row.label() + ": the update keeps the resource");
|
||||
}
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.ChangeSetType;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Parameter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* What the replacement integration tests share: a resource's physical id after a stack operation,
|
||||
* what a change set says about replacing one resource, and the templates they build.
|
||||
*/
|
||||
final class CfnStackTestSupport {
|
||||
|
||||
static final String PROFILE_TYPE = "AWS::AppConfig::ConfigurationProfile";
|
||||
|
||||
private CfnStackTestSupport() {
|
||||
}
|
||||
|
||||
static String physicalId(CloudFormationClient client, String stack, String logicalId) {
|
||||
return client.describeStackResource(request -> request.stackName(stack).logicalResourceId(logicalId))
|
||||
.stackResourceDetail().physicalResourceId();
|
||||
}
|
||||
|
||||
/** The {@code Replacement} value of every change the change set lists for {@code logicalId}. */
|
||||
static List<String> replacement(CloudFormationClient client, String stack, String changeSet,
|
||||
String logicalId) {
|
||||
return client.describeChangeSet(request -> request.stackName(stack).changeSetName(changeSet)).changes()
|
||||
.stream().filter(change -> logicalId.equals(change.resourceChange().logicalResourceId()))
|
||||
.map(change -> change.resourceChange().replacementAsString()).toList();
|
||||
}
|
||||
|
||||
/** Creates an UPDATE change set named {@code changeSet} for {@code template}. */
|
||||
static void createUpdateChangeSet(CloudFormationClient client, String stack, String changeSet,
|
||||
String template, Parameter... parameters) {
|
||||
client.createChangeSet(request -> request.stackName(stack).changeSetName(changeSet)
|
||||
.changeSetType(ChangeSetType.UPDATE).templateBody(template).parameters(parameters));
|
||||
}
|
||||
|
||||
/** Executes {@code changeSet} and waits for the stack to finish updating. */
|
||||
static void executeAndAwaitUpdate(CloudFormationClient client, String stack, String changeSet) {
|
||||
client.executeChangeSet(request -> request.stackName(stack).changeSetName(changeSet));
|
||||
CfnStackWaits.awaitStatus(client, stack, "UPDATE_COMPLETE");
|
||||
}
|
||||
|
||||
/** Turns a template written with single quotes into JSON. */
|
||||
static String json(String template) {
|
||||
return template.replace('\'', '"');
|
||||
}
|
||||
|
||||
/** The resource {@code App}: an AppConfig application named {@code name}. */
|
||||
static String appConfigApplication(String name) {
|
||||
return "\"App\": {\"Type\": \"AWS::AppConfig::Application\", \"Properties\": {\"Name\": \"" + name + "\"}}";
|
||||
}
|
||||
|
||||
/**
|
||||
* The properties of an AppConfig profile in {@code applicationId} (a JSON value) named settings,
|
||||
* followed by {@code rest}.
|
||||
*/
|
||||
static String profileProperties(String applicationId, String rest) {
|
||||
return "\"ApplicationId\": " + applicationId + ", \"Name\": \"settings\", " + rest;
|
||||
}
|
||||
|
||||
/** A template whose resource {@code Subject} is the one under test, after {@code extraResources}. */
|
||||
static String subjectStack(String extraResources, String parameters, String type, String properties) {
|
||||
String extra = extraResources.isEmpty() ? "" : extraResources + ",";
|
||||
String params = parameters.isEmpty() ? "" : "\"Parameters\": {" + parameters + "}, ";
|
||||
return "{" + params + "\"Resources\": {" + extra + "\"Subject\": {\"Type\": \"" + type
|
||||
+ "\", \"Properties\": {" + properties + "}}}}";
|
||||
}
|
||||
|
||||
/** An AppConfig profile {@code Subject} of the application {@code appName}; {@code rest} follows the profile's name. */
|
||||
static String profileStack(String appName, String applicationId, String rest) {
|
||||
return subjectStack(appConfigApplication(appName), "", PROFILE_TYPE, profileProperties(applicationId, rest));
|
||||
}
|
||||
|
||||
/** A VPC and one subnet in {@code cidrPrefix}.0.0/16, as resources followed by a comma. */
|
||||
static String vpcAndSubnet(String cidrPrefix) {
|
||||
return "'Vpc': {'Type': 'AWS::EC2::VPC', 'Properties': {'CidrBlock': '" + cidrPrefix + ".0.0/16'}},"
|
||||
+ "'Subnet': {'Type': 'AWS::EC2::Subnet', 'Properties': {'VpcId': {'Ref': 'Vpc'},"
|
||||
+ " 'CidrBlock': '" + cidrPrefix + ".0.0/24'}},";
|
||||
}
|
||||
|
||||
/** An ElastiCache subnet group in {@code Subnet}, as a resource followed by a comma. */
|
||||
static String subnetGroup(String logicalId, String name) {
|
||||
return "'" + logicalId + "': {'Type': 'AWS::ElastiCache::SubnetGroup', 'Properties': {"
|
||||
+ "'CacheSubnetGroupName': '" + name + "', 'Description': 'example',"
|
||||
+ " 'SubnetIds': [{'Ref': 'Subnet'}]}},";
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -69,8 +69,7 @@ class CloudFormationAppConfigIntegrationTest {
|
||||
"Properties":{"Name":"stack-original-application"}}}}
|
||||
"""));
|
||||
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status());
|
||||
String original = client.describeStackResource(request -> request.stackName(stack)
|
||||
.logicalResourceId("Application")).stackResourceDetail().physicalResourceId();
|
||||
String original = CfnStackTestSupport.physicalId(client, stack, "Application");
|
||||
String other = appconfig().body(Map.of("Name", original)).post("/applications")
|
||||
.then().statusCode(201).extract().path("Id");
|
||||
try (AutoCloseable applicationCleanup = () -> appconfig().delete("/applications/" + other)
|
||||
|
||||
+21
-8
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
@@ -18,6 +19,7 @@ import io.floci.aws.testing.InMemoryStorageFactory;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -61,6 +63,8 @@ class AppConfigCfnProvisionerTest {
|
||||
private AppConfigService service;
|
||||
private AppConfigCfnProvisioner provisioner;
|
||||
private CloudFormationTemplateEngine engine;
|
||||
/** The properties each resource was last provisioned with, which the next update hands over as the previous ones. */
|
||||
private final Map<StackResource, JsonNode> applied = new IdentityHashMap<>();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -267,7 +271,7 @@ class AppConfigCfnProvisionerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aProfileWithoutTypeDefaultsToFreeformAndChangingItReplacesIt() {
|
||||
void aProfileWithoutTypeDefaultsToFreeformAndChangingItKeepsTheProfileAndItsStoredType() {
|
||||
String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId();
|
||||
StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings",
|
||||
"LocationUri", "hosted"));
|
||||
@@ -278,10 +282,12 @@ class AppConfigCfnProvisionerTest {
|
||||
update(profile, props("ApplicationId", appId, "Name", "flags", "LocationUri", "hosted",
|
||||
"Type", "AWS.AppConfig.FeatureFlags"));
|
||||
|
||||
assertNotEquals(oldId, profile.getPhysicalId());
|
||||
ConfigurationProfile replacement = service.getConfigurationProfile(appId, profile.getPhysicalId());
|
||||
assertEquals("AWS.AppConfig.FeatureFlags", replacement.getType());
|
||||
assertEquals("flags", replacement.getName());
|
||||
assertEquals(oldId, profile.getPhysicalId(), "Type is not create-only in AWS, so the profile keeps its id");
|
||||
assertFalse(provisioner.hasReplacementUpdate(profile));
|
||||
ConfigurationProfile updated = service.getConfigurationProfile(appId, oldId);
|
||||
assertEquals("AWS.Freeform", updated.getType(),
|
||||
"UpdateConfigurationProfile has no Type member, so an update cannot change the stored type");
|
||||
assertEquals("flags", updated.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -633,13 +639,16 @@ class AppConfigCfnProvisionerTest {
|
||||
|
||||
private StackResource create(String type, Map<String, Object> properties) {
|
||||
StackResource resource = resource(type);
|
||||
provisioner.provision(resource, MAPPER.valueToTree(properties), context(null));
|
||||
provisioner.provision(resource, MAPPER.valueToTree(properties), context(null, null));
|
||||
applied.put(resource, MAPPER.valueToTree(properties));
|
||||
return resource;
|
||||
}
|
||||
|
||||
/** Provisions {@code resource} again with {@code properties}, as an UpdateStack does. */
|
||||
private void update(StackResource resource, Map<String, Object> properties) {
|
||||
provisioner.provision(resource, MAPPER.valueToTree(properties), context(resource.getPhysicalId()));
|
||||
provisioner.provision(resource, MAPPER.valueToTree(properties),
|
||||
context(resource.getPhysicalId(), applied.get(resource)));
|
||||
applied.put(resource, MAPPER.valueToTree(properties));
|
||||
}
|
||||
|
||||
/** The resource as the stack stores it, so a provision of the copy leaves the original alone. */
|
||||
@@ -658,7 +667,11 @@ class AppConfigCfnProvisionerTest {
|
||||
}
|
||||
|
||||
private ProvisionContext context(String priorPhysicalId) {
|
||||
return new ProvisionContext(engine, REGION, ACCOUNT, STACK, priorPhysicalId);
|
||||
return context(priorPhysicalId, null);
|
||||
}
|
||||
|
||||
private ProvisionContext context(String priorPhysicalId, JsonNode priorProperties) {
|
||||
return new ProvisionContext(engine, REGION, ACCOUNT, STACK, priorPhysicalId, event -> {}, priorProperties);
|
||||
}
|
||||
|
||||
/** Alternating property names and values, in order. */
|
||||
|
||||
+76
-4
@@ -64,6 +64,13 @@ class ElastiCacheCfnProvisionerTest {
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
/** An update context that carries the previous template's properties, as the stack engine's does. */
|
||||
private ProvisionContext ctx(String priorPhysicalId, String priorProperties) throws Exception {
|
||||
ProvisionContext base = ctx(priorPhysicalId);
|
||||
return new ProvisionContext(base.engine(), "us-east-1", "000000000000", "my-stack", priorPhysicalId,
|
||||
event -> { }, mapper.readTree(priorProperties));
|
||||
}
|
||||
|
||||
private StackResource resource(String type, String logicalId) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId(logicalId);
|
||||
@@ -196,7 +203,8 @@ class ElastiCacheCfnProvisionerTest {
|
||||
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r,
|
||||
props("{\"ClusterName\":\"app-cache\",\"Engine\":\"valkey\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx("app-cache")));
|
||||
props("{\"ClusterName\":\"app-cache\",\"Engine\":\"valkey\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"),
|
||||
ctx("app-cache", "{\"ClusterName\":\"app-cache\",\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -211,12 +219,74 @@ class ElastiCacheCfnProvisionerTest {
|
||||
});
|
||||
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, props("{\"Engine\":\"valkey\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx("old-id"));
|
||||
provisioner.provision(r, props("{\"Engine\":\"valkey\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"),
|
||||
ctx("old-id", "{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"));
|
||||
|
||||
assertNotEquals("old-id", r.getPhysicalId());
|
||||
assertEquals("6401", r.getAttributes().get("RedisEndpoint.Port"));
|
||||
}
|
||||
|
||||
private static final String REDIS_CLUSTER = "{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\","
|
||||
+ "\"NumCacheNodes\":1%s}";
|
||||
|
||||
private void existingRedisCluster(String id) {
|
||||
CacheCluster existing = new CacheCluster(id, CacheClusterStatus.AVAILABLE, "redis", "7.1",
|
||||
new Endpoint("localhost", 6400), Instant.now());
|
||||
when(cache.findCacheClusters(id)).thenReturn(List.of(existing));
|
||||
when(cache.createCacheCluster(any())).thenAnswer(inv -> {
|
||||
ElastiCacheService.CreateCacheClusterRequest req = inv.getArgument(0);
|
||||
return new CacheCluster(req.cacheClusterId(), CacheClusterStatus.AVAILABLE, "redis", "7.1",
|
||||
new Endpoint("localhost", 6401), Instant.now());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void unnamedClusterWithChangedPortIsReplacedAndTheOldOneDeletedWhenTheUpdateCompletes() throws Exception {
|
||||
existingRedisCluster("old-id");
|
||||
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, props(REDIS_CLUSTER.formatted(",\"Port\":6380")),
|
||||
ctx("old-id", REDIS_CLUSTER.formatted(",\"Port\":6379")));
|
||||
|
||||
assertNotEquals("old-id", r.getPhysicalId());
|
||||
verify(cache).createCacheCluster(any());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
assertEquals("old-id", provisioner.updateCleanupPhysicalId(r));
|
||||
verify(cache, never()).deleteCacheCluster("old-id");
|
||||
provisioner.completeUpdate(r);
|
||||
verify(cache).deleteCacheCluster("old-id");
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterWithChangedSnapshotNameIsReplaced() throws Exception {
|
||||
existingRedisCluster("old-id");
|
||||
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, props(REDIS_CLUSTER.formatted(",\"SnapshotName\":\"snap-2\"")),
|
||||
ctx("old-id", REDIS_CLUSTER.formatted(",\"SnapshotName\":\"snap-1\"")));
|
||||
|
||||
assertNotEquals("old-id", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
|
||||
StackResource arns = resource("AWS::ElastiCache::CacheCluster", "Cluster");
|
||||
provisioner.provision(arns, props(REDIS_CLUSTER.formatted(",\"SnapshotArns\":[\"arn:aws:s3:::b/2.rdb\"]")),
|
||||
ctx("old-id", REDIS_CLUSTER.formatted(",\"SnapshotArns\":[\"arn:aws:s3:::b/1.rdb\"]")));
|
||||
|
||||
assertNotEquals("old-id", arns.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(arns));
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitClusterNameWithChangedPortIsRejectedOnUpdate() throws Exception {
|
||||
existingRedisCluster("app-cache");
|
||||
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.provision(r,
|
||||
props(REDIS_CLUSTER.formatted(",\"ClusterName\":\"app-cache\",\"Port\":6380")),
|
||||
ctx("app-cache", REDIS_CLUSTER.formatted(",\"ClusterName\":\"app-cache\",\"Port\":6379"))));
|
||||
verify(cache, never()).createCacheCluster(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void engineSwitchCleansUpDisplacedEndpointAttributes() throws Exception {
|
||||
CacheCluster existingRedis = new CacheCluster("cluster-1", CacheClusterStatus.AVAILABLE, "redis", "7.1",
|
||||
@@ -233,7 +303,7 @@ class ElastiCacheCfnProvisionerTest {
|
||||
|
||||
provisioner.provision(r, props("""
|
||||
{"Engine":"memcached","CacheNodeType":"cache.t3.micro","NumCacheNodes":1}
|
||||
"""), ctx("cluster-1"));
|
||||
"""), ctx("cluster-1", "{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"));
|
||||
|
||||
assertEquals("6410", r.getAttributes().get("ConfigurationEndpoint.Port"));
|
||||
assertEquals("localhost", r.getAttributes().get("ConfigurationEndpoint.Address"));
|
||||
@@ -513,7 +583,9 @@ class ElastiCacheCfnProvisionerTest {
|
||||
});
|
||||
StackResource r = resource("AWS::ElastiCache::CacheCluster", "Cluster");
|
||||
|
||||
provisioner.provision(r, props("{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"), ctx("old-id"));
|
||||
provisioner.provision(r, props("{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1}"),
|
||||
ctx("old-id", "{\"Engine\":\"redis\",\"CacheNodeType\":\"cache.t3.micro\",\"NumCacheNodes\":1,"
|
||||
+ "\"NetworkType\":\"dual_stack\"}"));
|
||||
|
||||
assertNotEquals("old-id", r.getPhysicalId());
|
||||
verify(cache).createCacheCluster(any());
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package io.floci.aws.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PropertyChangesReplacementTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String TYPE = "AWS::Route53::HostedZone";
|
||||
|
||||
private static PropertyChanges between(String prior, String current) throws Exception {
|
||||
return PropertyChanges.between(TYPE, true, MAPPER.readTree(prior), MAPPER.readTree(current));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangedOrDroppedCreateOnlyPropertyReplaces() throws Exception {
|
||||
assertTrue(between("{\"Name\":\"a.example.\"}", "{\"Name\":\"b.example.\"}").requiresReplacement());
|
||||
assertTrue(between("{\"Name\":\"a.example.\",\"DelegationSetId\":\"N1\"}",
|
||||
"{\"Name\":\"a.example.\"}").requiresReplacement());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAddedOrNonCreateOnlyChangeDoesNotReplace() throws Exception {
|
||||
assertFalse(between("{\"Name\":\"a.example.\"}",
|
||||
"{\"Name\":\"a.example.\",\"DelegationSetId\":\"N1\"}").requiresReplacement());
|
||||
assertFalse(between("{\"Name\":\"a.example.\",\"HostedZoneConfig\":{\"Comment\":\"x\"}}",
|
||||
"{\"Name\":\"a.example.\",\"HostedZoneConfig\":{\"Comment\":\"y\"}}").requiresReplacement());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user