mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): resolve sequence-form GetAtt references (#8080)
This commit is contained in:
1 parent
f55f9f229b
commit
6ace00acc7
6 files changed
+398
-57
No files matched your search
@@ -1189,6 +1189,15 @@ public class CloudFormationService implements ResourceProvider {
|
||||
if (!replacedResourceIds.isEmpty() || !inPlaceChangedAttributes.isEmpty()) {
|
||||
Set<String> allResourceIds = new LinkedHashSet<>();
|
||||
newResources.fieldNames().forEachRemaining(allResourceIds::add);
|
||||
Map<String, String> physicalIds = new HashMap<>();
|
||||
for (StackResource resource : stack.resourcesSnapshot().values()) {
|
||||
if (resource.getPhysicalId() != null) {
|
||||
physicalIds.put(resource.getLogicalId(), resource.getPhysicalId());
|
||||
}
|
||||
}
|
||||
CloudFormationTemplateEngine dependencyEngine = new CloudFormationTemplateEngine(
|
||||
ownerAccount(stack), region, stack.getStackName(), stack.getStackId(),
|
||||
newResolvedParams, physicalIds, Map.of(), newConditions, Map.of(), objectMapper, null);
|
||||
|
||||
List<String> sortedLogicalIds = topologicalSort(newResources, newConditions);
|
||||
boolean anyNewChange = true;
|
||||
@@ -1209,7 +1218,8 @@ public class CloudFormationService implements ResourceProvider {
|
||||
boolean referencesChangedAttr = false;
|
||||
if (!dependsOnReplaced) {
|
||||
for (Map.Entry<String, Set<String>> entry : inPlaceChangedAttributes.entrySet()) {
|
||||
if (referencesAnyAttribute(newDef.path("Properties"), entry.getKey(), entry.getValue(), newConditions)) {
|
||||
if (referencesAnyAttribute(newDef.path("Properties"), entry.getKey(), entry.getValue(),
|
||||
newConditions, dependencyEngine)) {
|
||||
referencesChangedAttr = true;
|
||||
break;
|
||||
}
|
||||
@@ -2539,7 +2549,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
for (String candidateId : sortedLogicalIds) {
|
||||
if (!changedResourceIds.contains(candidateId)) {
|
||||
if (referencesAnyAttribute(resources.path(candidateId).path("Properties"),
|
||||
logicalId, changedAttrNames, conditions)) {
|
||||
logicalId, changedAttrNames, conditions, engine)) {
|
||||
changedResourceIds.add(candidateId);
|
||||
}
|
||||
}
|
||||
@@ -5612,61 +5622,41 @@ public class CloudFormationService implements ResourceProvider {
|
||||
* is updated in-place with modified attributes (e.g. LatestVersionNumber of LaunchTemplate).
|
||||
*/
|
||||
private boolean referencesAnyAttribute(JsonNode node, String targetLogicalId, Set<String> targetAttrNames,
|
||||
Map<String, Boolean> conditions) {
|
||||
Map<String, Boolean> conditions, CloudFormationTemplateEngine engine) {
|
||||
if (node == null || node.isNull() || node.isMissingNode()) {
|
||||
return false;
|
||||
}
|
||||
if (node.isObject()) {
|
||||
if (node.has("Fn::GetAtt")) {
|
||||
JsonNode getAtt = node.get("Fn::GetAtt");
|
||||
String logicalId = null;
|
||||
if (getAtt.isArray() && getAtt.size() >= 2) {
|
||||
logicalId = getAtt.get(0).asText();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 1; i < getAtt.size(); i++) {
|
||||
if (i > 1) {
|
||||
sb.append('.');
|
||||
}
|
||||
sb.append(getAtt.get(i).asText());
|
||||
}
|
||||
if (targetLogicalId.equals(logicalId)
|
||||
&& (targetAttrNames.contains(sb.toString()) || targetAttrNames.contains(getAtt.get(1).asText()))) {
|
||||
return true;
|
||||
}
|
||||
} else if (getAtt.isTextual()) {
|
||||
String[] parts = getAtt.textValue().split("\\.", 2);
|
||||
logicalId = parts[0];
|
||||
String attrName = parts.length > 1 ? parts[1] : null;
|
||||
if (targetLogicalId.equals(logicalId) && attrName != null && targetAttrNames.contains(attrName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (node.has("Fn::GetAtt")
|
||||
&& engine.referencesGetAttAttribute(node.get("Fn::GetAtt"), targetLogicalId, targetAttrNames)) {
|
||||
return true;
|
||||
}
|
||||
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);
|
||||
return referencesAnyAttribute(fnIf.get(condition ? 1 : 2), targetLogicalId, targetAttrNames,
|
||||
conditions, engine);
|
||||
}
|
||||
return referencesAnyAttribute(fnIf.get(1), targetLogicalId, targetAttrNames, conditions)
|
||||
|| referencesAnyAttribute(fnIf.get(2), targetLogicalId, targetAttrNames, conditions);
|
||||
return referencesAnyAttribute(fnIf.get(1), targetLogicalId, targetAttrNames, conditions, engine)
|
||||
|| referencesAnyAttribute(fnIf.get(2), targetLogicalId, targetAttrNames, conditions, engine);
|
||||
}
|
||||
}
|
||||
if (node.has("Fn::Sub")) {
|
||||
if (subReferencesAttribute(node.get("Fn::Sub"), targetLogicalId, targetAttrNames, conditions)) {
|
||||
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)) {
|
||||
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)) {
|
||||
if (referencesAnyAttribute(item, targetLogicalId, targetAttrNames, conditions, engine)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -5675,7 +5665,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
}
|
||||
|
||||
private boolean subReferencesAttribute(JsonNode sub, String targetLogicalId, Set<String> targetAttrNames,
|
||||
Map<String, Boolean> conditions) {
|
||||
Map<String, Boolean> conditions, CloudFormationTemplateEngine engine) {
|
||||
String template;
|
||||
Set<String> explicitVars = new HashSet<>();
|
||||
|
||||
@@ -5685,7 +5675,7 @@ public class CloudFormationService implements ResourceProvider {
|
||||
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)) {
|
||||
if (referencesAnyAttribute(sub.get(1), targetLogicalId, targetAttrNames, conditions, engine)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
+28
-7
@@ -18,6 +18,7 @@ import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.UnaryOperator;
|
||||
@@ -933,15 +934,35 @@ public class CloudFormationTemplateEngine {
|
||||
return parts == null ? TextNode.valueOf("") : resolveGetAttNodeParts(parts[0], parts[1]);
|
||||
}
|
||||
|
||||
private static String[] getAttParts(JsonNode getAtt) {
|
||||
if (getAtt.isArray() && getAtt.size() == 2) {
|
||||
return new String[] {getAtt.get(0).asText(), getAtt.get(1).asText()};
|
||||
/** Matches a GetAtt dependency using the same operands as attribute value resolution. */
|
||||
public boolean referencesGetAttAttribute(JsonNode getAtt, String logicalId, Set<String> attributeNames) {
|
||||
String[] parts = getAttParts(getAtt);
|
||||
return parts != null && logicalId.equals(parts[0]) && attributeNames.contains(parts[1]);
|
||||
}
|
||||
|
||||
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;
|
||||
if (getAtt.isArray()) {
|
||||
if (getAtt.size() != 2) {
|
||||
throw new AwsException("ValidationError", errorMessage, 400);
|
||||
}
|
||||
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;
|
||||
}
|
||||
if (getAtt.isTextual()) {
|
||||
String[] parts = getAtt.textValue().split("\\.", 2);
|
||||
return new String[] {parts[0], parts.length > 1 ? parts[1] : ""};
|
||||
if (parts.length != 2 || parts[0].isEmpty() || parts[1].isEmpty()) {
|
||||
throw new AwsException("ValidationError", errorMessage, 400);
|
||||
}
|
||||
return null;
|
||||
return parts;
|
||||
}
|
||||
|
||||
private Map<String, String> findAttributeSource(String logicalId, String attrName) {
|
||||
|
||||
@@ -12,9 +12,7 @@ import org.yaml.snakeyaml.nodes.ScalarNode;
|
||||
import org.yaml.snakeyaml.nodes.SequenceNode;
|
||||
import org.yaml.snakeyaml.nodes.Tag;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -99,19 +97,10 @@ public class CloudFormationYamlParser {
|
||||
}
|
||||
|
||||
private Object fnGetAtt(Node n) {
|
||||
String raw = scalar(n);
|
||||
// !GetAtt Resource.Attribute
|
||||
int dot = raw.indexOf('.');
|
||||
List<String> parts = new ArrayList<>();
|
||||
if (dot > 0) {
|
||||
parts.add(raw.substring(0, dot));
|
||||
parts.add(raw.substring(dot + 1));
|
||||
} else {
|
||||
parts.add(raw);
|
||||
if (n instanceof SequenceNode) {
|
||||
return fnMap("Fn::GetAtt", n);
|
||||
}
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("Fn::GetAtt", parts);
|
||||
return map;
|
||||
return scalarMap("Fn::GetAtt", scalar(n));
|
||||
}
|
||||
|
||||
private Object construct(Node n) {
|
||||
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.ChangeSetType;
|
||||
import software.amazon.awssdk.services.cloudformation.model.ResourceStatus;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
@QuarkusTest
|
||||
class CloudFormationGetAttYamlIntegrationTest {
|
||||
|
||||
@Test
|
||||
void getAttSequenceAndScalarFormsReturnTheProvisionedQueueArn() {
|
||||
String name = "cfn-getatt-yaml-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
Parameters:
|
||||
AttributeName:
|
||||
Type: String
|
||||
Default: Arn
|
||||
Resources:
|
||||
Queue:
|
||||
Type: AWS::SQS::Queue
|
||||
Properties:
|
||||
QueueName: %s
|
||||
Outputs:
|
||||
Flow:
|
||||
Value: !GetAtt [Queue, Arn]
|
||||
Block:
|
||||
Value: !GetAtt
|
||||
- Queue
|
||||
- Arn
|
||||
Scalar:
|
||||
Value: !GetAtt Queue.Arn
|
||||
LongScalar:
|
||||
Value:
|
||||
Fn::GetAtt: Queue.Arn
|
||||
Referenced:
|
||||
Value: !GetAtt [Queue, !Ref AttributeName]
|
||||
LongReferenced:
|
||||
Value:
|
||||
Fn::GetAtt:
|
||||
- Queue
|
||||
- Ref: AttributeName
|
||||
""".formatted(name);
|
||||
|
||||
try (CloudFormationClient cloudFormation = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
SqsClient sqs = AwsTestClients.create(SqsClient.builder(), "test", Region.US_EAST_1)) {
|
||||
cloudFormation.createStack(request -> request.stackName(name).templateBody(template));
|
||||
try {
|
||||
Stack stack = CfnStackWaits.awaitStatus(cloudFormation, name, "CREATE_COMPLETE");
|
||||
String queueUrl = sqs.getQueueUrl(request -> request.queueName(name)).queueUrl();
|
||||
String queueArn = sqs.getQueueAttributes(request -> request.queueUrl(queueUrl)
|
||||
.attributeNames(QueueAttributeName.QUEUE_ARN))
|
||||
.attributes().get(QueueAttributeName.QUEUE_ARN);
|
||||
assertNotNull(queueArn);
|
||||
|
||||
for (String output : List.of("Flow", "Block", "Scalar", "LongScalar", "Referenced", "LongReferenced")) {
|
||||
assertEquals(queueArn, CfnStackWaits.output(stack, output), output);
|
||||
}
|
||||
} finally {
|
||||
cloudFormation.deleteStack(request -> request.stackName(name));
|
||||
CfnStackWaits.awaitStackDeleted(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', value = {
|
||||
"!GetAtt [Queue] | false",
|
||||
"!GetAtt [Queue, ''] | false",
|
||||
"!GetAtt [] | false",
|
||||
"!GetAtt [Queue, !Ref EmptyAttribute] | false",
|
||||
"!GetAtt Queue | true",
|
||||
"!GetAtt Queue. | true",
|
||||
"!GetAtt .Arn | true",
|
||||
"!GetAtt '' | true",
|
||||
"{Fn::GetAtt: Queue} | true"
|
||||
})
|
||||
void invalidGetAttOutputReportsTheValidationReason(String expression, boolean stringForm) {
|
||||
String name = "cfn-getatt-invalid-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
Parameters:
|
||||
EmptyAttribute:
|
||||
Type: String
|
||||
Default: ""
|
||||
Resources:
|
||||
Queue:
|
||||
Type: AWS::SQS::Queue
|
||||
Properties:
|
||||
QueueName: %s
|
||||
Outputs:
|
||||
Invalid:
|
||||
Value: %s
|
||||
""".formatted(name, expression);
|
||||
|
||||
try (CloudFormationClient cloudFormation = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1)) {
|
||||
cloudFormation.createStack(request -> request.stackName(name).templateBody(template));
|
||||
try {
|
||||
Stack stack = CfnStackWaits.awaitStatus(cloudFormation, name, "ROLLBACK_COMPLETE");
|
||||
String expectedMessage = stringForm
|
||||
? "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";
|
||||
assertEquals(expectedMessage, stack.stackStatusReason());
|
||||
} finally {
|
||||
cloudFormation.deleteStack(request -> request.stackName(name));
|
||||
CfnStackWaits.awaitStackDeleted(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void stackUpdatesTrackReferencedAttributeNames(boolean executeChangeSet) {
|
||||
String name = "cfn-getatt-update-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
Parameters:
|
||||
AttributeName:
|
||||
Type: String
|
||||
Default: LatestVersionNumber
|
||||
StableAttributeName:
|
||||
Type: String
|
||||
Default: DefaultVersionNumber
|
||||
Conditions:
|
||||
UseLatest: !Equals [!Ref AttributeName, LatestVersionNumber]
|
||||
Resources:
|
||||
Lt:
|
||||
Type: AWS::EC2::LaunchTemplate
|
||||
Properties:
|
||||
LaunchTemplateData:
|
||||
ImageId: ami-12345678
|
||||
InstanceType: t3.micro
|
||||
Latest:
|
||||
Type: AWS::SSM::Parameter
|
||||
Properties:
|
||||
Name: %1$s/latest
|
||||
Type: String
|
||||
Value: !GetAtt [Lt, !Ref AttributeName]
|
||||
Wrapped:
|
||||
Type: AWS::SSM::Parameter
|
||||
Properties:
|
||||
Name: %1$s/wrapped
|
||||
Type: String
|
||||
Value: !Sub ["${Version}", {Version: !If [UseLatest, !GetAtt [Lt, !Ref AttributeName], "0"]}]
|
||||
Stable:
|
||||
Type: AWS::SSM::Parameter
|
||||
Properties:
|
||||
Name: %1$s/stable
|
||||
Type: String
|
||||
Value: !GetAtt [Lt, !Ref StableAttributeName]
|
||||
Inactive:
|
||||
Type: AWS::SSM::Parameter
|
||||
Properties:
|
||||
Name: %1$s/inactive
|
||||
Type: String
|
||||
Value: !If [UseLatest, !GetAtt [Lt, !Ref StableAttributeName], !GetAtt [Lt, !Ref AttributeName]]
|
||||
""".formatted(name);
|
||||
String updatedTemplate = template.replace("t3.micro", "t3.small");
|
||||
|
||||
try (CloudFormationClient cloudFormation = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
SsmClient ssm = AwsTestClients.create(SsmClient.builder(), "test", Region.US_EAST_1)) {
|
||||
cloudFormation.createStack(request -> request.stackName(name).templateBody(template));
|
||||
try {
|
||||
CfnStackWaits.awaitStatus(cloudFormation, name, "CREATE_COMPLETE");
|
||||
for (String parameter : List.of("latest", "wrapped", "stable", "inactive")) {
|
||||
assertEquals("1", ssm.getParameter(request -> request.name(name + "/" + parameter))
|
||||
.parameter().value(), parameter);
|
||||
}
|
||||
|
||||
if (executeChangeSet) {
|
||||
cloudFormation.createChangeSet(request -> request.stackName(name)
|
||||
.changeSetName("update-version").changeSetType(ChangeSetType.UPDATE)
|
||||
.templateBody(updatedTemplate));
|
||||
Set<String> changedResources = cloudFormation.describeChangeSet(request ->
|
||||
request.stackName(name).changeSetName("update-version")).changes().stream()
|
||||
.map(change -> change.resourceChange().logicalResourceId()).collect(Collectors.toSet());
|
||||
assertEquals(Set.of("Lt", "Latest", "Wrapped"), changedResources,
|
||||
"The preview must include only consumers of the changed attribute");
|
||||
cloudFormation.executeChangeSet(request ->
|
||||
request.stackName(name).changeSetName("update-version"));
|
||||
} else {
|
||||
cloudFormation.updateStack(request -> request.stackName(name).templateBody(updatedTemplate));
|
||||
}
|
||||
|
||||
CfnStackWaits.awaitStatus(cloudFormation, name, "UPDATE_COMPLETE");
|
||||
for (String parameter : List.of("latest", "wrapped")) {
|
||||
assertEquals("2", ssm.getParameter(request -> request.name(name + "/" + parameter))
|
||||
.parameter().value(), parameter + " must read the updated launch template version");
|
||||
}
|
||||
for (String parameter : List.of("stable", "inactive")) {
|
||||
assertEquals("1", ssm.getParameter(request -> request.name(name + "/" + parameter))
|
||||
.parameter().value(), parameter);
|
||||
}
|
||||
Set<String> updatedParameters = cloudFormation.describeStackEvents(request -> request.stackName(name))
|
||||
.stackEvents().stream()
|
||||
.filter(event -> "AWS::SSM::Parameter".equals(event.resourceType())
|
||||
&& event.resourceStatus() == ResourceStatus.UPDATE_COMPLETE)
|
||||
.map(event -> event.logicalResourceId()).collect(Collectors.toSet());
|
||||
assertEquals(Set.of("Latest", "Wrapped"), updatedParameters,
|
||||
"Unchanged attributes and inactive branches must not trigger an update");
|
||||
} finally {
|
||||
cloudFormation.deleteStack(request -> request.stackName(name));
|
||||
CfnStackWaits.awaitStackDeleted(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -12,6 +12,7 @@ import org.junit.jupiter.params.provider.ValueSource;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.UnaryOperator;
|
||||
|
||||
@@ -178,6 +179,87 @@ class CloudFormationTemplateEngineTest {
|
||||
assertEquals("Thing.Missing", e.resolve(json("{\"Fn::GetAtt\": [\"Thing\", \"Missing\"]}")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"Value: !GetAtt [Vpc, !Ref AttributeName]\n",
|
||||
"Value: !GetAtt\n - Vpc\n - !Ref AttributeName\n",
|
||||
"Value:\n Fn::GetAtt: [Vpc, {Ref: AttributeName}]\n"
|
||||
})
|
||||
void getAttSequenceResolvesAttributeNameRef(String yaml) {
|
||||
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
|
||||
"stack/id", Map.of("AttributeName", "CidrBlock"), Map.of(),
|
||||
Map.of("Vpc", Map.of("CidrBlock", "10.0.0.0/16")), Map.of(), Map.of(), mapper, name -> null);
|
||||
JsonNode value = new CloudFormationYamlParser(mapper).parse(yaml).get("Value");
|
||||
|
||||
assertEquals("10.0.0.0/16", e.resolve(value));
|
||||
assertEquals("10.0.0.0/16", e.resolveNode(value).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAttAttributeNameRefRetainsTypedList() {
|
||||
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
|
||||
"stack/id", Map.of("AttributeName", "SourceIdsList"), Map.of(),
|
||||
Map.of("Watcher", Map.of("SourceIdsList", "stored")), Map.of(), Map.of(), mapper,
|
||||
null, UnaryOperator.identity(), null, Map.of(),
|
||||
(logicalId, attribute, value) -> mapper.createArrayNode().add("first,with-comma").add("second"));
|
||||
JsonNode value = new CloudFormationYamlParser(mapper).parse(
|
||||
"Value: !GetAtt [Watcher, !Ref AttributeName]").get("Value");
|
||||
|
||||
assertEquals(json("[\"first,with-comma\", \"second\"]"), e.resolveNode(value));
|
||||
assertEquals("first,with-comma|second", e.resolve(json("""
|
||||
{
|
||||
"Fn::Join": [
|
||||
"|",
|
||||
{
|
||||
"Fn::GetAtt": ["Watcher", {"Ref": "AttributeName"}]
|
||||
}
|
||||
]
|
||||
}
|
||||
""")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"[]", "[Vpc]", "[Vpc, CidrBlock, Extra]",
|
||||
"['', CidrBlock]", "[Vpc, '']", "['', '']",
|
||||
"[Vpc, !Ref EmptyAttribute]"
|
||||
})
|
||||
void getAttRejectsMissingOrEmptyOperands(String operands) {
|
||||
assertInvalidGetAtt(operands, "Template error: every Fn::GetAtt object requires two non-empty parameters, "
|
||||
+ "the resource name and the resource attribute");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"'Vpc.'", "'.CidrBlock'", "'Vpc'", "''"})
|
||||
void getAttRejectsMalformedStringOperands(String operand) {
|
||||
assertInvalidGetAtt(operand, "Template error: if specifying one argument to Fn::GetAtt, "
|
||||
+ "that argument must be a non-empty string in format <LogicalId>.<Attribute>");
|
||||
}
|
||||
|
||||
private void assertInvalidGetAtt(String operands, String expectedMessage) {
|
||||
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
|
||||
"stack/id", Map.of("EmptyAttribute", ""), Map.of(),
|
||||
Map.of("Vpc", Map.of("CidrBlock", "10.0.0.0/16")), Map.of(), Map.of(), mapper, name -> null);
|
||||
CloudFormationYamlParser parser = new CloudFormationYamlParser(mapper);
|
||||
for (JsonNode value : List.of(parser.parse("!GetAtt " + operands),
|
||||
parser.parse("Fn::GetAtt: " + operands))) {
|
||||
AwsException scalarFailure = assertThrows(AwsException.class, () -> e.resolve(value));
|
||||
AwsException nodeFailure = assertThrows(AwsException.class, () -> e.resolveNode(value));
|
||||
AwsException dependencyFailure = assertThrows(AwsException.class,
|
||||
() -> e.referencesGetAttAttribute(value.get("Fn::GetAtt"), "Vpc", Set.of("CidrBlock")));
|
||||
|
||||
assertEquals("ValidationError", scalarFailure.getErrorCode());
|
||||
assertEquals("ValidationError", nodeFailure.getErrorCode());
|
||||
assertEquals("ValidationError", dependencyFailure.getErrorCode());
|
||||
assertEquals(400, scalarFailure.getHttpStatus());
|
||||
assertEquals(400, nodeFailure.getHttpStatus());
|
||||
assertEquals(400, dependencyFailure.getHttpStatus());
|
||||
assertEquals(expectedMessage, scalarFailure.getMessage());
|
||||
assertEquals(scalarFailure.getMessage(), nodeFailure.getMessage());
|
||||
assertEquals(scalarFailure.getMessage(), dependencyFailure.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"{\"Fn::Sub\":\"${Bucket.Missing}/*\"}",
|
||||
|
||||
+32
-1
@@ -3,6 +3,8 @@ package io.floci.aws.services.cloudformation;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -37,7 +39,7 @@ class CloudFormationYamlParserTest {
|
||||
Fn::Select:
|
||||
- 1
|
||||
- Fn::Cidr:
|
||||
- Fn::GetAtt: [Vpc, CidrBlock]
|
||||
- Fn::GetAtt: Vpc.CidrBlock
|
||||
- 4
|
||||
- 8
|
||||
""");
|
||||
@@ -62,4 +64,33 @@ class CloudFormationYamlParserTest {
|
||||
assertEquals(longForm, shorthand);
|
||||
assertEquals("Producer", shorthand.get("SubnetId").get("Fn::GetStackOutput").get("StackName").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"Value: !GetAtt [Vpc, CidrBlock]\n",
|
||||
"Value: !GetAtt\n - Vpc\n - CidrBlock\n"
|
||||
})
|
||||
void getAttShorthandAcceptsTheSequenceForm(String yaml) throws Exception {
|
||||
JsonNode shorthand = parse(yaml);
|
||||
JsonNode longForm = parse("""
|
||||
Value:
|
||||
Fn::GetAtt: [Vpc, CidrBlock]
|
||||
""");
|
||||
assertEquals(longForm, shorthand);
|
||||
assertEquals("CidrBlock", shorthand.get("Value").get("Fn::GetAtt").get(1).asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAttSequenceFormPreservesANestedIntrinsic() throws Exception {
|
||||
JsonNode shorthand = parse("Value: !GetAtt [Vpc, !Ref AttributeName]\n");
|
||||
assertEquals("AttributeName", shorthand.get("Value").get("Fn::GetAtt").get(1).get("Ref").asText());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"Vpc.CidrBlock", "Vpc", "Vpc.", ".CidrBlock", ""})
|
||||
void getAttScalarFormPreservesItsOriginalString(String operand) throws Exception {
|
||||
JsonNode getAtt = parse("Value: !GetAtt '" + operand + "'").get("Value").get("Fn::GetAtt");
|
||||
assertTrue(getAtt.isTextual());
|
||||
assertEquals(operand, getAtt.textValue());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user