mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): fill change set details for resources that read a replaced or changed resource (#9555)
This commit is contained in:
1 parent
34153a29f0
commit
52fb3589fc
4 files changed
+276
-133
No files matched your search
@@ -119,13 +119,25 @@ public final class CfnCreateOnlyProperties {
|
||||
|
||||
/** 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) {
|
||||
return createOnlySubtrees(resourceType, props, null);
|
||||
}
|
||||
|
||||
/** As above, only the pointers at and under {@code property}; null means every property. */
|
||||
public static List<JsonNode> createOnlySubtrees(String resourceType, JsonNode props, String property) {
|
||||
List<JsonNode> out = new ArrayList<>();
|
||||
for (String pointer : replacementPointers(resourceType)) {
|
||||
collect(props, pointer.split("/"), 0, out);
|
||||
if (isUnder(pointer, property)) {
|
||||
collect(props, pointer.split("/"), 0, out);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Whether the pointer is at or under the top-level property; a null property matches every pointer. */
|
||||
static boolean isUnder(String pointer, String property) {
|
||||
return property == null || pointer.equals(property) || pointer.startsWith(property + "/");
|
||||
}
|
||||
|
||||
private static boolean pointerChanged(JsonNode oldNode, JsonNode newNode, String[] segments, int index) {
|
||||
if (index == segments.length) {
|
||||
return oldNode == null ? newNode != null : !oldNode.equals(newNode);
|
||||
|
||||
@@ -54,6 +54,7 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -1276,7 +1277,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
changes.add(new ResourceChange("Modify", logicalId,
|
||||
resourcePhysicalId(stack, logicalId), resourceType,
|
||||
replacement ? REPLACEMENT_TRUE : REPLACEMENT_FALSE,
|
||||
details.stream().map(ChangeDetail::attribute).distinct().toList(), details));
|
||||
changeScope(details), details));
|
||||
}
|
||||
});
|
||||
oldResources.fields().forEachRemaining(e -> {
|
||||
@@ -1318,6 +1319,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
newResolvedParams, physicalIds, Map.of(), newConditions, Map.of(), objectMapper, null);
|
||||
|
||||
List<String> sortedLogicalIds = topologicalSort(newResources, newConditions);
|
||||
Set<String> dependencyDetailIds = new HashSet<>();
|
||||
boolean anyNewChange = true;
|
||||
while (anyNewChange) {
|
||||
anyNewChange = false;
|
||||
@@ -1367,6 +1369,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
newConditions, dependencyEngine)));
|
||||
String replacementState = replacement ? REPLACEMENT_TRUE
|
||||
: conditional ? REPLACEMENT_CONDITIONAL : REPLACEMENT_FALSE;
|
||||
if (comparedProperties == null && oldDef != null && !typeChanged) {
|
||||
dependencyDetailIds.add(logicalId);
|
||||
}
|
||||
if (replacement && replacedResourceIds.add(logicalId)) {
|
||||
anyNewChange = true;
|
||||
}
|
||||
@@ -1385,6 +1390,24 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!dependencyDetailIds.isEmpty()) {
|
||||
Map<String, String> replacementStates = new HashMap<>();
|
||||
for (ResourceChange change : changes) {
|
||||
if (replacementRank(change.replacement()) > 0) {
|
||||
replacementStates.put(change.logicalResourceId(), change.replacement());
|
||||
}
|
||||
}
|
||||
changes.replaceAll(change -> {
|
||||
String logicalId = change.logicalResourceId();
|
||||
if (!dependencyDetailIds.contains(logicalId)) {
|
||||
return change;
|
||||
}
|
||||
return change.withDependencyDetails(replacementDecider.dependencyDetails(
|
||||
change.resourceType(), logicalId, oldResources.get(logicalId), newResources.get(logicalId),
|
||||
subtree -> changedResourceReads(subtree, replacementStates, inPlaceChangedAttributes,
|
||||
newConditions, dependencyEngine)));
|
||||
});
|
||||
}
|
||||
}
|
||||
return changes;
|
||||
} catch (AwsException e) {
|
||||
@@ -1423,15 +1446,22 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
/** 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) {
|
||||
return anyCreateOnlyValue(resourceType, props, null, test);
|
||||
}
|
||||
|
||||
private static boolean anyCreateOnlyValue(String resourceType, JsonNode props, String property,
|
||||
Predicate<JsonNode> test) {
|
||||
if (props == null || !props.isObject()) {
|
||||
return false;
|
||||
}
|
||||
if (CfnCreateOnlyProperties.hasSchema(resourceType)) {
|
||||
return CfnCreateOnlyProperties.createOnlySubtrees(resourceType, props).stream().anyMatch(test);
|
||||
return CfnCreateOnlyProperties.createOnlySubtrees(resourceType, props, property).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))) {
|
||||
if ((property == null || property.equals(field))
|
||||
&& CfnCreateOnlyProperties.isCreateOnly(resourceType, field) && test.test(props.get(field))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1575,12 +1605,30 @@ public class CloudFormationService implements ResourceProvider {
|
||||
return comparedChanged(resourceType, logicalId, props[0], props[1], property);
|
||||
}
|
||||
return CfnCreateOnlyProperties.replacementPointers(resourceType).stream()
|
||||
.filter(pointer -> under(pointer, property))
|
||||
.filter(pointer -> CfnCreateOnlyProperties.isUnder(pointer, property))
|
||||
.anyMatch(pointer -> writtenPointerChanged(pointer, props[0], props[1]));
|
||||
}
|
||||
|
||||
private static boolean under(String pointer, String property) {
|
||||
return property == null || pointer.equals(property) || pointer.startsWith(property + "/");
|
||||
private Set<ChangeDetail> dependencyDetails(String resourceType, String logicalId, JsonNode oldDef,
|
||||
JsonNode newDef, Function<JsonNode, Set<ResourceRead>> reads) {
|
||||
Set<ChangeDetail> details = new LinkedHashSet<>();
|
||||
JsonNode props = newDef.path("Properties");
|
||||
props.fields().forEachRemaining(field -> {
|
||||
String property = field.getKey();
|
||||
Set<ResourceRead> causes = reads.apply(field.getValue());
|
||||
if (causes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
boolean recreates = recreates(resourceType, logicalId, property, oldDef, newDef)
|
||||
|| anyCreateOnlyValue(resourceType, props, property,
|
||||
subtree -> !reads.apply(subtree).isEmpty());
|
||||
boolean tags = "Tags".equals(property);
|
||||
for (ResourceRead cause : causes) {
|
||||
details.add(new ChangeDetail(tags ? "Tags" : "Properties", tags ? null : property,
|
||||
recreates ? "Always" : "Never", cause.evaluation(), cause.source(), cause.entity()));
|
||||
}
|
||||
});
|
||||
return details;
|
||||
}
|
||||
|
||||
/** The block as written with every AWS::NoValue member left out, by the side's own conditions. */
|
||||
@@ -1639,7 +1687,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
JsonNode digestedBefore = digested(before);
|
||||
JsonNode digestedAfter = digested(after);
|
||||
for (String pointer : CfnCreateOnlyProperties.replacementPointers(resourceType)) {
|
||||
if (!under(pointer, property)) {
|
||||
if (!CfnCreateOnlyProperties.isUnder(pointer, property)) {
|
||||
continue;
|
||||
}
|
||||
boolean changed = noEvidence(pointer, before)
|
||||
@@ -1812,8 +1860,9 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
/**
|
||||
* One change of a resource. {@code scope} and {@code details} are those of {@code
|
||||
* DescribeChangeSet}: filled for a Modify that the template diff found, empty for an Add, a Remove, a nested
|
||||
* stack and a resource that changes only because it reads a replaced resource or a changed attribute.
|
||||
* DescribeChangeSet}, built on the describe path only: for a Modify, one detail per property or attribute
|
||||
* the template diff found and, from the dependency pass, one per property that reads a replaced resource or an
|
||||
* attribute changed in place; empty for an Add and a Remove, and for a nested stack nothing of which differs.
|
||||
*/
|
||||
public record ResourceChange(String action, String logicalResourceId, String physicalResourceId,
|
||||
String resourceType, String replacement,
|
||||
@@ -1822,23 +1871,38 @@ public class CloudFormationService implements ResourceProvider {
|
||||
String resourceType, String replacement) {
|
||||
this(action, logicalResourceId, physicalResourceId, resourceType, replacement, List.of(), List.of());
|
||||
}
|
||||
|
||||
private ResourceChange withDependencyDetails(Set<ChangeDetail> dependencies) {
|
||||
if (dependencies == null || dependencies.isEmpty() || !"Modify".equals(action)) {
|
||||
return this;
|
||||
}
|
||||
Set<ChangeDetail> merged = new LinkedHashSet<>(details);
|
||||
merged.addAll(dependencies);
|
||||
return new ResourceChange(action, logicalResourceId, physicalResourceId, resourceType, replacement,
|
||||
changeScope(merged), List.copyOf(merged));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An AWS {@code ResourceChangeDetail}: {@code attribute} and {@code name} are its Target (no name
|
||||
* unless the attribute is Properties), {@code requiresRecreation} is set for Properties and Tags
|
||||
* only, {@code causingEntity} is the parameter of a ParameterReference.
|
||||
* only. A reference names its parameter, resource or resource attribute in {@code causingEntity}.
|
||||
*/
|
||||
public record ChangeDetail(String attribute, String name, String requiresRecreation, String evaluation,
|
||||
String changeSource, String causingEntity) {}
|
||||
|
||||
private static List<String> changeScope(Collection<ChangeDetail> details) {
|
||||
return details.stream().map(ChangeDetail::attribute).distinct().toList();
|
||||
}
|
||||
|
||||
private static final List<String> RESOURCE_ATTRIBUTES = List.of(
|
||||
"Metadata", "DeletionPolicy", "UpdateReplacePolicy", "UpdatePolicy");
|
||||
|
||||
/**
|
||||
* The details of a modified resource: one entry per property and per resource-level attribute that
|
||||
* differs, in the forms the diff compared ({@code comparedOld} and {@code comparedNew}, null when the
|
||||
* template did not resolve and the definitions as written were diffed). See {@link #addDetails}.
|
||||
* The details of a resource the template diff found modified: one entry per property and per
|
||||
* resource-level attribute that differs, in the forms the diff compared ({@code comparedOld} and
|
||||
* {@code comparedNew}, null when the template did not resolve and the definitions as written were diffed).
|
||||
* See {@link #addDetails}.
|
||||
* {@code RequiresRecreation} is {@code Always} when the replacement decision's rule for the create-only
|
||||
* pointers at and under the property says the update recreates, and {@code Never} otherwise.
|
||||
* {@code Conditionally} is not produced: floci's create-only table records no conditional replacement,
|
||||
@@ -6219,52 +6283,64 @@ public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
private void collectDependencies(JsonNode node, Set<String> allIds, Set<String> deps,
|
||||
Map<String, Boolean> conditions) {
|
||||
visitResourceReads(node, conditions, false, (id, getAtt, subAttribute) -> {
|
||||
if (allIds.contains(id)) {
|
||||
deps.add(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Receives one read of a resource: the raw {@code Fn::GetAtt} node when the template reads an attribute that
|
||||
* way, so the engine's one attribute rule and its validation apply; the attribute text of a {@code Fn::Sub}
|
||||
* variable {@code Id.Attribute}; neither for a Ref and for a Sub variable without an attribute.
|
||||
*/
|
||||
private interface ResourceReadVisitor {
|
||||
void read(String logicalId, JsonNode getAtt, String subAttribute);
|
||||
}
|
||||
|
||||
/** Attribute matching also checks both branches of a condition that is not known. */
|
||||
private void visitResourceReads(JsonNode node, Map<String, Boolean> conditions, boolean bothIfUnknown,
|
||||
ResourceReadVisitor read) {
|
||||
if (node == null || node.isNull() || node.isMissingNode()) {
|
||||
return;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if (node.has("Ref")) {
|
||||
String ref = node.get("Ref").asText();
|
||||
if (allIds.contains(ref)) {
|
||||
deps.add(ref);
|
||||
}
|
||||
read.read(node.get("Ref").asText(), null, null);
|
||||
return;
|
||||
}
|
||||
if (node.has("Fn::GetAtt")) {
|
||||
JsonNode getAtt = node.get("Fn::GetAtt");
|
||||
String logicalId;
|
||||
if (getAtt.isArray() && getAtt.size() >= 1) {
|
||||
logicalId = getAtt.get(0).asText();
|
||||
if (getAtt.isArray() && !getAtt.isEmpty()) {
|
||||
read.read(getAtt.get(0).asText(), getAtt, null);
|
||||
} else {
|
||||
logicalId = getAtt.asText().split("\\.", 2)[0];
|
||||
}
|
||||
if (allIds.contains(logicalId)) {
|
||||
deps.add(logicalId);
|
||||
read.read(getAtt.asText().split("\\.", 2)[0], getAtt, null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (node.has("Fn::If")) {
|
||||
JsonNode fnIf = node.get("Fn::If");
|
||||
if (fnIf.isArray() && fnIf.size() == 3) {
|
||||
boolean condition = conditions.getOrDefault(fnIf.get(0).asText(), false);
|
||||
collectDependencies(fnIf.get(condition ? 1 : 2), allIds, deps, conditions);
|
||||
String name = fnIf.get(0).asText();
|
||||
if (bothIfUnknown && (conditions == null || !conditions.containsKey(name))) {
|
||||
visitResourceReads(fnIf.get(1), conditions, true, read);
|
||||
}
|
||||
boolean condition = conditions != null && conditions.getOrDefault(name, false);
|
||||
visitResourceReads(fnIf.get(condition ? 1 : 2), conditions, bothIfUnknown, read);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (node.has("Fn::Sub")) {
|
||||
collectSubDependencies(node.get("Fn::Sub"), allIds, deps, conditions);
|
||||
visitSubReads(node.get("Fn::Sub"), conditions, bothIfUnknown, read);
|
||||
return;
|
||||
}
|
||||
node.fields().forEachRemaining(e -> collectDependencies(e.getValue(), allIds, deps, conditions));
|
||||
} else if (node.isArray()) {
|
||||
for (JsonNode item : node) {
|
||||
collectDependencies(item, allIds, deps, conditions);
|
||||
}
|
||||
}
|
||||
node.forEach(child -> visitResourceReads(child, conditions, bothIfUnknown, read));
|
||||
}
|
||||
|
||||
private void collectSubDependencies(JsonNode sub, Set<String> allIds, Set<String> deps,
|
||||
Map<String, Boolean> conditions) {
|
||||
private void visitSubReads(JsonNode sub, Map<String, Boolean> conditions, boolean bothIfUnknown,
|
||||
ResourceReadVisitor read) {
|
||||
String template;
|
||||
Set<String> explicitVars = new HashSet<>();
|
||||
|
||||
@@ -6273,8 +6349,10 @@ public class CloudFormationService implements ResourceProvider {
|
||||
} else if (sub.isArray() && sub.size() >= 1) {
|
||||
template = sub.get(0).asText();
|
||||
if (sub.size() >= 2 && sub.get(1).isObject()) {
|
||||
sub.get(1).fieldNames().forEachRemaining(explicitVars::add);
|
||||
collectDependencies(sub.get(1), allIds, deps, conditions);
|
||||
sub.get(1).fields().forEachRemaining(entry -> {
|
||||
explicitVars.add(entry.getKey());
|
||||
visitResourceReads(entry.getValue(), conditions, bothIfUnknown, read);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
@@ -6288,12 +6366,54 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
int dot = varName.indexOf('.');
|
||||
String resourcePart = dot > 0 ? varName.substring(0, dot) : varName;
|
||||
if (allIds.contains(resourcePart)) {
|
||||
deps.add(resourcePart);
|
||||
}
|
||||
read.read(resourcePart, null, dot > 0 ? varName.substring(dot + 1) : null);
|
||||
}
|
||||
}
|
||||
|
||||
private record ResourceRead(String logicalId, String attribute, String evaluation) {
|
||||
String source() {
|
||||
return attribute == null ? "ResourceReference" : "ResourceAttribute";
|
||||
}
|
||||
|
||||
String entity() {
|
||||
return attribute == null ? logicalId : logicalId + "." + attribute;
|
||||
}
|
||||
}
|
||||
|
||||
private Set<ResourceRead> changedResourceReads(JsonNode node, Map<String, String> replacementStates,
|
||||
Map<String, Set<String>> changedAttributes,
|
||||
Map<String, Boolean> conditions,
|
||||
CloudFormationTemplateEngine engine) {
|
||||
Set<ResourceRead> reads = new LinkedHashSet<>();
|
||||
if (!replacementStates.isEmpty()) {
|
||||
visitResourceReads(node, conditions, false, (id, getAtt, subAttribute) -> {
|
||||
String replacement = replacementStates.get(id);
|
||||
if (replacement != null) {
|
||||
String name = readAttribute(getAtt, subAttribute, engine);
|
||||
if (name == null || !name.isEmpty()) {
|
||||
String evaluation = REPLACEMENT_TRUE.equals(replacement) ? "Static" : "Dynamic";
|
||||
reads.add(new ResourceRead(id, name, evaluation));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!changedAttributes.isEmpty()) {
|
||||
visitResourceReads(node, conditions, true, (id, getAtt, subAttribute) -> {
|
||||
String name = readAttribute(getAtt, subAttribute, engine);
|
||||
if (name != null && changedAttributes.getOrDefault(id, Set.of()).contains(name)) {
|
||||
String evaluation = REPLACEMENT_TRUE.equals(replacementStates.get(id)) ? "Static" : "Dynamic";
|
||||
reads.add(new ResourceRead(id, name, evaluation));
|
||||
}
|
||||
});
|
||||
}
|
||||
return reads;
|
||||
}
|
||||
|
||||
/** The attribute of a read by the engine's rule: null for a Ref, empty when a GetAtt names none. */
|
||||
private static String readAttribute(JsonNode getAtt, String subAttribute, CloudFormationTemplateEngine engine) {
|
||||
return getAtt != null ? engine.getAttAttributeName(getAtt) : subAttribute;
|
||||
}
|
||||
|
||||
private Set<String> expectedChangedAttributes(String resourceType, JsonNode oldDef, JsonNode newDef) {
|
||||
Set<String> changedAttrs = new HashSet<>();
|
||||
if ("AWS::EC2::LaunchTemplate".equals(resourceType)) {
|
||||
@@ -6318,82 +6438,19 @@ public class CloudFormationService implements ResourceProvider {
|
||||
*/
|
||||
private boolean referencesAnyAttribute(JsonNode node, String targetLogicalId, Set<String> targetAttrNames,
|
||||
Map<String, Boolean> conditions, CloudFormationTemplateEngine engine) {
|
||||
if (node == null || node.isNull() || node.isMissingNode()) {
|
||||
return false;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if (node.has("Fn::GetAtt")
|
||||
&& engine.referencesGetAttAttribute(node.get("Fn::GetAtt"), targetLogicalId, targetAttrNames)) {
|
||||
return true;
|
||||
boolean[] found = {false};
|
||||
visitResourceReads(node, conditions, true, (id, getAtt, subAttribute) -> {
|
||||
// The first match ends the check, as before: a GetAtt after it is not validated.
|
||||
if (found[0]) {
|
||||
return;
|
||||
}
|
||||
if (node.has("Fn::If")) {
|
||||
JsonNode fnIf = node.get("Fn::If");
|
||||
if (fnIf.isArray() && fnIf.size() == 3) {
|
||||
if (conditions != null && conditions.containsKey(fnIf.get(0).asText())) {
|
||||
boolean condition = conditions.get(fnIf.get(0).asText());
|
||||
return referencesAnyAttribute(fnIf.get(condition ? 1 : 2), targetLogicalId, targetAttrNames,
|
||||
conditions, engine);
|
||||
}
|
||||
return referencesAnyAttribute(fnIf.get(1), targetLogicalId, targetAttrNames, conditions, engine)
|
||||
|| referencesAnyAttribute(fnIf.get(2), targetLogicalId, targetAttrNames, conditions, engine);
|
||||
}
|
||||
if (getAtt != null) {
|
||||
found[0] = engine.referencesGetAttAttribute(getAtt, targetLogicalId, targetAttrNames);
|
||||
} else if (subAttribute != null) {
|
||||
found[0] = targetLogicalId.equals(id) && targetAttrNames.contains(subAttribute);
|
||||
}
|
||||
if (node.has("Fn::Sub")) {
|
||||
if (subReferencesAttribute(node.get("Fn::Sub"), targetLogicalId, targetAttrNames, conditions, engine)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
for (Iterator<JsonNode> it = node.elements(); it.hasNext(); ) {
|
||||
if (referencesAnyAttribute(it.next(), targetLogicalId, targetAttrNames, conditions, engine)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
} else if (node.isArray()) {
|
||||
for (JsonNode item : node) {
|
||||
if (referencesAnyAttribute(item, targetLogicalId, targetAttrNames, conditions, engine)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean subReferencesAttribute(JsonNode sub, String targetLogicalId, Set<String> targetAttrNames,
|
||||
Map<String, Boolean> conditions, CloudFormationTemplateEngine engine) {
|
||||
String template;
|
||||
Set<String> explicitVars = new HashSet<>();
|
||||
|
||||
if (sub.isTextual()) {
|
||||
template = sub.textValue();
|
||||
} else if (sub.isArray() && sub.size() >= 1) {
|
||||
template = sub.get(0).asText();
|
||||
if (sub.size() >= 2 && sub.get(1).isObject()) {
|
||||
sub.get(1).fieldNames().forEachRemaining(explicitVars::add);
|
||||
if (referencesAnyAttribute(sub.get(1), targetLogicalId, targetAttrNames, conditions, engine)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
Matcher matcher = SUB_VAR_PATTERN.matcher(template);
|
||||
while (matcher.find()) {
|
||||
String varName = matcher.group(1);
|
||||
if (varName.startsWith("AWS::") || explicitVars.contains(varName)) {
|
||||
continue;
|
||||
}
|
||||
int dot = varName.indexOf('.');
|
||||
if (dot > 0) {
|
||||
String resourcePart = varName.substring(0, dot);
|
||||
String attrPart = varName.substring(dot + 1);
|
||||
if (targetLogicalId.equals(resourcePart) && targetAttrNames.contains(attrPart)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return found[0];
|
||||
}
|
||||
|
||||
private static String stackStorageKey(String stackName, String region) {
|
||||
|
||||
+28
-15
@@ -946,28 +946,41 @@ public class CloudFormationTemplateEngine {
|
||||
}
|
||||
|
||||
private String[] getAttParts(JsonNode getAtt) {
|
||||
String errorMessage = "Template error: every Fn::GetAtt object requires two non-empty parameters, "
|
||||
+ "the resource name and the resource attribute";
|
||||
String[] parts;
|
||||
String[] parts = getAttOperands(getAtt);
|
||||
if (parts == null) {
|
||||
return null;
|
||||
}
|
||||
if (parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty()) {
|
||||
throw new AwsException("ValidationError", getAtt.isTextual()
|
||||
? "Template error: if specifying one argument to Fn::GetAtt, "
|
||||
+ "that argument must be a non-empty string in format <LogicalId>.<Attribute>"
|
||||
: "Template error: every Fn::GetAtt object requires two non-empty parameters, "
|
||||
+ "the resource name and the resource attribute", 400);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource and the attribute a GetAtt names, as written: a Ref-valued attribute is resolved. Null when
|
||||
* the node is no GetAtt form; an array of the wrong size gives no operands, and a text without a dot gives one.
|
||||
*/
|
||||
private String[] getAttOperands(JsonNode getAtt) {
|
||||
if (getAtt.isArray()) {
|
||||
if (getAtt.size() != 2) {
|
||||
throw new AwsException("ValidationError", errorMessage, 400);
|
||||
return new String[0];
|
||||
}
|
||||
JsonNode attribute = getAtt.get(1);
|
||||
String attributeName = attribute.has("Ref")
|
||||
? resolveRef(attribute.get("Ref").asText()) : attribute.asText();
|
||||
parts = new String[] {getAtt.get(0).asText(), attributeName};
|
||||
} else if (getAtt.isTextual()) {
|
||||
errorMessage = "Template error: if specifying one argument to Fn::GetAtt, "
|
||||
+ "that argument must be a non-empty string in format <LogicalId>.<Attribute>";
|
||||
parts = getAtt.textValue().split("\\.", 2);
|
||||
} else {
|
||||
return null;
|
||||
return new String[] {getAtt.get(0).asText(), attributeName};
|
||||
}
|
||||
if (parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty()) {
|
||||
throw new AwsException("ValidationError", errorMessage, 400);
|
||||
}
|
||||
return parts;
|
||||
return getAtt.isTextual() ? getAtt.textValue().split("\\.", 2) : null;
|
||||
}
|
||||
|
||||
/** The attribute a GetAtt reads by the rule of {@link #getAttParts}, empty when the node names none. */
|
||||
public String getAttAttributeName(JsonNode getAtt) {
|
||||
String[] parts = getAttOperands(getAtt);
|
||||
return parts != null && parts.length == 2 ? parts[1] : "";
|
||||
}
|
||||
|
||||
private Map<String, String> findAttributeSource(String logicalId, String attrName) {
|
||||
|
||||
+65
-4
@@ -1131,7 +1131,13 @@ class CloudFormationChangeSetDiffIntegrationTest {
|
||||
}
|
||||
|
||||
private record DetailsRow(String name, String type, String oldProps, String newProps, String newParam,
|
||||
List<String> scope, List<String> details, String replacement, boolean exact) { }
|
||||
List<String> scope, List<String> details, String replacement, boolean exact,
|
||||
String logicalId, String oldExtra, String newExtra) {
|
||||
private DetailsRow(String name, String type, String oldProps, String newProps, String newParam,
|
||||
List<String> scope, List<String> details, String replacement, boolean exact) {
|
||||
this(name, type, oldProps, newProps, newParam, scope, details, replacement, exact, "R", "", "");
|
||||
}
|
||||
}
|
||||
|
||||
/** Details are "Attribute|Name|RequiresRecreation|ChangeSource|Evaluation|CausingEntity", empty when absent. */
|
||||
private static String template(String type, String props, String... extraResources) {
|
||||
@@ -1178,6 +1184,34 @@ class CloudFormationChangeSetDiffIntegrationTest {
|
||||
void modifiedResource_reportsScopeAndDetails() {
|
||||
String direct = "|DirectModification|Static|";
|
||||
String ifSet = "{\"Fn::If\":[\"C\",5,{\"Ref\":\"AWS::NoValue\"}]}";
|
||||
String queueName = "\"QueueName\":\"cs-det-%s-%s\"";
|
||||
String topic = """
|
||||
,"Reader":{"Type":"AWS::SNS::Topic","Properties":{"DisplayName":%s}}
|
||||
""";
|
||||
String readsRef = topic.formatted("{\"Ref\":\"R\"}");
|
||||
String readsArn = topic.formatted("{\"Fn::GetAtt\":[\"R\",\"Arn\"]}");
|
||||
String role = """
|
||||
,"Role":{"Type":"AWS::IAM::Role","Properties":{"RoleName":"cs-det-role-%s",
|
||||
"AssumeRolePolicyDocument":{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"Service":"batch.amazonaws.com"},"Action":"sts:AssumeRole"}]}}}
|
||||
""";
|
||||
String compute = """
|
||||
"ComputeEnvironmentName":"cs-det-compute","Type":"MANAGED",
|
||||
"ComputeResources":{"Type":"FARGATE","MaxvCpus":4,"Subnets":["subnet-local"],
|
||||
"SecurityGroupIds":["sg-local"],"SpotIamFleetRole":{"Ref":"Role"}}
|
||||
""";
|
||||
String launchTemplate = """
|
||||
,"Lt":{"Type":"AWS::EC2::LaunchTemplate","Properties":{"LaunchTemplateName":"cs-det-lt",
|
||||
"LaunchTemplateData":{"ImageId":"%s","InstanceType":"t3.micro"}}}
|
||||
""";
|
||||
String asg = """
|
||||
"AutoScalingGroupName":"cs-det-asg","MinSize":0,"MaxSize":0,"DesiredCapacity":0,
|
||||
"AvailabilityZones":["us-east-1a"],"LaunchTemplate":{
|
||||
"LaunchTemplateId":{"Ref":"Lt"},"Version":{"Fn::GetAtt":["Lt","LatestVersionNumber"]}}
|
||||
""";
|
||||
String asgSub = asg.replace("{\"Fn::GetAtt\":[\"Lt\",\"LatestVersionNumber\"]}",
|
||||
"{\"Fn::Sub\":[\"${Ref}\",{\"Ref\":{\"Fn::GetAtt\":[\"Lt\",\"LatestVersionNumber\"]}}]}")
|
||||
.replace("cs-det-asg", "cs-det-asg-sub");
|
||||
List<DetailsRow> rows = List.of(
|
||||
new DetailsRow("changed", "AWS::SNS::Topic", "\"DisplayName\":\"a\"", "\"DisplayName\":\"b\"", null,
|
||||
List.of("Properties"), List.of("Properties|DisplayName|Never" + direct), "False", true),
|
||||
@@ -1208,15 +1242,42 @@ class CloudFormationChangeSetDiffIntegrationTest {
|
||||
List.of("Properties"), List.of("Properties|HealthCheckConfig|Always" + direct), "True", true),
|
||||
new DetailsRow("condition", "AWS::SQS::Queue", "\"QueueName\":\"cs-det-cond\",\"DelaySeconds\":" + ifSet,
|
||||
"\"QueueName\":\"cs-det-cond\",\"DelaySeconds\":" + ifSet, "Env=dev", List.of("Properties"),
|
||||
List.of("Properties|DelaySeconds|Never|DirectModification|Dynamic|"), "False", false));
|
||||
List.of("Properties|DelaySeconds|Never|DirectModification|Dynamic|"), "False", false),
|
||||
new DetailsRow("replaced-ref", "AWS::SQS::Queue", queueName.formatted("ref", "a"),
|
||||
queueName.formatted("ref", "b"), null, List.of("Properties"),
|
||||
List.of("Properties|DisplayName|Never|ResourceReference|Static|R"), "False", true,
|
||||
"Reader", readsRef, readsRef),
|
||||
new DetailsRow("replaced-get-att", "AWS::SQS::Queue", queueName.formatted("arn", "a"),
|
||||
queueName.formatted("arn", "b"), null, List.of("Properties"),
|
||||
List.of("Properties|DisplayName|Never|ResourceAttribute|Static|R.Arn"), "False", true,
|
||||
"Reader", readsArn, readsArn),
|
||||
new DetailsRow("create-only-ref", "AWS::Batch::ComputeEnvironment", compute, compute, null,
|
||||
List.of("Properties"), List.of("Properties|ComputeResources|Always|ResourceReference|Static|Role"),
|
||||
"True", true, "R", role.formatted("a"), role.formatted("b")),
|
||||
new DetailsRow("in-place-get-att", "AWS::AutoScaling::AutoScalingGroup", asg, asg, null,
|
||||
List.of("Properties"), List.of("Properties|LaunchTemplate|Never|ResourceAttribute|Dynamic|Lt.LatestVersionNumber"),
|
||||
"False", true, "R", launchTemplate.formatted("ami-12345678"), launchTemplate.formatted("ami-87654321")),
|
||||
new DetailsRow("sub-variable-named-ref", "AWS::AutoScaling::AutoScalingGroup", asgSub, asgSub, null,
|
||||
List.of("Properties"), List.of("Properties|LaunchTemplate|Never|ResourceAttribute|Dynamic|Lt.LatestVersionNumber"),
|
||||
"False", true, "R", launchTemplate.formatted("ami-12345678").replace("cs-det-lt", "cs-det-lt-sub"),
|
||||
launchTemplate.formatted("ami-87654321").replace("cs-det-lt", "cs-det-lt-sub")),
|
||||
// This pins Floci's merge of both details. The AWS response for this combination is unconfirmed.
|
||||
new DetailsRow("edited-and-ref", "AWS::SQS::Queue", queueName.formatted("both", "a"),
|
||||
queueName.formatted("both", "b"), null, List.of("Properties"),
|
||||
List.of("Properties|DisplayName|Never" + direct, "Properties|DisplayName|Never|ResourceReference|Static|R"),
|
||||
"False", true, "Reader", topic.formatted("\"before\""), readsRef));
|
||||
|
||||
List<String> failures = new ArrayList<>();
|
||||
for (DetailsRow row : rows) {
|
||||
String stackName = "cs-details-" + row.name();
|
||||
stacksToDelete.add(stackName);
|
||||
createStack(stackName, template(row.type(), row.oldProps()));
|
||||
createStack(stackName, template(row.type(), row.oldProps(), row.oldExtra()));
|
||||
XmlParser.XmlElement rc = resourceChange(describeChangeSet(stackName, row.name() + "-cs",
|
||||
template(row.type(), row.newProps()), row.newParam()), "R");
|
||||
template(row.type(), row.newProps(), row.newExtra()), row.newParam()), row.logicalId());
|
||||
if (!"Modify".equals(text(rc, "Action"))) {
|
||||
failures.add(row.name() + ": expected Modify for " + row.logicalId() + ", action=" + text(rc, "Action"));
|
||||
continue;
|
||||
}
|
||||
List<String> scope = rc.child("Scope").children().stream().map(XmlParser.XmlElement::text).sorted().toList();
|
||||
List<String> details = detailsOf(rc);
|
||||
boolean recreates = row.details().stream().anyMatch(d -> d.contains("|Always|"));
|
||||
|
||||
Reference in new issue
Block a user