mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): provision AWS::EC2::LaunchTemplate (#1973)
* feat(cloudformation): provision AWS::EC2::LaunchTemplate Create the launch template in Ec2Service from LaunchTemplateData (ImageId, InstanceType, KeyName, SecurityGroupIds, UserData, IamInstanceProfile). Ref resolves to the launch template id and Fn::GetAtt exposes LatestVersionNumber/DefaultVersionNumber, which CDK ASGs and instances reference. DeleteStack removes the template. Fixes #1971 * feat(cloudformation): resolve EC2 instance config from its LaunchTemplate reference An AWS::EC2::Instance that sets LaunchTemplate instead of direct properties now fills ImageId/InstanceType/KeyName from the referenced template's data (AWS resolution order), so instances launched from a launch template no longer fail with 'The request must contain the parameter ImageId'. * refactor(cloudformation): move AWS::EC2::LaunchTemplate into a per-service provisioner Follows the CfnResourceProvisioner pattern instead of growing the monolithic switch: Ec2LaunchTemplateCfnProvisioner injects only Ec2Service and is picked up by CloudFormationResourceRegistry via CDI. Provision and delete arms for AWS::EC2::LaunchTemplate are removed from CloudFormationResourceProvisioner along with the now-unused private provisionLaunchTemplate method. EC2 instance resolution against a referenced launch template stays put, since AWS::EC2::Instance is not extracted yet. An IamInstanceProfile given only by Name is now normalized to its instance-profile ARN, matching the EC2 query API path; previously the bare name was stored as if it were an ARN. Adds unit coverage for the new provisioner (attributes, generated name, profile ARN normalization, security groups, delete). * test(cloudformation): delete the launch-template instance stack so EC2 state stays clean The instance case left its stack standing, so a running instance (and its network interface) leaked into the shared emulator state for the rest of the suite. That pushed the total interface count past the MaxResults=5 boundary Ec2IntegrationTest's DescribeNetworkInterfaces pagination cases assert on, and they failed in full-suite runs while passing in isolation. Deleting the stack terminates the instance, which describeNetworkInterfaces skips. * fix(cloudformation): update a launch template in place instead of recreating it UpdateStack re-provisions every resource, and the provisioner called createLaunchTemplate unconditionally. An explicit LaunchTemplateName therefore hit InvalidLaunchTemplateName.AlreadyExistsException on every update, and an omitted one generated a fresh random name, creating a second template and orphaning the first. A template whose name has not changed is now updated by publishing a new version and keeping its physical id, which is how AWS::EC2::LaunchTemplate behaves when only its LaunchTemplateData changes. An unnamed template keeps the name generated at create time rather than minting a new one. A changed name is a replacement: the new template is created first and the previous one deleted only after that succeeds.
This commit is contained in:
1 parent
1a99721ae0
commit
4e0a815f20
4 files changed
+546
-1
No files matched your search
+180
@@ -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("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<OutputValue>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("<StackStatus>CREATE_COMPLETE</StackStatus>"))
|
||||
.body(containsString("<OutputValue>lt-"))
|
||||
.body(containsString("<OutputValue>1</OutputValue>"));
|
||||
|
||||
// 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)));
|
||||
}
|
||||
}
|
||||
+211
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user