fix(cloudformation): preserve mapped list values (#7511)

This commit is contained in:
Jackson Price authored and GitHub committed 2026-11-04 14:05:30 -04:00
1 parent ecd1138d86
commit 31451dfff3
9 files changed
+604 -55

No files matched your search

+8
View File
@@ -3,6 +3,14 @@
**Protocol:** Query (XML) — `POST http://localhost:4566/` with `Action=` parameter
**Endpoint:** `POST http://localhost:4566/`
## Mapping values
`Fn::FindInMap` preserves both string and list values from `Mappings`. Mapped lists
can feed list properties or a conditional `Fn::If` branch. `Fn::Select` and
`Fn::Join` preserve literal commas and empty list positions. This includes templates
that choose between mapped Availability Zones and `Fn::GetAZs`. AWS documents
both value types in the [Mappings syntax](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html).
## IAM role session duration
`AWS::IAM::Role` applies `MaxSessionDuration` on creation and update, including
@@ -331,6 +331,9 @@ public class CloudFormationTemplateEngine {
if (node.has("Fn::Select")) {
return resolveNode(selectedElement(node.get("Fn::Select")));
}
if (node.has("Fn::FindInMap")) {
return resolveNode(findMappedValue(node.get("Fn::FindInMap")));
}
if (callsIntrinsic(node)) {
return TextNode.valueOf(resolve(node));
}
@@ -663,6 +666,9 @@ public class CloudFormationTemplateEngine {
return resolveListElements(node, resolveDynamicReferences);
}
if (node.isObject()) {
if (node.has("Fn::FindInMap")) {
return resolveList(findMappedValue(node.get("Fn::FindInMap")), resolveDynamicReferences);
}
if (node.has("Fn::GetAtt")) {
JsonNode attribute = resolveGetAttNode(node.get("Fn::GetAtt"));
if (attribute.isArray()) {
@@ -804,6 +810,9 @@ public class CloudFormationTemplateEngine {
if (node.has("Fn::Split") || node.has("Fn::GetAZs") || node.has("Fn::Cidr")) {
return true;
}
if (node.has("Fn::FindInMap")) {
return findMappedValue(node.get("Fn::FindInMap")).isArray();
}
if (node.has("Fn::If")) {
JsonNode branch = selectIfBranch(node.get("Fn::If"));
return branch != null && isListValuedIntrinsic(branch);
@@ -963,6 +972,10 @@ public class CloudFormationTemplateEngine {
}
private String resolveFindInMap(JsonNode node) {
return resolve(findMappedValue(node));
}
private JsonNode findMappedValue(JsonNode node) {
if (node.isArray()) {
String mapName = resolve(node.get(0));
String topLvlName = resolve(node.get(1));
@@ -974,12 +987,12 @@ public class CloudFormationTemplateEngine {
if (topLvl != null && topLvl.isObject()) {
JsonNode secondLvl = topLvl.get(secondLvlName);
if (secondLvl != null) {
return resolve(secondLvl);
return secondLvl;
}
}
}
}
return "";
return TextNode.valueOf("");
}
private String resolveImportValue(JsonNode node) {
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
@@ -10,12 +11,10 @@ import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Tag;
import java.time.Duration;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -76,12 +75,12 @@ class CloudFormationFlowLogTagsIntegrationTest {
"Tags": [{"Key": {"Ref": "TagKey"}, "Value": "core"}]""";
cfn.createStack(request -> request.stackName(stackName).templateBody(template(keyFromParameter)));
stackCreated = true;
awaitStack("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
String flowLogId = flowLogId();
cfn.updateStack(request -> request.stackName(stackName).templateBody(template(keyFromParameter))
.parameters(parameter -> parameter.parameterKey("TagKey").parameterValue("owner")));
awaitStack("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
// Re-resolving the previous template would read owner too and leave team behind.
assertEquals(Map.of("owner", "core"), tags(flowLogId));
@@ -91,7 +90,7 @@ class CloudFormationFlowLogTagsIntegrationTest {
private String createStackWithExternalTag() {
cfn.createStack(request -> request.stackName(stackName).templateBody(template(tagsProperty("team", "core"))));
stackCreated = true;
awaitStack("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
String flowLogId = flowLogId();
assertEquals(Map.of("team", "core"), tags(flowLogId));
ec2.createTags(request -> request.resources(flowLogId)
@@ -101,7 +100,7 @@ class CloudFormationFlowLogTagsIntegrationTest {
private void updateStack(String tagsProperty) {
cfn.updateStack(request -> request.stackName(stackName).templateBody(template(tagsProperty)));
awaitStack("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
}
private static String tagsProperty(String key, String value) {
@@ -132,12 +131,6 @@ class CloudFormationFlowLogTagsIntegrationTest {
""".formatted(tagsProperty);
}
private void awaitStack(String status) {
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertEquals(status, cfn.describeStacks(request -> request.stackName(stackName))
.stacks().getFirst().stackStatusAsString()));
}
private String flowLogId() {
return cfn.describeStacks(request -> request.stackName(stackName)).stacks().getFirst()
.outputs().getFirst().outputValue();
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.ValidateSignaturesProfile;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
@@ -92,14 +93,14 @@ class CloudFormationIamRoleDurationIntegrationTest {
cfn.updateStack(request -> request.stackName(name).templateBody(template(43200, false))
.parameters(parameter -> parameter.parameterKey("Duration").parameterValue("43200"))
.capabilitiesWithStrings("CAPABILITY_NAMED_IAM"));
awaitStack("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, name, "UPDATE_COMPLETE");
assertEquals(original.roleId(), role().roleId());
assertEquals(43200, role().maxSessionDuration());
assumeFor(43200);
cfn.updateStack(request -> request.stackName(name).templateBody(template(null, false))
.capabilitiesWithStrings("CAPABILITY_NAMED_IAM"));
awaitStack("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, name, "UPDATE_COMPLETE");
assertEquals(original.roleId(), role().roleId());
assertEquals(3600, role().maxSessionDuration());
assertRejected(3601);
@@ -114,7 +115,7 @@ class CloudFormationIamRoleDurationIntegrationTest {
cfn.updateStack(request -> request.stackName(name).templateBody(template(14400, true))
.parameters(parameter -> parameter.parameterKey("Duration").parameterValue("14400"))
.capabilitiesWithStrings("CAPABILITY_NAMED_IAM"));
awaitStack("UPDATE_ROLLBACK_COMPLETE");
CfnStackWaits.awaitStatus(cfn, name, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(original.roleId(), role().roleId());
assertEquals(7200, role().maxSessionDuration());
assumeFor(7200);
@@ -133,7 +134,7 @@ class CloudFormationIamRoleDurationIntegrationTest {
cfn.updateStack(request -> request.stackName(name).templateBody(updated.toString())
.parameters(parameter -> parameter.parameterKey("Duration").parameterValue("14400"))
.capabilitiesWithStrings("CAPABILITY_NAMED_IAM"));
awaitStack("UPDATE_ROLLBACK_COMPLETE");
CfnStackWaits.awaitStatus(cfn, name, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(original.roleId(), role().roleId());
assertEquals(7200, role().maxSessionDuration());
assumeFor(7200);
@@ -145,13 +146,7 @@ class CloudFormationIamRoleDurationIntegrationTest {
cfn.createStack(request -> request.stackName(name).templateBody(template(duration, false))
.capabilitiesWithStrings("CAPABILITY_NAMED_IAM"));
stackCreated = true;
awaitStack("CREATE_COMPLETE");
}
private void awaitStack(String status) {
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertEquals(status, cfn.describeStacks(request -> request.stackName(name))
.stacks().getFirst().stackStatusAsString()));
CfnStackWaits.awaitStatus(cfn, name, "CREATE_COMPLETE");
}
private Role role() {
@@ -0,0 +1,329 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
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.CloudFormationException;
import software.amazon.awssdk.services.cloudformation.model.Output;
import software.amazon.awssdk.services.cloudformation.model.Parameter;
import software.amazon.awssdk.services.cloudformation.model.StackResource;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Subnet;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudFormationMappingListIntegrationTest {
private final String name = "mapping-lists-" + UUID.randomUUID();
private CloudFormationClient cfn;
private Ec2Client ec2;
@BeforeEach
void clients() {
String account = String.format(Locale.ROOT, "%012d",
ThreadLocalRandom.current().nextLong(1, 1_000_000_000_000L));
cfn = AwsTestClients.create(CloudFormationClient.builder(), account, Region.US_EAST_1);
ec2 = AwsTestClients.create(Ec2Client.builder(), account, Region.US_EAST_1);
}
@AfterEach
void cleanup() {
try {
List<String> subnetIds = cfn.describeStackResources(request -> request.stackName(name))
.stackResources().stream()
.filter(resource -> "AWS::EC2::Subnet".equals(resource.resourceType()))
.map(StackResource::physicalResourceId).toList();
cfn.deleteStack(request -> request.stackName(name));
assertEquals(3, subnetIds.size(), "Capture every created subnet before deleting the stack");
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
CloudFormationException absent = assertThrows(CloudFormationException.class,
() -> cfn.describeStacks(request -> request.stackName(name)));
assertEquals("ValidationError", absent.awsErrorDetails().errorCode());
assertTrue(absent.getMessage().contains("does not exist"));
List<String> remaining = ec2.describeSubnets().subnets().stream().map(Subnet::subnetId).toList();
for (String subnetId : subnetIds) {
assertFalse(remaining.contains(subnetId), "Subnet remains after stack deletion: " + subnetId);
}
});
} finally {
ec2.close();
cfn.close();
}
}
@ParameterizedTest
@ValueSource(strings = {"Discover", "Mapped"})
void conditionalMappedListsPlaceEachSubnetInTheSelectedZone(String mode) {
cfn.createStack(request -> request.stackName(name).templateBody(template())
.parameters(mode(mode)));
CfnStackWaits.awaitStatus(cfn, name, "CREATE_COMPLETE");
assertPlacement(mode);
}
@Test
void changingTheSelectedMappingReplacesSubnetsInTheNewZones() {
cfn.createStack(request -> request.stackName(name).templateBody(template())
.parameters(mode("Discover")));
CfnStackWaits.awaitStatus(cfn, name, "CREATE_COMPLETE");
assertPlacement("Discover");
Map<String, String> previous = outputs();
String updated = template().replace("10.88.0.0/24", "10.88.3.0/24")
.replace("10.88.2.0/24", "10.88.4.0/24");
cfn.updateStack(request -> request.stackName(name).templateBody(updated)
.parameters(mode("Mapped")));
CfnStackWaits.awaitStatus(cfn, name, "UPDATE_COMPLETE");
assertPlacement("Mapped");
List<String> remaining = ec2.describeSubnets().subnets().stream().map(Subnet::subnetId).toList();
assertTrue(!remaining.contains(previous.get("Subnet0")) && !remaining.contains(previous.get("Subnet2")),
"Subnets whose selected zone changed must be replaced and cleaned up");
assertEquals(previous.get("Subnet1"), outputs().get("Subnet1"));
}
private void assertPlacement(String mode) {
Map<String, String> output = outputs();
List<String> expected = "Discover".equals(mode)
? List.of("us-east-1a", "us-east-1b", "us-east-1c")
: List.of("us-east-1c", "us-east-1b", "us-east-1a");
for (int index = 0; index < expected.size(); index++) {
String subnetId = output.get("Subnet" + index);
assertEquals(expected.get(index), ec2.describeSubnets(request -> request.subnetIds(subnetId))
.subnets().getFirst().availabilityZone());
}
assertEquals("Discover".equals(mode) ? "true" : "false", output.get("UsesDiscovery"));
assertEquals("first,with-comma||last", output.get("Joined"));
}
private Map<String, String> outputs() {
return cfn.describeStacks(request -> request.stackName(name)).stacks().getFirst().outputs().stream()
.collect(Collectors.toMap(Output::outputKey, Output::outputValue));
}
private static Parameter mode(String value) {
return Parameter.builder().parameterKey("ZoneMode").parameterValue(value).build();
}
private static String template() {
return """
{
"Parameters": {
"ZoneMode": {
"Type": "String"
}
},
"Mappings": {
"Zones": {
"Discover": {
"Values": [
"automatic"
]
},
"Mapped": {
"Values": [
"us-east-1c",
"us-east-1b",
"us-east-1a"
]
}
},
"Text": {
"Example": {
"Values": [
"first,with-comma",
"",
"last"
]
}
}
},
"Conditions": {
"UseDiscovery": {
"Fn::Equals": [
"automatic",
{
"Fn::Select": [
0,
{
"Fn::FindInMap": [
"Zones",
{
"Ref": "ZoneMode"
},
"Values"
]
}
]
}
]
}
},
"Resources": {
"Vpc": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": "10.88.0.0/16"
}
},
"Subnet0": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"VpcId": {
"Ref": "Vpc"
},
"CidrBlock": "10.88.0.0/24",
"AvailabilityZone": {
"Fn::Select": [
0,
{
"Fn::If": [
"UseDiscovery",
{
"Fn::GetAZs": {
"Ref": "AWS::Region"
}
},
{
"Fn::FindInMap": [
"Zones",
{
"Ref": "ZoneMode"
},
"Values"
]
}
]
}
]
}
}
},
"Subnet1": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"VpcId": {
"Ref": "Vpc"
},
"CidrBlock": "10.88.1.0/24",
"AvailabilityZone": {
"Fn::Select": [
1,
{
"Fn::If": [
"UseDiscovery",
{
"Fn::GetAZs": {
"Ref": "AWS::Region"
}
},
{
"Fn::FindInMap": [
"Zones",
{
"Ref": "ZoneMode"
},
"Values"
]
}
]
}
]
}
}
},
"Subnet2": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"VpcId": {
"Ref": "Vpc"
},
"CidrBlock": "10.88.2.0/24",
"AvailabilityZone": {
"Fn::Select": [
2,
{
"Fn::If": [
"UseDiscovery",
{
"Fn::GetAZs": {
"Ref": "AWS::Region"
}
},
{
"Fn::FindInMap": [
"Zones",
{
"Ref": "ZoneMode"
},
"Values"
]
}
]
}
]
}
}
}
},
"Outputs": {
"Subnet0": {
"Value": {
"Ref": "Subnet0"
}
},
"Subnet1": {
"Value": {
"Ref": "Subnet1"
}
},
"Subnet2": {
"Value": {
"Ref": "Subnet2"
}
},
"UsesDiscovery": {
"Value": {
"Fn::If": [
"UseDiscovery",
"true",
"false"
]
}
},
"Joined": {
"Value": {
"Fn::Join": [
"|",
{
"Fn::FindInMap": [
"Text",
"Example",
"Values"
]
}
]
}
}
}
}
""";
}
}
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.ses.SesReceiptRuleService;
import io.github.hectorvent.floci.services.ses.model.ReceiptRule;
import io.github.hectorvent.floci.services.ssm.SsmService;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
@@ -76,14 +77,14 @@ class CloudFormationSesReceiptRuleIntegrationTest {
initial.withObject("/Resources/Rule").put("UpdateReplacePolicy", "Retain");
}
cfn.createStack(r -> r.stackName(stackName).templateBody(initial.toString()));
awaitStatus("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
ObjectNode updated = (ObjectNode) mapper.readTree(template("store", false));
updated.withObject("/Resources/Rule/Properties").put("RuleSetName", ruleSet + "-next");
if (retain) {
updated.withObject("/Resources/Rule").put("UpdateReplacePolicy", "Retain");
}
cfn.updateStack(r -> r.stackName(stackName).templateBody(updated.toString()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertFalse(ses.describeReceiptRule(ruleSet + "-next", "store", "us-east-1").isEnabled());
if (retain) {
assertTrue(ses.describeReceiptRule(ruleSet, "store", "us-east-1").isEnabled());
@@ -101,11 +102,11 @@ class CloudFormationSesReceiptRuleIntegrationTest {
ObjectNode initial = (ObjectNode) mapper.readTree(template("store", true));
initial.withObject("/Resources/Rule/Properties").put("After", "anchor");
cfn.createStack(r -> r.stackName(stackName).templateBody(initial.toString()));
awaitStatus("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
ObjectNode updated = (ObjectNode) mapper.readTree(template("store", false));
updated.withObject("/Resources/Rule/Properties").put("After", "missing");
cfn.updateStack(r -> r.stackName(stackName).templateBody(updated.toString()));
awaitStatus("UPDATE_ROLLBACK_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_ROLLBACK_COMPLETE");
assertTrue(ses.describeReceiptRule(ruleSet, "store", "us-east-1").isEnabled());
assertEquals(List.of("anchor", "store"), ses.describeReceiptRuleSet(ruleSet, "us-east-1")
.getRules().stream().map(ReceiptRule::getName).toList());
@@ -127,7 +128,7 @@ class CloudFormationSesReceiptRuleIntegrationTest {
secondProperties.put("After", "anchor");
}
cfn.createStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
List<String> expected = explicitAfter ? List.of("anchor", "second", "first")
: List.of("second", "first", "anchor");
assertEquals(expected, ruleNames());
@@ -137,14 +138,14 @@ class CloudFormationSesReceiptRuleIntegrationTest {
}
template.withObject("/Resources/Rule/Properties/Rule").put("Enabled", false);
cfn.updateStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
List<String> migratedOrder = explicitAfter ? List.of("anchor", "first", "second")
: List.of("first", "second", "anchor");
assertEquals(legacy ? migratedOrder : expected, ruleNames());
assertFalse(ses.describeReceiptRule(ruleSet, "first", "us-east-1").isEnabled());
template.withObject("/Resources/Rule/Properties/Rule").put("Enabled", true);
cfn.updateStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertEquals(legacy ? migratedOrder : expected, ruleNames());
}
@@ -161,7 +162,7 @@ class CloudFormationSesReceiptRuleIntegrationTest {
template.withObject("/Resources/Rule/Properties").putObject("After").put("Ref", "AfterAnchor");
cfn.createStack(r -> r.stackName(stackName).templateBody(template.toString()).parameters(
Parameter.builder().parameterKey("AfterAnchor").parameterValue("anchor").build()));
awaitStatus("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
assertEquals(List.of("other", "anchor", "store"), ruleNames());
if (legacy) {
cloudFormation.describeStacks(stackName, "us-east-1", "000000000000").getFirst()
@@ -169,7 +170,7 @@ class CloudFormationSesReceiptRuleIntegrationTest {
}
cfn.updateStack(r -> r.stackName(stackName).templateBody(template.toString()).parameters(
Parameter.builder().parameterKey("AfterAnchor").parameterValue("other").build()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertEquals(List.of("other", "store", "anchor"), ruleNames());
}
@@ -194,11 +195,11 @@ class CloudFormationSesReceiptRuleIntegrationTest {
.put("After", "management");
second.putObject("Rule").put("Name", "between");
cfn.createStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
assertEquals(List.of("management", "between", "store"), ruleNames());
template.withObject("/Resources/Rule/Properties/Rule").put("Enabled", false);
cfn.updateStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertEquals(List.of("management", "between", "store"), ruleNames());
}
@@ -223,7 +224,7 @@ class CloudFormationSesReceiptRuleIntegrationTest {
properties.put("After", reference);
}
cfn.createStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
assertEquals(List.of("other", "anchor", "store"), ruleNames());
if (legacy) {
cloudFormation.describeStacks(stackName, "us-east-1", "000000000000").getFirst()
@@ -232,7 +233,7 @@ class CloudFormationSesReceiptRuleIntegrationTest {
ssm.putParameter(parameter, indexReference ? "0" : "other", "String", null, true, "us-east-1");
template.withObject("/Resources/Rule/Properties/Rule").put("Enabled", false);
cfn.updateStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertEquals(List.of("other", "store", "anchor"), ruleNames());
assertFalse(ses.describeReceiptRule(ruleSet, "store", "us-east-1").isEnabled());
} finally {
@@ -251,15 +252,15 @@ class CloudFormationSesReceiptRuleIntegrationTest {
second.put("Type", "AWS::SES::ReceiptRule").put("DependsOn", "Rule");
second.putObject("Properties").put("RuleSetName", ruleSet).putObject("Rule").put("Name", "second");
cfn.createStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("CREATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
assertEquals(List.of("second", "anchor", "first"), ruleNames());
template.withObject("/Resources/Rule/Properties").put("After", "second");
cfn.updateStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertEquals(List.of("second", "first", "anchor"), ruleNames());
template.withObject("/Resources/Rule/Properties").remove("After");
cfn.updateStack(r -> r.stackName(stackName).templateBody(template.toString()));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertEquals(List.of("first", "second", "anchor"), ruleNames());
}
@@ -275,7 +276,7 @@ class CloudFormationSesReceiptRuleIntegrationTest {
.addObject().putObject("S3Action").putObject("BucketName").put("Ref", "Bucket");
template.withObject("/Outputs").putObject("BucketName").putObject("Value").put("Ref", "Bucket");
cfn.createStack(r -> r.stackName(stackName).templateBody(template.toString()));
Stack created = awaitStatus("CREATE_COMPLETE");
Stack created = CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
String bucket = created.outputs().stream().filter(o -> "BucketName".equals(o.outputKey()))
.findFirst().orElseThrow().outputValue();
ReceiptRule rule = ses.describeReceiptRule(ruleSet, "store", "us-east-1");
@@ -287,13 +288,13 @@ class CloudFormationSesReceiptRuleIntegrationTest {
void provisionsUpdatesAndDeletesRealReceiptRules() throws Exception {
String initial = template("store", true);
cfn.createStack(r -> r.stackName(stackName).templateBody(initial));
Stack created = awaitStatus("CREATE_COMPLETE");
Stack created = CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
assertTrue(ses.describeReceiptRule(ruleSet, "store", "us-east-1").isEnabled());
assertTrue(created.outputs().stream().allMatch(o -> "store".equals(o.outputValue())));
String updated = template("store", false);
cfn.updateStack(r -> r.stackName(stackName).templateBody(updated));
awaitStatus("UPDATE_COMPLETE");
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
assertFalse(ses.describeReceiptRule(ruleSet, "store", "us-east-1").isEnabled());
cfn.deleteStack(r -> r.stackName(stackName));
@@ -302,12 +303,6 @@ class CloudFormationSesReceiptRuleIntegrationTest {
() -> ses.describeReceiptRule(ruleSet, "store", "us-east-1")).getErrorCode()));
}
private Stack awaitStatus(String expected) {
return await().atMost(Duration.ofSeconds(15)).until(
() -> cfn.describeStacks(r -> r.stackName(stackName)).stacks().getFirst(),
s -> expected.equals(s.stackStatusAsString()));
}
private String template(String name, boolean enabled) throws Exception {
return mapper.writeValueAsString(Map.of("Resources", Map.of("Rule", Map.of(
"Type", "AWS::SES::ReceiptRule", "Properties", Map.of("RuleSetName", ruleSet,
@@ -39,6 +39,111 @@ class CloudFormationTemplateEngineTest {
(Function<String, String>) name -> null);
}
@Test
void mappedListsKeepTheirShapeMemberCommasAndEmptyEntries() {
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
"stack/id", Map.of(), Map.of(), Map.of(), Map.of("UseMapping", true),
Map.of("Values", json("""
{
"Example": {
"List": [
"first,with-comma",
"",
"last"
],
"Scalar": "unchanged",
"Empty": []
}
}
""")), mapper, (Function<String, String>) name -> null);
JsonNode list = json("{\"Fn::FindInMap\":[\"Values\",\"Example\",\"List\"]}");
assertEquals(json("[\"first,with-comma\",\"\",\"last\"]"), e.resolveNode(list));
assertEquals(List.of("first,with-comma", "last"), e.resolveStringList(list));
assertEquals(List.of("first,with-comma", "", "last"), e.resolveLiteralList(mapper.createArrayNode().add(list)));
assertEquals("first,with-comma", e.resolve(json("""
{
"Fn::Select": [
0,
{
"Fn::FindInMap": [
"Values",
"Example",
"List"
]
}
]
}
""")));
assertEquals("", e.resolve(json("""
{
"Fn::Select": [
1,
{
"Fn::FindInMap": [
"Values",
"Example",
"List"
]
}
]
}
""")));
assertEquals("last", e.resolve(json("""
{
"Fn::Select": [
2,
{
"Fn::If": [
"UseMapping",
{
"Fn::FindInMap": [
"Values",
"Example",
"List"
]
},
[
"unused"
]
]
}
]
}
""")));
assertEquals("first,with-comma||last", e.resolve(json("""
{
"Fn::Join": [
"|",
{
"Fn::FindInMap": [
"Values",
"Example",
"List"
]
}
]
}
""")));
assertEquals(json("[]"), e.resolveNode(json("""
{
"Fn::FindInMap": [
"Values",
"Example",
"Empty"
]
}
""")));
assertEquals("unchanged", e.resolve(json("""
{
"Fn::FindInMap": [
"Values",
"Example",
"Scalar"
]
}
""")));
}
@Test
void joinAndSelectConsumeTypedGetAttArraysWithoutSplittingMemberCommas() {
CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
@@ -4,11 +4,16 @@ import io.restassured.path.xml.XmlPath;
import io.restassured.path.xml.element.Node;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@@ -98,13 +103,9 @@ public final class CfnStackWaits {
String status = xml.getString("**.find { it.name() == 'StackStatus' }");
String reason = xml.getString("**.find { it.name() == 'StackStatusReason' }");
last = new StackState(status == null || status.isEmpty() ? null : status, reason == null ? "" : reason);
if (expectedStatus.equals(last.status())) {
if (hasExpectedStatus(stackName, expectedStatus, last)) {
return last;
}
if (last.status() != null && TERMINAL.contains(last.status())) {
fail("Stack " + stackName + " reached " + last.status() + " instead of " + expectedStatus
+ ": " + last.reason());
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
@@ -116,6 +117,32 @@ public final class CfnStackWaits {
return last;
}
/** SDK counterpart of {@link #awaitStatus(String, String)}, retaining the complete stack response. */
public static Stack awaitStatus(CloudFormationClient client, String stackName, String expectedStatus) {
DescribeStacksRequest request = DescribeStacksRequest.builder().stackName(stackName).build();
return await("Stack " + stackName + " to reach " + expectedStatus)
.atMost(Duration.ofSeconds(10)).pollInterval(Duration.ofMillis(50)).until(() -> {
List<Stack> stacks = client.describeStacks(request).stacks();
if (stacks.isEmpty()) {
fail("DescribeStacks " + stackName + " returned no stacks");
}
return stacks.getFirst();
}, stack -> hasExpectedStatus(stackName, expectedStatus,
new StackState(stack.stackStatusAsString(),
stack.stackStatusReason() == null ? "" : stack.stackStatusReason())));
}
private static boolean hasExpectedStatus(String stackName, String expectedStatus, StackState state) {
if (expectedStatus.equals(state.status())) {
return true;
}
if (state.status() != null && TERMINAL.contains(state.status())) {
fail("Stack " + stackName + " reached " + state.status() + " instead of " + expectedStatus
+ ": " + state.reason());
}
return false;
}
/**
* The reason on the first resource event that failed a create or update in the stack's latest
* operation, the one its last stack-level CREATE_IN_PROGRESS or UPDATE_IN_PROGRESS began. The
@@ -0,0 +1,84 @@
package io.github.hectorvent.floci.testing;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;
import software.amazon.awssdk.services.cloudformation.model.DescribeStacksResponse;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class CfnStackWaitsTest {
private static final String NAME = "waiter-stack";
private static final DescribeStacksRequest REQUEST = DescribeStacksRequest.builder().stackName(NAME).build();
private final CloudFormationClient client = mock(CloudFormationClient.class);
@Test
void sdkWaitReturnsTheCompleteStackAfterProgress() {
Stack completed = Stack.builder().stackName(NAME).stackStatus("CREATE_COMPLETE")
.outputs(output -> output.outputKey("Bucket").outputValue("created-bucket")).build();
when(client.describeStacks(REQUEST)).thenReturn(
response(Stack.builder().stackStatus("CREATE_IN_PROGRESS").build()), response(completed));
assertSame(completed, CfnStackWaits.awaitStatus(client, NAME, "CREATE_COMPLETE"));
verify(client, times(2)).describeStacks(REQUEST);
}
@Test
void sdkWaitAcceptsAnExpectedRollback() {
Stack rollback = Stack.builder().stackStatus("UPDATE_ROLLBACK_COMPLETE")
.stackStatusReason("Resource update failed").build();
when(client.describeStacks(REQUEST)).thenReturn(response(rollback));
assertSame(rollback, CfnStackWaits.awaitStatus(client, NAME, "UPDATE_ROLLBACK_COMPLETE"));
verify(client).describeStacks(REQUEST);
}
@ParameterizedTest
@ValueSource(strings = {"CREATE_FAILED", "ROLLBACK_COMPLETE", "ROLLBACK_FAILED", "UPDATE_COMPLETE",
"UPDATE_FAILED", "UPDATE_ROLLBACK_COMPLETE", "UPDATE_ROLLBACK_FAILED", "DELETE_COMPLETE", "DELETE_FAILED"})
void sdkWaitRejectsAnyOtherTerminalStatusWithoutPollingAgain(String status) {
Stack terminal = Stack.builder().stackStatus(status).stackStatusReason("Resource rejected").build();
Stack laterSuccess = Stack.builder().stackStatus("CREATE_COMPLETE").build();
when(client.describeStacks(REQUEST)).thenReturn(response(terminal), response(laterSuccess));
AssertionError failure = assertThrows(AssertionError.class,
() -> CfnStackWaits.awaitStatus(client, NAME, "CREATE_COMPLETE"));
assertEquals("Stack " + NAME + " reached " + status + " instead of CREATE_COMPLETE: Resource rejected",
failure.getMessage());
verify(client).describeStacks(REQUEST);
}
@Test
void sdkWaitPropagatesDescribeErrorsWithoutPollingAgain() {
AwsServiceException error = CloudFormationException.builder().statusCode(400)
.message("Stack does not exist").build();
when(client.describeStacks(REQUEST)).thenThrow(error);
assertSame(error, assertThrows(CloudFormationException.class,
() -> CfnStackWaits.awaitStatus(client, NAME, "CREATE_COMPLETE")));
verify(client).describeStacks(REQUEST);
}
@Test
void sdkWaitRejectsAnEmptyStackResponseWithoutPollingAgain() {
when(client.describeStacks(REQUEST)).thenReturn(DescribeStacksResponse.builder().build());
AssertionError failure = assertThrows(AssertionError.class,
() -> CfnStackWaits.awaitStatus(client, NAME, "CREATE_COMPLETE"));
assertEquals("DescribeStacks " + NAME + " returned no stacks", failure.getMessage());
verify(client).describeStacks(REQUEST);
}
private static DescribeStacksResponse response(Stack stack) {
return DescribeStacksResponse.builder().stacks(stack).build();
}
}