Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): add Fn::GetAZs and Fn::Cidr intrinsics (#1365)
Hector Venturaad61bb5e2c77
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.javaindex ff10440788..17446a5143 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java@@ -6,16 +6,20 @@ import com.fasterxml.jackson.databind.node.TextNode;import io.github.hectorvent.floci.core.common.AwsException;import org.jboss.logging.Logger;+import java.util.ArrayList;+import java.util.Arrays;import java.util.Base64;import java.util.HashMap;import java.util.Iterator;+import java.util.List;import java.util.Map;import java.util.function.Function;+import java.util.regex.Pattern;/*** Resolves CloudFormation intrinsic functions and pseudo-parameters in template nodes.* Supported: Ref, Fn::Sub, Fn::Join, Fn::Select, Fn::If, Fn::Split, Fn::Base64,- * Fn::GetAtt, Condition.+ * Fn::GetAtt, Fn::GetAZs, Fn::Cidr, Fn::FindInMap, Fn::ImportValue, Condition.*/public class CloudFormationTemplateEngine {@@ -89,6 +93,12 @@ public class CloudFormationTemplateEngine {if (node.has("Fn::Split")) {return resolve(node.get("Fn::Split").get(1));}+ if (node.has("Fn::GetAZs")) {+ return String.join(",", resolveAvailabilityZones(node.get("Fn::GetAZs")));+ }+ if (node.has("Fn::Cidr")) {+ return String.join(",", resolveCidr(node.get("Fn::Cidr")));+ }if (node.has("Fn::GetAtt")) {return resolveGetAtt(node.get("Fn::GetAtt"));}@@ -112,7 +122,8 @@ public class CloudFormationTemplateEngine {if (node.isObject()) {if (node.has("Ref") || node.has("Fn::Sub") || node.has("Fn::Join") ||node.has("Fn::Select") || node.has("Fn::If") || node.has("Fn::Base64") ||- node.has("Fn::GetAtt") || node.has("Fn::ImportValue") || node.has("Fn::Split")) {+ node.has("Fn::GetAtt") || node.has("Fn::ImportValue") || node.has("Fn::Split") ||+ node.has("Fn::GetAZs") || node.has("Fn::Cidr") || node.has("Fn::FindInMap")) {return TextNode.valueOf(resolve(node));}// Plain object — resolve each field@@ -220,14 +231,129 @@ public class CloudFormationTemplateEngine {if (!select.isArray() || select.size() < 2) {return "";}- int index = select.get(0).asInt(0);- JsonNode list = select.get(1);- if (list.isArray() && index < list.size()) {- return resolve(list.get(index));+ int index = parseInt(resolve(select.get(0)), 0);+ List<String> items = resolveList(select.get(1));+ if (index >= 0 && index < items.size()) {+ return items.get(index);}return "";}+ /**+ * Resolves a node that represents a list — a literal array, a list-producing intrinsic+ * ({@code Fn::GetAZs}, {@code Fn::Cidr}, {@code Fn::Split}), or a comma-delimited scalar+ * (e.g. a {@code Ref} to a {@code List<>} parameter).+ */+ private List<String> resolveList(JsonNode node) {+ List<String> out = new ArrayList<>();+ if (node == null || node.isNull() || node.isMissingNode()) {+ return out;+ }+ if (node.isArray()) {+ for (JsonNode item : node) {+ out.add(resolve(item));+ }+ return out;+ }+ if (node.isObject()) {+ if (node.has("Fn::GetAZs")) {+ return resolveAvailabilityZones(node.get("Fn::GetAZs"));+ }+ if (node.has("Fn::Cidr")) {+ return resolveCidr(node.get("Fn::Cidr"));+ }+ if (node.has("Fn::Split")) {+ return resolveSplit(node.get("Fn::Split"));+ }+ }+ String scalar = resolve(node);+ if (!scalar.isEmpty()) {+ out.addAll(Arrays.asList(scalar.split(",", -1)));+ }+ return out;+ }++ private List<String> resolveSplit(JsonNode split) {+ if (!split.isArray() || split.size() < 2) {+ return List.of();+ }+ String delimiter = resolve(split.get(0));+ String source = resolve(split.get(1));+ if (delimiter.isEmpty()) {+ return List.of(source);+ }+ return Arrays.asList(source.split(Pattern.quote(delimiter), -1));+ }++ /**+ * {@code Fn::GetAZs} — returns the Availability Zones for a region. The argument is the region+ * (empty string means the stack's region). Floci seeds three default zones per region.+ */+ private List<String> resolveAvailabilityZones(JsonNode arg) {+ String r = (arg == null || arg.isNull()) ? region : resolve(arg);+ if (r == null || r.isBlank()) {+ r = region;+ }+ return List.of(r + "a", r + "b", r + "c");+ }++ /**+ * {@code Fn::Cidr} — splits an IPv4 CIDR block into {@code count} subnets, each with+ * {@code cidrBits} host bits (i.e. a /{@code (32 - cidrBits)} mask). IPv6 is not supported.+ */+ private List<String> resolveCidr(JsonNode args) {+ if (!args.isArray() || args.size() < 2) {+ return List.of();+ }+ String ipBlock = resolve(args.get(0));+ int count = parseInt(resolve(args.get(1)), 0);+ int cidrBits = args.size() > 2 ? parseInt(resolve(args.get(2)), 8) : 8;+ int slash = ipBlock.indexOf('/');+ if (slash < 0 || count <= 0 || cidrBits <= 0 || cidrBits > 32) {+ return List.of();+ }+ long base = ipv4ToLong(ipBlock.substring(0, slash));+ if (base < 0) {+ return List.of();+ }+ int newPrefix = 32 - cidrBits;+ long step = 1L << cidrBits;+ List<String> out = new ArrayList<>();+ for (int i = 0; i < count; i++) {+ out.add(longToIpv4(base + (long) i * step) + "/" + newPrefix);+ }+ return out;+ }++ private static int parseInt(String value, int fallback) {+ try {+ return Integer.parseInt(value.trim());+ } catch (NumberFormatException e) {+ return fallback;+ }+ }++ private static long ipv4ToLong(String ip) {+ String[] octets = ip.trim().split("\\.");+ if (octets.length != 4) {+ return -1;+ }+ long result = 0;+ for (String octet : octets) {+ int value = parseInt(octet, -1);+ if (value < 0 || value > 255) {+ return -1;+ }+ result = (result << 8) | value;+ }+ return result;+ }++ private static String longToIpv4(long value) {+ return ((value >> 24) & 0xFF) + "." + ((value >> 16) & 0xFF) + "."+ + ((value >> 8) & 0xFF) + "." + (value & 0xFF);+ }+private String resolveIf(JsonNode ifNode) {if (!ifNode.isArray() || ifNode.size() < 3) {return "";diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2IntegrationTest.javaindex bd6fb49f5d..dbf1479775 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2IntegrationTest.java@@ -130,6 +130,76 @@ class CloudFormationEc2IntegrationTest {.body(containsString("<LoadBalancerArn>"));}+ @Test+ void subnetAzAndCidrResolveFromGetAzsAndCidr() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-ec2-fn-" + suffix;++ // Subnet AZ comes from Fn::Select(Fn::GetAZs("")) and its CIDR from Fn::Cidr — the+ // pattern CDK emits. Both must resolve to real values on the provisioned subnet.+ String template = """+ {+ "Resources": {+ "Vpc": {+ "Type": "AWS::EC2::VPC",+ "Properties": {"CidrBlock": "10.30.0.0/16"}+ },+ "Subnet1": {+ "Type": "AWS::EC2::Subnet",+ "Properties": {+ "VpcId": {"Ref": "Vpc"},+ "CidrBlock": {"Fn::Select": [1, {"Fn::Cidr": ["10.30.0.0/16", 4, 8]}]},+ "AvailabilityZone": {"Fn::Select": [0, {"Fn::GetAZs": ""}]}+ }+ }+ },+ "Outputs": {+ "Subnet1Id": {"Value": {"Ref": "Subnet1"}}+ }+ }+ """;++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ String describeStacks = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))+ .extract().asString();++ List<String> subnetIds = extractSubnetIds(describeStacks);+ assertEquals(1, subnetIds.size(), "expected one exported subnet id, got: " + subnetIds);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", EC2_AUTH)+ .formParam("Action", "DescribeSubnets")+ .formParam("SubnetId.1", subnetIds.get(0))+ .when()+ .post("/")+ .then()+ .statusCode(200)+ // AZ resolved from Fn::Select(0, Fn::GetAZs("")) in the stack's region.+ .body(containsString("ap-southeast-2a"))+ // CIDR resolved from Fn::Select(1, Fn::Cidr(["10.30.0.0/16", 4, 8])).+ .body(containsString("10.30.1.0/24"));+ }+private static List<String> extractSubnetIds(String xml) {Matcher m = Pattern.compile("<OutputValue>(subnet-[0-9a-fA-F]+)</OutputValue>").matcher(xml);List<String> ids = new ArrayList<>();diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.javanew file mode 100644index 0000000000..666682b142--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java@@ -0,0 +1,61 @@+package io.github.hectorvent.floci.services.cloudformation;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.Test;++import java.util.Map;+import java.util.function.Function;++import static org.junit.jupiter.api.Assertions.assertEquals;++class CloudFormationTemplateEngineTest {++ private final ObjectMapper mapper = new ObjectMapper();++ private CloudFormationTemplateEngine engine() {+ return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",+ "stack/id", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,+ (Function<String, String>) name -> null);+ }++ private JsonNode json(String s) {+ try {+ return mapper.readTree(s);+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }++ @Test+ void getAzsReturnsStackRegionZones() {+ assertEquals("us-east-1a,us-east-1b,us-east-1c",+ engine().resolve(json("{\"Fn::GetAZs\": \"\"}")));+ }++ @Test+ void getAzsHonoursExplicitRegion() {+ assertEquals("eu-west-1a,eu-west-1b,eu-west-1c",+ engine().resolve(json("{\"Fn::GetAZs\": \"eu-west-1\"}")));+ }++ @Test+ void selectFromGetAzsResolvesZoneByIndex() {+ CloudFormationTemplateEngine e = engine();+ // CDK emits the index as a string; AWS also allows a number.+ assertEquals("us-east-1a", e.resolve(json("{\"Fn::Select\": [\"0\", {\"Fn::GetAZs\": \"\"}]}")));+ assertEquals("us-east-1b", e.resolve(json("{\"Fn::Select\": [1, {\"Fn::GetAZs\": \"\"}]}")));+ }++ @Test+ void cidrSplitsBlockIntoSubnets() {+ assertEquals("10.0.0.0/24,10.0.1.0/24,10.0.2.0/24,10.0.3.0/24",+ engine().resolve(json("{\"Fn::Cidr\": [\"10.0.0.0/16\", 4, 8]}")));+ }++ @Test+ void selectFromCidrResolvesSubnetByIndex() {+ assertEquals("10.0.2.0/24",+ engine().resolve(json("{\"Fn::Select\": [2, {\"Fn::Cidr\": [\"10.0.0.0/16\", 4, 8]}]}")));+ }+}