diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 869e7b3a11..c1ec1b6e81 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -220,7 +220,7 @@ Floci seeds the following resources on first use in each region so Terraform, th | Action | Description | |--------|-------------| -| CreateVpc | Creates a VPC with the requested CIDR block. | +| CreateVpc | Creates a VPC with the requested CIDR block. `InstanceTenancy` accepts `default` or `dedicated`; `host` is rejected with `InvalidParameterValue`, as on AWS. | | DescribeVpcs | Lists or returns stored VPCs. | | DeleteVpc | Deletes a VPC from the local EC2 store, together with its default security group and rules, main route table and default network ACL. Fails with `DependencyViolation` while the VPC still has a subnet, a security group, route table or network ACL other than those defaults, a VPC endpoint, or an attached internet gateway. Instances, NAT gateways and other subnet-resident resources are not checked. | | ModifyVpcAttribute | Updates supported VPC attributes. | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java index 26b52c0d47..782f42293d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java @@ -4,21 +4,41 @@ import com.fasterxml.jackson.databind.JsonNode; import io.github.hectorvent.floci.core.common.CidrCanonicalizer; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.github.hectorvent.floci.services.ec2.model.NetworkAcl; import io.github.hectorvent.floci.services.ec2.model.Vpc; +import io.github.hectorvent.floci.services.ec2.model.VpcCidrBlockAssociation; +import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; /** - * CloudFormation provisioning for {@code AWS::EC2::VPC}. Extracted verbatim from - * the former CloudFormation monolith as part of the per-service decomposition. + * CloudFormation provisioning for {@code AWS::EC2::VPC}. + * + *
Property and attribute contract follows + * https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html: + * {@code CidrBlock} is create-only and a change replaces the VPC; {@code InstanceTenancy} is + * applied in place only for the {@code dedicated} to {@code default} direction AWS allows, any + * other change replaces; {@code EnableDnsSupport}, {@code EnableDnsHostnames} and {@code Tags} are + * applied in place on every provision. {@code Ref} is the VPC id; {@code Fn::GetAtt} exposes + * VpcId, CidrBlock, CidrBlockAssociations, DefaultNetworkAcl, DefaultSecurityGroup and + * Ipv6CidrBlocks. List-valued attributes are comma-joined like the other provisioners' lists. + * + *
Tags are reconciled to the template's {@code Tags} the way {@link Ec2Tags} does for the + * instance and security-group provisioners: a key the template dropped is deleted. Stack-level + * tags and the {@code aws:cloudformation:*} system tags are not applied here, matching every other + * EC2 provisioner in this package. */ @ApplicationScoped public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { + private static final String DEFAULT_TENANCY = "default"; + private static final String DEDICATED_TENANCY = "dedicated"; + private final Ec2Service ec2Service; @Inject @@ -33,20 +53,53 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { @Override public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + String region = ctx.region(); String cidr = ctx.resolveOptional(props, "CidrBlock"); - Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, ctx.region()); - final Vpc vpc = reconciled != null ? reconciled : ec2Service.createVpc(ctx.region(), cidr, false); - r.setPhysicalId(vpc.getVpcId()); - r.getAttributes().put("VpcId", vpc.getVpcId()); + String tenancy = ctx.resolveOptional(props, "InstanceTenancy"); + String desiredTenancy = tenancy == null || tenancy.isBlank() ? DEFAULT_TENANCY : tenancy; + Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, desiredTenancy, region); + Vpc vpc = reconciled != null + ? reconciled + : ec2Service.createVpc(region, cidr, false, false, desiredTenancy); + String vpcId = vpc.getVpcId(); + if (reconciled != null && isDedicatedToDefault(vpc, desiredTenancy)) { + ec2Service.modifyVpcTenancy(region, vpcId, desiredTenancy); + } + + // AWS defaults for a non-default VPC: DnsSupport on, DnsHostnames off. A template that + // omits the property (or resolves it to AWS::NoValue, which the engine renders blank) gets + // the default, as CloudFormation applies it on every update too. + String dnsSupport = ctx.resolveOrDefault(props, "EnableDnsSupport", "true"); + String dnsHostnames = ctx.resolveOrDefault(props, "EnableDnsHostnames", "false"); + ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport", + String.valueOf(Boolean.parseBoolean(dnsSupport))); + ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames", + String.valueOf(Boolean.parseBoolean(dnsHostnames))); + + Ec2Tags.reconcile(ec2Service, region, vpcId, ctx.resolveTags(props, "Tags")); + + r.setPhysicalId(vpcId); + r.getAttributes().put("VpcId", vpcId); if (vpc.getCidrBlock() != null) { r.getAttributes().put("CidrBlock", vpc.getCidrBlock()); } + r.getAttributes().put("CidrBlockAssociations", vpc.getCidrBlockAssociationSet().stream() + .map(VpcCidrBlockAssociation::getAssociationId) + .collect(Collectors.joining(","))); + r.getAttributes().put("Ipv6CidrBlocks", vpc.getIpv6CidrBlockAssociationSet().stream() + .map(VpcIpv6CidrBlockAssociation::getIpv6CidrBlock) + .collect(Collectors.joining(","))); // Fn::GetAtt DefaultSecurityGroup — CDK's Custom::VpcRestrictDefaultSG handler // depends on it resolving to the VPC's default security group id. - ec2Service.describeSecurityGroups(ctx.region(), List.of(), List.of("default"), Map.of()).stream() - .filter(sg -> vpc.getVpcId().equals(sg.getVpcId())) + ec2Service.describeSecurityGroups(region, List.of(), List.of("default"), Map.of()).stream() + .filter(sg -> vpcId.equals(sg.getVpcId())) .findFirst() .ifPresent(sg -> r.getAttributes().put("DefaultSecurityGroup", sg.getGroupId())); + ec2Service.describeNetworkAcls(region, List.of(), + Map.of("vpc-id", List.of(vpcId), "default", List.of("true"))).stream() + .map(NetworkAcl::getNetworkAclId) + .findFirst() + .ifPresent(aclId -> r.getAttributes().put("DefaultNetworkAcl", aclId)); } /** @@ -55,14 +108,15 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { * unconditionally would mint a fresh VPC id and silently orphan every subnet, route table and * security group that referenced the old one. * - *
Returns {@code null} for a fresh create, for a CidrBlock change (which AWS treats as a - * replacement), or when the VPC is gone from the backend - the caller then creates. + *
Returns {@code null} for a fresh create, for a CidrBlock change or an InstanceTenancy + * change other than {@code dedicated} to {@code default} (which AWS treats as a replacement), + * or when the VPC is gone from the backend - the caller then creates. * *
The prior id is the one the context captured, not the one on the {@link StackResource}:
* {@code provision} assigns the new id onto that resource as it runs, so a resource-derived
* check flips from create to update mid-method.
*/
- private Vpc existingVpcToReconcile(String priorPhysicalId, String cidr, String region) {
+ private Vpc existingVpcToReconcile(String priorPhysicalId, String cidr, String tenancy, String region) {
if (priorPhysicalId == null || priorPhysicalId.isBlank()) {
return null;
}
@@ -78,9 +132,17 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner {
&& !CidrCanonicalizer.sameBlock(cidr, existing.getCidrBlock())) {
return null;
}
+ // ModifyVpcTenancy only goes dedicated -> default; every other tenancy change replaces.
+ if (!tenancy.equals(existing.getInstanceTenancy()) && !isDedicatedToDefault(existing, tenancy)) {
+ return null;
+ }
return existing;
}
+ private static boolean isDedicatedToDefault(Vpc existing, String desiredTenancy) {
+ return DEDICATED_TENANCY.equals(existing.getInstanceTenancy()) && DEFAULT_TENANCY.equals(desiredTenancy);
+ }
+
// No delete override: the switch this replaces had no AWS::EC2::VPC delete arm,
// so stack teardown leaves the VPC alone. Adding one here would change teardown
// behavior beyond the scope of this extraction.
diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
index 67f7f3fa7f..0dc73eced0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java
@@ -1550,7 +1550,7 @@ public class Ec2QueryHandler {
private Response handleCreateVpc(MultivaluedMap> tags(String... expected) {
+ return actual -> actual != null
+ && actual.stream().map(t -> t.getKey() + "=" + t.getValue()).collect(Collectors.toSet())
+ .equals(Set.of(expected));
+ }
+
+ private void stubCreate(Vpc created) {
+ when(ec2.createVpc(anyString(), anyString(), anyBoolean(), anyBoolean(), anyString())).thenReturn(created);
+ }
+
/**
* Provisions the way the engine does: an update arrives with the prior id on both the context
* and the resource, so a provisioner reading the wrong one still looks correct here. The
@@ -82,12 +101,20 @@ class Ec2VpcCfnProvisionerTest {
@Test
void refIsTheVpcIdAndGetAttExposesTheDocumentedAttributes() {
- when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16"));
+ Vpc created = vpc("vpc-new", "10.0.0.0/16");
+ created.getCidrBlockAssociationSet().add(new VpcCidrBlockAssociation("vpc-cidr-assoc-1", "10.0.0.0/16"));
+ stubCreate(created);
SecurityGroup def = new SecurityGroup();
def.setGroupId("sg-default");
def.setVpcId("vpc-new");
when(ec2.describeSecurityGroups(REGION, List.of(), List.of("default"), Map.of()))
.thenReturn(List.of(def));
+ NetworkAcl acl = new NetworkAcl();
+ acl.setNetworkAclId("acl-default");
+ acl.setVpcId("vpc-new");
+ acl.setDefault(true);
+ when(ec2.describeNetworkAcls(REGION, List.of(), Map.of("vpc-id", List.of("vpc-new"), "default", List.of("true"))))
+ .thenReturn(List.of(acl));
StackResource r = provision(null, """
{"CidrBlock": "10.0.0.0/16"}""");
@@ -95,20 +122,69 @@ class Ec2VpcCfnProvisionerTest {
assertEquals("vpc-new", r.getPhysicalId());
assertEquals("vpc-new", r.getAttributes().get("VpcId"));
assertEquals("10.0.0.0/16", r.getAttributes().get("CidrBlock"));
+ assertEquals("vpc-cidr-assoc-1", r.getAttributes().get("CidrBlockAssociations"));
assertEquals("sg-default", r.getAttributes().get("DefaultSecurityGroup"));
+ assertEquals("acl-default", r.getAttributes().get("DefaultNetworkAcl"));
+ assertEquals("", r.getAttributes().get("Ipv6CidrBlocks"));
}
@Test
- void anUnchangedVpcIsReusedInsteadOfCreatedAgain() {
- when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
- .thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
+ void omittedDnsPropertiesApplyTheAwsDefaults() {
+ stubCreate(vpc("vpc-new", "10.0.0.0/16"));
- StackResource r = provision("vpc-existing", """
+ provision(null, """
{"CidrBlock": "10.0.0.0/16"}""");
- verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean());
+ verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "default");
+ verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsSupport", "true");
+ verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsHostnames", "false");
+ }
+
+ @Test
+ void dnsPropertiesResolvingBlankApplyTheAwsDefaults() {
+ // Fn::If with AWS::NoValue renders as "" through the engine; Boolean.parseBoolean("") would
+ // otherwise silently switch DnsSupport off.
+ stubCreate(vpc("vpc-new", "10.0.0.0/16"));
+
+ provision(null, """
+ {"CidrBlock": "10.0.0.0/16", "EnableDnsSupport": "", "EnableDnsHostnames": ""}""");
+
+ verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsSupport", "true");
+ verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsHostnames", "false");
+ }
+
+ @Test
+ void tagsDnsSettingsAndTenancyFromTheTemplateAreApplied() {
+ stubCreate(vpc("vpc-new", "10.0.0.0/16"));
+
+ provision(null, """
+ {"CidrBlock": "10.0.0.0/16", "EnableDnsHostnames": true, "EnableDnsSupport": "true",
+ "InstanceTenancy": "dedicated",
+ "Tags": [{"Key": "Name", "Value": "my-vpc"}, {"Key": "env", "Value": "dev"}]}""");
+
+ verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "dedicated");
+ verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsHostnames", "true");
+ verify(ec2).modifyVpcAttribute(REGION, "vpc-new", "enableDnsSupport", "true");
+ verify(ec2).createTags(eq(REGION), eq(List.of("vpc-new")), argThat(tags("Name=my-vpc", "env=dev")));
+ }
+
+ @Test
+ void anUnchangedVpcIsReusedAndItsTagSetReplaced() {
+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
+ .thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
+ when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing")))).thenReturn(List.of(
+ Map.of("key", "Name", "value", "old"),
+ Map.of("key", "stale", "value", "x")));
+
+ StackResource r = provision("vpc-existing", """
+ {"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "new"}]}""");
+
+ verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean(), anyBoolean(), any());
+ verify(ec2, never()).modifyVpcTenancy(anyString(), anyString(), anyString());
assertEquals("vpc-existing", r.getPhysicalId(),
"reusing must keep the id every subnet and route table already references");
+ verify(ec2).deleteTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("stale=x")));
+ verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=new")));
}
@Test
@@ -142,18 +218,38 @@ class Ec2VpcCfnProvisionerTest {
void aChangedCidrBlockCreatesAReplacement() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
- when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-replaced", "10.1.0.0/16"));
+ stubCreate(vpc("vpc-replaced", "10.1.0.0/16"));
StackResource r = provision("vpc-existing", """
{"CidrBlock": "10.1.0.0/16"}""");
- verify(ec2).createVpc(REGION, "10.1.0.0/16", false);
+ verify(ec2).createVpc(REGION, "10.1.0.0/16", false, false, "default");
assertEquals("vpc-replaced", r.getPhysicalId());
}
+ @Test
+ void tenancyDedicatedToDefaultIsAppliedInPlaceAnyOtherChangeReplaces() {
+ Vpc dedicated = vpc("vpc-existing", "10.0.0.0/16");
+ dedicated.setInstanceTenancy("dedicated");
+ when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(dedicated));
+
+ StackResource kept = provision("vpc-existing", """
+ {"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "default"}""");
+ assertEquals("vpc-existing", kept.getPhysicalId());
+ verify(ec2).modifyVpcTenancy(REGION, "vpc-existing", "default");
+
+ // Now a default VPC asked to become dedicated: the only in-place direction is dedicated->default.
+ dedicated.setInstanceTenancy("default");
+ stubCreate(vpc("vpc-replaced", "10.0.0.0/16"));
+ StackResource replaced = provision("vpc-existing", """
+ {"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "dedicated"}""");
+ assertEquals("vpc-replaced", replaced.getPhysicalId());
+ verify(ec2).createVpc(eq(REGION), eq("10.0.0.0/16"), eq(false), eq(false), eq("dedicated"));
+ }
+
@Test
void anIdOnTheResourceAloneDoesNotCountAsAnUpdate() {
- when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-new", "10.0.0.0/16"));
+ stubCreate(vpc("vpc-new", "10.0.0.0/16"));
// A resource carrying a physical id under a create context: what provision() itself
// produces the moment it assigns the new id. Reading create-vs-update off the resource
@@ -162,7 +258,7 @@ class Ec2VpcCfnProvisionerTest {
{"CidrBlock": "10.0.0.0/16"}""");
verify(ec2, never()).describeVpcs(anyString(), any(), any());
- verify(ec2).createVpc(REGION, "10.0.0.0/16", false);
+ verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "default");
assertEquals("vpc-new", r.getPhysicalId());
}
@@ -170,12 +266,12 @@ class Ec2VpcCfnProvisionerTest {
void aVpcDeletedOutOfBandFallsBackToCreate() {
when(ec2.describeVpcs(REGION, List.of("vpc-gone"), Map.of()))
.thenReturn(List.of());
- when(ec2.createVpc(anyString(), anyString(), anyBoolean())).thenReturn(vpc("vpc-fresh", "10.0.0.0/16"));
+ stubCreate(vpc("vpc-fresh", "10.0.0.0/16"));
StackResource r = provision("vpc-gone", """
{"CidrBlock": "10.0.0.0/16"}""");
- verify(ec2).createVpc(REGION, "10.0.0.0/16", false);
+ verify(ec2).createVpc(REGION, "10.0.0.0/16", false, false, "default");
assertEquals("vpc-fresh", r.getPhysicalId());
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateVpcInstanceTenancyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateVpcInstanceTenancyIntegrationTest.java
new file mode 100644
index 0000000000..b06aa3949a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2CreateVpcInstanceTenancyIntegrationTest.java
@@ -0,0 +1,75 @@
+package io.github.hectorvent.floci.services.ec2;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * CreateVpc's InstanceTenancy on the Query API: {@code default} or {@code dedicated} is stored and
+ * read back by DescribeVpcs; omitting it means {@code default}; {@code host} is refused, as the
+ * EC2 reference says ("The host value cannot be used with this parameter").
+ */
+@QuarkusTest
+class Ec2CreateVpcInstanceTenancyIntegrationTest {
+
+ private final List