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 952a1e651e..31e14c1000 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 @@ -934,10 +934,34 @@ public class CloudFormationResourceProvisioner { String region) { String imageId = resolveOptional(props, "ImageId", engine); String instanceType = resolveOptional(props, "InstanceType", engine); + String keyName = resolveOptional(props, "KeyName", engine); + + // An instance may reference a LaunchTemplate for its config; fields the + // properties don't set resolve from the template's data, as on AWS. + if (props != null && props.has("LaunchTemplate")) { + JsonNode ltRef = engine.resolveNode(props.get("LaunchTemplate")); + try { + var ltData = ec2Service.resolveLaunchTemplateData(region, + ltRef.path("LaunchTemplateId").asText(null), + ltRef.path("LaunchTemplateName").asText(null), + ltRef.path("Version").asText(null)); + if (imageId == null || imageId.isBlank()) { + imageId = ltData.getImageId(); + } + if (instanceType == null || instanceType.isBlank()) { + instanceType = ltData.getInstanceType(); + } + if (keyName == null || keyName.isBlank()) { + keyName = ltData.getKeyName(); + } + } catch (Exception e) { + LOG.debugv("Could not resolve launch template for instance {0}: {1}", + r.getLogicalId(), e.getMessage()); + } + } 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisioner.java new file mode 100644 index 0000000000..222aa27be8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisioner.java @@ -0,0 +1,130 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +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.LaunchTemplate; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * CloudFormation provisioning for {@code AWS::EC2::LaunchTemplate} (issue #1971). + */ +@ApplicationScoped +public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner { + + private final Ec2Service ec2Service; + + @Inject + public Ec2LaunchTemplateCfnProvisioner(Ec2Service ec2Service) { + this.ec2Service = ec2Service; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::EC2::LaunchTemplate"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + String previousId = r.getPhysicalId(); + LaunchTemplate existing = previousId == null ? null : findExisting(ctx.region(), previousId); + String declaredName = ctx.resolveOptional(props, "LaunchTemplateName"); + String name; + if (declaredName != null && !declaredName.isBlank()) { + name = declaredName; + } else if (existing != null) { + // Keep the name generated at create time; generating a fresh one on every update is + // what made an unnamed template multiply. + name = existing.getLaunchTemplateName(); + } else { + name = ctx.generatePhysicalName(r.getLogicalId(), 128, false); + } + String imageId = null; + String instanceType = null; + String keyName = null; + String encodedUserData = null; + String iamInstanceProfileArn = null; + List securityGroupIds = null; + if (props != null && props.has("LaunchTemplateData")) { + JsonNode data = ctx.engine().resolveNode(props.get("LaunchTemplateData")); + imageId = data.path("ImageId").asText(null); + instanceType = data.path("InstanceType").asText(null); + keyName = data.path("KeyName").asText(null); + // CFN carries UserData already base64-encoded. + encodedUserData = data.path("UserData").asText(null); + iamInstanceProfileArn = resolveIamInstanceProfileArn(data.path("IamInstanceProfile"), ctx); + if (data.has("SecurityGroupIds")) { + securityGroupIds = new ArrayList<>(); + for (JsonNode sg : data.get("SecurityGroupIds")) { + securityGroupIds.add(sg.asText()); + } + } + } + // UpdateStack re-provisions every resource. Creating unconditionally meant an explicit + // LaunchTemplateName hit InvalidLaunchTemplateName.AlreadyExistsException, while an + // omitted one minted a second randomly named template and orphaned the first. A template + // whose name has not changed is updated in place by publishing a new version, which is how + // AWS::EC2::LaunchTemplate behaves when only its LaunchTemplateData changes. + LaunchTemplate lt; + if (existing != null && name.equals(existing.getLaunchTemplateName())) { + lt = ec2Service.createLaunchTemplateVersion(ctx.region(), previousId, null, null, + imageId, instanceType, keyName, securityGroupIds, null, encodedUserData, + iamInstanceProfileArn, null); + } else { + lt = ec2Service.createLaunchTemplate(ctx.region(), name, imageId, instanceType, keyName, + securityGroupIds, null, encodedUserData, iamInstanceProfileArn, null, null); + // A changed name is a replacement: drop the template the previous execution created, + // once the new one exists, so the old one is not left behind. + if (existing != null) { + try { + ec2Service.deleteLaunchTemplate(ctx.region(), previousId, null); + } catch (RuntimeException ignored) { + // already gone — nothing to clean up + } + } + } + r.setPhysicalId(lt.getLaunchTemplateId()); + r.getAttributes().put("LaunchTemplateId", lt.getLaunchTemplateId()); + r.getAttributes().put("LatestVersionNumber", lt.getLatestVersionNumber()); + r.getAttributes().put("DefaultVersionNumber", lt.getDefaultVersionNumber()); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + ec2Service.deleteLaunchTemplate(region, physicalId, null); + } + + /** The template a previous execution created, or null when it is gone. */ + private LaunchTemplate findExisting(String region, String launchTemplateId) { + try { + return ec2Service.describeLaunchTemplates(region, List.of(launchTemplateId), List.of(), Map.of()) + .stream().findFirst().orElse(null); + } catch (RuntimeException e) { + return null; + } + } + + /** + * A profile given only by {@code Name} is normalized to its instance-profile ARN, matching + * what the EC2 query API does for {@code IamInstanceProfile.Name} request parameters + * (see {@code Ec2QueryHandler#resolveIamInstanceProfileArn}). + */ + private String resolveIamInstanceProfileArn(JsonNode profile, ProvisionContext ctx) { + String arn = profile.path("Arn").asText(null); + if (arn != null && !arn.isBlank()) { + return arn; + } + String profileName = profile.path("Name").asText(null); + if (profileName == null || profileName.isBlank()) { + return null; + } + return AwsArnUtils.Arn.of("iam", "", ctx.accountId(), "instance-profile/" + profileName).toString(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLaunchTemplateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLaunchTemplateIntegrationTest.java new file mode 100644 index 0000000000..515e475f3c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLaunchTemplateIntegrationTest.java @@ -0,0 +1,180 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +/** + * End-to-end check that CloudFormation provisions AWS::EC2::LaunchTemplate for real + * (issue #1971): the template exists in Ec2Service, Ref resolves to the launch template + * id, Fn::GetAtt LatestVersionNumber resolves, and DeleteStack removes it. Metadata-only, + * so the test is Docker-free. + */ +@QuarkusTest +class CloudFormationLaunchTemplateIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; + private static final String EC2_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request"; + + @Test + void ec2InstanceResolvesImageAndTypeFromLaunchTemplate() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-lt-inst-stack-" + suffix; + + String template = """ + { + "Resources": { + "Lt": { + "Type": "AWS::EC2::LaunchTemplate", + "Properties": { + "LaunchTemplateData": { + "ImageId": "ami-87654321", + "InstanceType": "t3.small" + } + } + }, + "Inst": { + "Type": "AWS::EC2::Instance", + "Properties": { + "LaunchTemplate": { + "LaunchTemplateId": {"Ref": "Lt"}, + "Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]} + } + } + } + }, + "Outputs": { + "InstanceId": {"Value": {"Ref": "Inst"}} + } + } + """; + + 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); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString("i-")); + + // Delete the stack so the instance is terminated: a live instance would otherwise leak + // into the shared emulator state and change what EC2 describe calls in other tests see. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + void createStackProvisionsLaunchTemplateWithVersionAttributes() { + String suffix = Long.toString(System.nanoTime(), 36); + String templateName = "cfn-lt-" + suffix; + String stackName = "cfn-lt-stack-" + suffix; + + String template = """ + { + "Resources": { + "AppLaunchTemplate": { + "Type": "AWS::EC2::LaunchTemplate", + "Properties": { + "LaunchTemplateName": "%s", + "LaunchTemplateData": { + "ImageId": "ami-12345678", + "InstanceType": "t3.micro", + "UserData": "IyEvYmluL2Jhc2gKZWNobyBoaQo=" + } + } + } + }, + "Outputs": { + "TemplateId": {"Value": {"Ref": "AppLaunchTemplate"}}, + "LatestVersion": {"Value": {"Fn::GetAtt": ["AppLaunchTemplate", "LatestVersionNumber"]}} + } + } + """.formatted(templateName); + + 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); + + // Stack completes, Ref resolves to a launch template id, GetAtt resolves the version. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString("lt-")) + .body(containsString("1")); + + // The launch template is real: EC2 DescribeLaunchTemplates finds it by name. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", EC2_AUTH) + .formParam("Action", "DescribeLaunchTemplates") + .formParam("LaunchTemplateName.1", templateName) + .formParam("Version", "2016-11-15") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString(templateName)); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", EC2_AUTH) + .formParam("Action", "DescribeLaunchTemplates") + .formParam("Version", "2016-11-15") + .when() + .post("/") + .then() + .statusCode(200) + .body(not(containsString(templateName))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisionerTest.java new file mode 100644 index 0000000000..951c0f23a0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2LaunchTemplateCfnProvisionerTest.java @@ -0,0 +1,211 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +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.LaunchTemplate; +import org.junit.jupiter.api.Test; +import org.mockito.InOrder; + +import java.util.HashMap; +import java.util.List; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * The launch-template CFN provisioner in isolation, mocking only Ec2Service. + */ +class Ec2LaunchTemplateCfnProvisionerTest { + + private final Ec2Service ec2 = mock(Ec2Service.class); + private final Ec2LaunchTemplateCfnProvisioner provisioner = new Ec2LaunchTemplateCfnProvisioner(ec2); + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx() { + // Scalar/tree resolution is identity here; intrinsics are the engine's own concern. + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + } + + private StackResource resource(String logicalId) { + StackResource r = new StackResource(); + r.setLogicalId(logicalId); + r.setResourceType("AWS::EC2::LaunchTemplate"); + r.setAttributes(new HashMap<>()); + return r; + } + + private LaunchTemplate template(String id) { + LaunchTemplate lt = new LaunchTemplate(); + lt.setLaunchTemplateId(id); + return lt; + } + + @Test + void setsPhysicalIdAndGetAttAttributes() { + when(ec2.createLaunchTemplate(eq("us-east-1"), eq("my-lt"), eq("ami-12345678"), + eq("t3.small"), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull())) + .thenReturn(template("lt-abc123")); + ObjectNode data = mapper.createObjectNode() + .put("ImageId", "ami-12345678") + .put("InstanceType", "t3.small"); + ObjectNode props = mapper.createObjectNode().put("LaunchTemplateName", "my-lt"); + props.set("LaunchTemplateData", data); + StackResource r = resource("Lt"); + + provisioner.provision(r, props, ctx()); + + assertEquals("lt-abc123", r.getPhysicalId()); + assertEquals("lt-abc123", r.getAttributes().get("LaunchTemplateId")); + assertEquals("1", r.getAttributes().get("LatestVersionNumber")); + assertEquals("1", r.getAttributes().get("DefaultVersionNumber")); + } + + @Test + void withoutNameGeneratesPhysicalName() { + when(ec2.createLaunchTemplate(eq("us-east-1"), anyString(), any(), any(), any(), + any(), any(), any(), any(), any(), any())) + .thenReturn(template("lt-gen")); + StackResource r = resource("Lt"); + + provisioner.provision(r, mapper.createObjectNode(), ctx()); + + verify(ec2).createLaunchTemplate(eq("us-east-1"), + org.mockito.ArgumentMatchers.matches("my-stack-Lt-[0-9a-f]{12}"), + isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull()); + } + + @Test + void updateWithTheSameNamePublishesAVersionInsteadOfANewTemplate() { + // Creating unconditionally hit InvalidLaunchTemplateName.AlreadyExistsException for an + // explicitly named template. + LaunchTemplate existing = template("lt-abc123"); + existing.setLaunchTemplateName("my-lt"); + when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-abc123")), eq(List.of()), any())) + .thenReturn(List.of(existing)); + when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-abc123"), isNull(), isNull(), + eq("ami-updated"), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(template("lt-abc123")); + + ObjectNode props = mapper.createObjectNode().put("LaunchTemplateName", "my-lt"); + props.set("LaunchTemplateData", mapper.createObjectNode().put("ImageId", "ami-updated")); + StackResource r = resource("Lt"); + r.setPhysicalId("lt-abc123"); + + provisioner.provision(r, props, ctx()); + + assertEquals("lt-abc123", r.getPhysicalId()); + verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any()); + verify(ec2, never()).deleteLaunchTemplate(any(), any(), any()); + } + + @Test + void updateOfAnUnnamedTemplateKeepsItsGeneratedName() { + // Regenerating the name on every update minted a second template and orphaned the first. + LaunchTemplate existing = template("lt-gen"); + existing.setLaunchTemplateName("my-stack-Lt-0123456789ab"); + when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-gen")), eq(List.of()), any())) + .thenReturn(List.of(existing)); + when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-gen"), isNull(), isNull(), + any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(template("lt-gen")); + + StackResource r = resource("Lt"); + r.setPhysicalId("lt-gen"); + + provisioner.provision(r, mapper.createObjectNode(), ctx()); + + assertEquals("lt-gen", r.getPhysicalId()); + verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any()); + } + + @Test + void renamingReplacesTheTemplateAndRemovesTheOldOne() { + LaunchTemplate existing = template("lt-old"); + existing.setLaunchTemplateName("old-name"); + when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-old")), eq(List.of()), any())) + .thenReturn(List.of(existing)); + when(ec2.createLaunchTemplate(eq("us-east-1"), eq("new-name"), any(), any(), any(), + any(), any(), any(), any(), any(), any())) + .thenReturn(template("lt-new")); + + StackResource r = resource("Lt"); + r.setPhysicalId("lt-old"); + + provisioner.provision(r, mapper.createObjectNode().put("LaunchTemplateName", "new-name"), ctx()); + + assertEquals("lt-new", r.getPhysicalId()); + // Created before the old one is dropped, so a failed create leaves the original intact. + InOrder order = inOrder(ec2); + order.verify(ec2).createLaunchTemplate(eq("us-east-1"), eq("new-name"), any(), any(), any(), + any(), any(), any(), any(), any(), any()); + order.verify(ec2).deleteLaunchTemplate("us-east-1", "lt-old", null); + } + + @Test + void profileNameIsNormalizedToInstanceProfileArn() { + when(ec2.createLaunchTemplate(any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any())) + .thenReturn(template("lt-prof")); + ObjectNode data = mapper.createObjectNode(); + data.putObject("IamInstanceProfile").put("Name", "my-profile"); + ObjectNode props = mapper.createObjectNode(); + props.set("LaunchTemplateData", data); + + provisioner.provision(resource("Lt"), props, ctx()); + + verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), isNull(), isNull(), isNull(), + isNull(), isNull(), isNull(), + eq("arn:aws:iam::000000000000:instance-profile/my-profile"), isNull(), isNull()); + } + + @Test + void profileArnIsPassedThrough() { + when(ec2.createLaunchTemplate(any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any())) + .thenReturn(template("lt-prof")); + ObjectNode data = mapper.createObjectNode(); + data.putObject("IamInstanceProfile") + .put("Arn", "arn:aws:iam::000000000000:instance-profile/explicit"); + data.putArray("SecurityGroupIds").add("sg-1").add("sg-2"); + ObjectNode props = mapper.createObjectNode(); + props.set("LaunchTemplateData", data); + + provisioner.provision(resource("Lt"), props, ctx()); + + verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), isNull(), isNull(), isNull(), + eq(List.of("sg-1", "sg-2")), isNull(), isNull(), + eq("arn:aws:iam::000000000000:instance-profile/explicit"), isNull(), isNull()); + } + + @Test + void deleteDelegatesToServiceById() { + provisioner.delete("AWS::EC2::LaunchTemplate", "lt-abc123", "us-east-1"); + verify(ec2).deleteLaunchTemplate("us-east-1", "lt-abc123", null); + } + + @Test + void handlesOnlyLaunchTemplate() { + assertEquals(Set.of("AWS::EC2::LaunchTemplate"), provisioner.resourceTypes()); + } +}