Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision EC2 instances (#1366)

Hector Venturafeae42166666
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index 1e0d550fb7..d768184f10 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.dynamodb.model.TableDefinition;
import io.github.hectorvent.floci.services.ecr.EcrService;
import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
+import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
@@ -286,6 +287,7 @@ public class CloudFormationResourceProvisioner {
case "AWS::EC2::Route" -> provisionRoute(resource, properties, engine, region);
case "AWS::EC2::NatGateway" -> provisionNatGateway(resource, properties, engine, region);
case "AWS::EC2::EIP" -> provisionEip(resource, region);
+ case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region);
default -> {
if (resourceType != null && resourceType.startsWith("Custom::")) {
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
@@ -357,6 +359,7 @@ public class CloudFormationResourceProvisioner {
case "AWS::ElasticLoadBalancingV2::TargetGroup" -> elbV2Service.deleteTargetGroup(region, physicalId);
case "AWS::ElasticLoadBalancingV2::Listener" -> elbV2Service.deleteListener(region, physicalId);
case "AWS::ElasticLoadBalancingV2::ListenerRule" -> elbV2Service.deleteRule(region, physicalId);
+ case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
}
} catch (Exception e) {
@@ -504,6 +507,57 @@ public class CloudFormationResourceProvisioner {
r.getAttributes().put("PublicIp", addr.getPublicIp());
}
+ private void provisionEc2Instance(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
+ String region) {
+ String imageId = resolveOptional(props, "ImageId", engine);
+ String instanceType = resolveOptional(props, "InstanceType", engine);
+ if (instanceType == null || instanceType.isBlank()) {
+ instanceType = "t3.micro";
+ }
+ String keyName = resolveOptional(props, "KeyName", engine);
+ String subnetId = resolveOptional(props, "SubnetId", engine);
+ String userData = resolveOptional(props, "UserData", engine);
+ String iamInstanceProfile = resolveOptional(props, "IamInstanceProfile", engine);
+
+ List<String> securityGroupIds = new ArrayList<>();
+ if (props != null && props.has("SecurityGroupIds") && props.get("SecurityGroupIds").isArray()) {
+ for (JsonNode sg : props.get("SecurityGroupIds")) {
+ securityGroupIds.add(engine.resolve(sg));
+ }
+ }
+
+ List<Tag> tags = new ArrayList<>();
+ if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
+ for (JsonNode tag : props.get("Tags")) {
+ String key = engine.resolve(tag.path("Key"));
+ if (!key.isEmpty()) {
+ tags.add(new Tag(key, engine.resolve(tag.path("Value"))));
+ }
+ }
+ }
+
+ var reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName,
+ securityGroupIds, subnetId, null, tags, userData, iamInstanceProfile);
+ var instance = reservation.getInstances().get(0);
+ r.setPhysicalId(instance.getInstanceId());
+ r.getAttributes().put("InstanceId", instance.getInstanceId());
+ if (instance.getPrivateIpAddress() != null) {
+ r.getAttributes().put("PrivateIp", instance.getPrivateIpAddress());
+ }
+ if (instance.getPublicIpAddress() != null) {
+ r.getAttributes().put("PublicIp", instance.getPublicIpAddress());
+ }
+ if (instance.getPrivateDnsName() != null) {
+ r.getAttributes().put("PrivateDnsName", instance.getPrivateDnsName());
+ }
+ if (instance.getPublicDnsName() != null) {
+ r.getAttributes().put("PublicDnsName", instance.getPublicDnsName());
+ }
+ if (instance.getPlacement() != null && instance.getPlacement().getAvailabilityZone() != null) {
+ r.getAttributes().put("AvailabilityZone", instance.getPlacement().getAvailabilityZone());
+ }
+ }
+
// ── SNS ───────────────────────────────────────────────────────────────────
private void provisionSnsTopic(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java
new file mode 100644
index 0000000000..08cb32bec1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java
@@ -0,0 +1,86 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * End-to-end check that CloudFormation provisions a real EC2 instance (into Ec2Service) rather than
+ * stubbing it, so the exported instance id is visible to describe-instances. EC2 instances are
+ * emulated as metadata (no container), so this stays Docker-free. Isolated to ap-southeast-2 so it
+ * doesn't pollute the shared in-memory Ec2Service state asserted by us-east-1 EC2 tests.
+ */
+@QuarkusTest
+class CloudFormationEc2InstanceIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/ap-southeast-2/cloudformation/aws4_request";
+ private static final String EC2_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/ap-southeast-2/ec2/aws4_request";
+
+ @Test
+ void createStackProvisionsRealEc2Instance() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-ec2-instance-" + suffix;
+
+ String template = """
+ {
+ "Resources": {
+ "Server": {
+ "Type": "AWS::EC2::Instance",
+ "Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}
+ }
+ },
+ "Outputs": {
+ "InstanceId": {"Value": {"Ref": "Server"}}
+ }
+ }
+ """;
+
+ 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();
+
+ // Ref(Server) exports a real instance id (i-...), not the stub shape.
+ Matcher m = Pattern.compile("<OutputValue>(i-[0-9a-fA-F]+)</OutputValue>").matcher(describeStacks);
+ assertTrue(m.find(), "expected an instance id in the stack outputs");
+ String instanceId = m.group(1);
+
+ // The instance really exists in EC2.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", EC2_AUTH)
+ .formParam("Action", "DescribeInstances")
+ .formParam("InstanceId.1", instanceId)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString(instanceId));
+ }
+}