fix(ec2): round-trip launch template data instead of discarding it (#2595)

* fix(ec2): round-trip launch template data instead of discarding it

CreateLaunchTemplate returned 200 and kept only ImageId, InstanceType,
KeyName, UserData, IamInstanceProfile, SecurityGroupIds and
TagSpecifications. Every other member of RequestLaunchTemplateData was
dropped without a word, so Terraform read back its own input missing and
reported "Provider produced inconsistent result after apply", or diffed
forever. MetadataOptions with HttpTokens=required (IMDSv2) and
BlockDeviceMappings appear in most Gruntwork ASG and ECS modules.

The AWS EC2 service model is the reference for what is stored and for the
element names it is read back under: request parameter names are the ones
botocore's EC2 serializer emits (note the singular BlockDeviceMapping.N
and NetworkInterface.N list prefixes, taken from each list member's
locationName), and response elements use ResponseLaunchTemplateData's
locationNames.

Stored and read back unchanged: ImageId, InstanceType, KeyName, UserData,
KernelId, RamDiskId, SecurityGroupIds, IamInstanceProfile,
BlockDeviceMappings, NetworkInterfaces, TagSpecifications, MetadataOptions,
Monitoring, Placement, CpuOptions, CreditSpecification, EnclaveOptions,
HibernationOptions, MaintenanceOptions, PrivateDnsNameOptions,
CapacityReservationSpecification, EbsOptimized, DisableApiTermination,
DisableApiStop, InstanceInitiatedShutdownBehavior.

Two further contradictions in the same call, both fixed:

- IamInstanceProfile keeps the form it was given. A profile submitted as
  Name reads back as Name rather than being rewritten to an Arn, so
  aws_launch_template.iam_instance_profile.name converges. The
  instance-profile ARN is derived at launch time instead.
- NetworkInterfaces survives as a NetworkInterfaces block. Its Groups are
  no longer hoisted into top-level SecurityGroupIds; on AWS the two are
  mutually exclusive, and the promotion made the block vanish from state.
  A launch resolves security groups from whichever of the two is set.

Deliberately out of scope, accepted and ignored rather than rejected:
InstanceMarketOptions, InstanceRequirements, LicenseSpecifications,
ElasticGpuSpecifications, ElasticInferenceAccelerators,
NetworkPerformanceOptions, Operator, SecondaryInterfaces, and
SecurityGroups (groups by name). Within NetworkInterfaces the IPv4/IPv6
address and prefix lists, EnaSrdSpecification,
ConnectionTrackingSpecification, PrimaryIpv6 and EnaQueueCount are also
ignored. A focused subset that round-trips beats a broad partial one.

LaunchTemplate no longer mirrors launch data in flat fields alongside its
version map; it holds one LaunchTemplateData, which removes the
dataFrom/applyData sync and collapses two 11-argument service methods into
a parameter object with explicit merge semantics for version creation.

Fixes a compatibility defect this collapse introduced (flagged by review):
a template persisted before this change stored the IAM instance profile as
a bare iamInstanceProfileArn string and instance tags as a flat
instanceTags list, both directly on LaunchTemplate and, separately, inside
each entry of its versions map. Neither key exists on the new model, so
ignoreUnknown silently dropped both on load - an upgrade would launch from
an existing template with no IAM profile and no instance tags, with
nothing in the logs to say so.

Legacy @JsonSetters on LaunchTemplateData and LaunchTemplate map both old
keys onto the new shape at load time, covering the versions-map entry (the
path DescribeLaunchTemplateVersions and AutoScaling actually read) and the
top-level fields (the path a template with no versions map falls back to).
Deserialize-only, so a file saved by the current code never regains the
old shape. Ec2ServicePersistenceTest#legacyIamProfileAndInstanceTagsSurviveRestart
seeds a hand-built pre-migration ec2-launch-templates.json and asserts both
paths survive a restart; reverting the two model changes alone fails it.

* fix(ec2): correct SourceVersion inheritance and round-trip VersionDescription

Addresses review feedback on the prior commit:

- CreateLaunchTemplateVersion with SourceVersion omitted merged onto the
  latest version instead of following the AWS-documented "no source
  specified, no inheritance" behavior. A version created without
  SourceVersion now starts from an empty LaunchTemplateData, populated
  only by whatever fields the request itself supplies.
- VersionDescription was accepted and silently dropped. It is a
  version-level field on LaunchTemplateVersion, not a member of
  RequestLaunchTemplateData, so it is tracked in a parallel per-version
  map on LaunchTemplate (alongside VersionNumber, CreateTime) rather than
  inside LaunchTemplateData, and round-trips through
  DescribeLaunchTemplateVersions. CreateLaunchTemplate accepts the same
  field for the initial version.
- SecurityGroups (security groups by name) stays out of scope: resolving
  names to IDs would need lookup machinery - store scan, not-found
  handling, ambiguity across VPCs - that no other EC2 action here has
  either (RunInstances itself only accepts SecurityGroupId). Documented
  the reasoning in both the code and docs/services/ec2.md so the ignored
  list stays accurate now that SourceVersion and VersionDescription are
  handled correctly.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-08-28 11:08:52 -04:00
1 parent 2963601f69
commit f1ad306599
15 files changed
+1843 -313

No files matched your search

@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
@@ -101,12 +102,16 @@ class AutoScalingReconcilerTest {
launchTemplate.setLaunchTemplateId("lt-123");
LaunchTemplate version = new LaunchTemplate();
version.setLatestVersionNumber("1");
version.setImageId("ami-version-1");
version.setInstanceType("t3.micro");
version.setIamInstanceProfileArn("arn:aws:iam::000000000000:instance-profile/app-profile");
version.getData().setImageId("ami-version-1");
version.getData().setInstanceType("t3.micro");
version.getData().setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(
"arn:aws:iam::000000000000:instance-profile/app-profile", null));
when(ec2Service.iamInstanceProfileArn(version.getData()))
.thenReturn("arn:aws:iam::000000000000:instance-profile/app-profile");
List<Tag> instanceTags = List.of(new Tag("app.ClusterId", "development"));
List<Tag> propagatedTags = List.of(new Tag("app.ClusterId", "development"), new Tag("job-id", "2001"));
version.setInstanceTags(instanceTags);
version.getData().setTagSpecifications(List.of(
new LaunchTemplateData.TagSpecification("instance", instanceTags)));
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
.thenReturn(List.of(launchTemplate));
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("1")))
@@ -198,8 +203,8 @@ class AutoScalingReconcilerTest {
launchTemplate.setLaunchTemplateId("lt-123");
LaunchTemplate version = new LaunchTemplate();
version.setLatestVersionNumber("7");
version.setImageId("ami-version-7");
version.setInstanceType("t3.micro");
version.getData().setImageId("ami-version-7");
version.getData().setInstanceType("t3.micro");
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
.thenReturn(List.of(launchTemplate));
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("$Latest")))
@@ -247,8 +252,8 @@ class AutoScalingReconcilerTest {
launchTemplate.setLaunchTemplateId("lt-123");
LaunchTemplate version = new LaunchTemplate();
version.setLatestVersionNumber("3");
version.setImageId("ami-version-3");
version.setInstanceType("t3.micro");
version.getData().setImageId("ami-version-3");
version.getData().setInstanceType("t3.micro");
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
.thenReturn(List.of(launchTemplate));
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("3")))
@@ -98,7 +98,7 @@ class AutoScalingServiceTest {
Ec2Service ec2Service = mock(Ec2Service.class);
service.ec2Service = ec2Service;
LaunchTemplate version = new LaunchTemplate();
version.setImageId(null);
version.getData().setImageId(null);
when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-no-image", null, List.of("1")))
.thenReturn(List.of(version));
@@ -242,7 +242,7 @@ class AutoScalingServiceTest {
Ec2Service ec2Service = mock(Ec2Service.class);
service.ec2Service = ec2Service;
LaunchTemplate version = new LaunchTemplate();
version.setImageId("");
version.getData().setImageId("");
when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-no-image", null, List.of("2")))
.thenReturn(List.of(version));
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
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 io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
@@ -15,7 +17,9 @@ import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.anyString;
@@ -61,8 +65,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
@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()))
when(ec2.createLaunchTemplate(eq("us-east-1"), eq("my-lt"), any(), any()))
.thenReturn(template("lt-abc123"));
ObjectNode data = mapper.createObjectNode()
.put("ImageId", "ami-12345678")
@@ -81,16 +84,14 @@ class Ec2LaunchTemplateCfnProvisionerTest {
@Test
void withoutNameGeneratesPhysicalName() {
when(ec2.createLaunchTemplate(eq("us-east-1"), anyString(), any(), any(), any(),
any(), any(), any(), any(), any(), any()))
when(ec2.createLaunchTemplate(eq("us-east-1"), anyString(), 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());
org.mockito.ArgumentMatchers.matches("my-stack-Lt-[0-9a-f]{12}"), any(), isNull());
}
@Test
@@ -102,7 +103,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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()))
argThat(d -> d != null && "ami-updated".equals(d.getImageId()))))
.thenReturn(template("lt-abc123"));
ObjectNode props = mapper.createObjectNode().put("LaunchTemplateName", "my-lt");
@@ -113,8 +114,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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()).createLaunchTemplate(any(), any(), any(), any());
verify(ec2, never()).deleteLaunchTemplate(any(), any(), any());
}
@@ -125,8 +125,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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()))
when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-gen"), isNull(), isNull(), any()))
.thenReturn(template("lt-gen"));
StackResource r = resource("Lt");
@@ -135,8 +134,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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());
verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any());
}
@Test
@@ -145,8 +143,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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()))
when(ec2.createLaunchTemplate(eq("us-east-1"), eq("new-name"), any(), any()))
.thenReturn(template("lt-new"));
StackResource r = resource("Lt");
@@ -157,16 +154,16 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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).createLaunchTemplate(eq("us-east-1"), eq("new-name"), 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"));
void profileGivenOnlyByNameKeepsThatForm() {
// Normalizing Name into an Arn here is what made
// aws_launch_template.iam_instance_profile.name never converge: Terraform sets .name and
// read back .arn. EC2 derives the ARN at launch time instead.
when(ec2.createLaunchTemplate(any(), any(), any(), any())).thenReturn(template("lt-prof"));
ObjectNode data = mapper.createObjectNode();
data.putObject("IamInstanceProfile").put("Name", "my-profile");
ObjectNode props = mapper.createObjectNode();
@@ -174,16 +171,15 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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());
ArgumentCaptor<LaunchTemplateData> captor = ArgumentCaptor.forClass(LaunchTemplateData.class);
verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), captor.capture(), isNull());
assertEquals("my-profile", captor.getValue().getIamInstanceProfile().getName());
assertNull(captor.getValue().getIamInstanceProfile().getArn());
}
@Test
void profileArnIsPassedThrough() {
when(ec2.createLaunchTemplate(any(), any(), any(), any(), any(),
any(), any(), any(), any(), any(), any()))
.thenReturn(template("lt-prof"));
when(ec2.createLaunchTemplate(any(), any(), any(), any())).thenReturn(template("lt-prof"));
ObjectNode data = mapper.createObjectNode();
data.putObject("IamInstanceProfile")
.put("Arn", "arn:aws:iam::000000000000:instance-profile/explicit");
@@ -193,19 +189,11 @@ class Ec2LaunchTemplateCfnProvisionerTest {
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());
ArgumentCaptor<LaunchTemplateData> captor = ArgumentCaptor.forClass(LaunchTemplateData.class);
verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), captor.capture(), isNull());
assertEquals("arn:aws:iam::000000000000:instance-profile/explicit",
captor.getValue().getIamInstanceProfile().getArn());
assertNull(captor.getValue().getIamInstanceProfile().getName());
assertEquals(List.of("sg-1", "sg-2"), captor.getValue().getSecurityGroupIds());
}
}
@@ -1594,8 +1594,10 @@ class Ec2IntegrationTest {
equalTo("t3.micro"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.userData",
equalTo(launchTemplateUserData))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.iamInstanceProfile.arn",
equalTo("arn:aws:iam::000000000000:instance-profile/sample-profile"))
// Submitted as Name, so it reads back as Name. Rewriting it to an Arn is what made
// aws_launch_template.iam_instance_profile.name diff forever.
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.iamInstanceProfile.name",
equalTo("sample-profile"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.resourceType",
equalTo("instance"))
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:ClusterId' }.value",
@@ -1638,8 +1640,8 @@ class Ec2IntegrationTest {
equalTo("t3.small"))
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.userData",
equalTo(launchTemplateVersionUserData))
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.iamInstanceProfile.arn",
equalTo("arn:aws:iam::000000000000:instance-profile/sample-profile-v2"))
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.iamInstanceProfile.name",
equalTo("sample-profile-v2"))
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:NodeType' }.value",
equalTo("SECONDARY"));
@@ -0,0 +1,354 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.contains;
import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* Regression tests for CreateLaunchTemplate discarding nearly all of RequestLaunchTemplateData.
*
* <p>Only ImageId, InstanceType, KeyName, UserData, IamInstanceProfile, SecurityGroupIds and
* TagSpecifications survived a create; MetadataOptions, BlockDeviceMappings, NetworkInterfaces and
* every options block were dropped without an error. Terraform then read back its own input
* missing and reported "Provider produced inconsistent result after apply", or diffed forever.
*
* <p>Field names and shapes here follow the EC2 service model's RequestLaunchTemplateData and
* ResponseLaunchTemplateData. The request parameter names are the ones botocore's EC2 serializer
* actually emits — note the singular {@code BlockDeviceMapping.1} / {@code NetworkInterface.1}
* list prefixes, which come from each list member's locationName.
*/
@QuarkusTest
class Ec2LaunchTemplateFieldsIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String DATA =
"DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.";
private String uniqueName(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
}
private String describeBody(String name) {
return describeLatest(name).extract().body().asString();
}
private ValidatableResponse describeLatest(String name) {
return given()
.formParam("Action", "DescribeLaunchTemplateVersions")
.formParam("LaunchTemplateName", name)
.formParam("Versions.1", "$Latest")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
void metadataOptionsAndBlockDeviceMappingsRoundTrip() {
String name = uniqueName("repro-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.BlockDeviceMapping.1.DeviceName", "/dev/xvda")
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.VolumeSize", "20")
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.VolumeType", "gp3")
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.Encrypted", "true")
.formParam("LaunchTemplateData.MetadataOptions.HttpTokens", "required")
.formParam("LaunchTemplateData.MetadataOptions.HttpPutResponseHopLimit", "2")
.formParam("LaunchTemplateData.EbsOptimized", "true")
.formParam("LaunchTemplateData.Monitoring.Enabled", "true")
.formParam("LaunchTemplateData.CpuOptions.CoreCount", "1")
.formParam("LaunchTemplateData.CpuOptions.ThreadsPerCore", "1")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
describeLatest(name)
// IMDSv2 — appears in essentially every Gruntwork ASG/ECS module.
.body(DATA + "metadataOptions.httpTokens", equalTo("required"))
.body(DATA + "metadataOptions.httpPutResponseHopLimit", equalTo("2"))
.body(DATA + "metadataOptions.state", equalTo("applied"))
.body(DATA + "blockDeviceMappingSet.item.deviceName", equalTo("/dev/xvda"))
.body(DATA + "blockDeviceMappingSet.item.ebs.volumeSize", equalTo("20"))
.body(DATA + "blockDeviceMappingSet.item.ebs.volumeType", equalTo("gp3"))
.body(DATA + "blockDeviceMappingSet.item.ebs.encrypted", equalTo("true"))
.body(DATA + "ebsOptimized", equalTo("true"))
.body(DATA + "monitoring.enabled", equalTo("true"))
.body(DATA + "cpuOptions.coreCount", equalTo("1"))
.body(DATA + "cpuOptions.threadsPerCore", equalTo("1"));
}
@Test
void remainingOptionsBlocksRoundTrip() {
String name = uniqueName("options-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.Placement.Tenancy", "default")
.formParam("LaunchTemplateData.Placement.AvailabilityZone", "us-east-1a")
.formParam("LaunchTemplateData.CreditSpecification.CpuCredits", "unlimited")
.formParam("LaunchTemplateData.EnclaveOptions.Enabled", "false")
.formParam("LaunchTemplateData.HibernationOptions.Configured", "false")
.formParam("LaunchTemplateData.MaintenanceOptions.AutoRecovery", "default")
.formParam("LaunchTemplateData.PrivateDnsNameOptions.HostnameType", "ip-name")
.formParam("LaunchTemplateData.PrivateDnsNameOptions.EnableResourceNameDnsARecord", "true")
.formParam("LaunchTemplateData.CapacityReservationSpecification.CapacityReservationPreference", "open")
.formParam("LaunchTemplateData.DisableApiTermination", "false")
.formParam("LaunchTemplateData.InstanceInitiatedShutdownBehavior", "terminate")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
describeLatest(name)
.body(DATA + "placement.tenancy", equalTo("default"))
.body(DATA + "placement.availabilityZone", equalTo("us-east-1a"))
.body(DATA + "creditSpecification.cpuCredits", equalTo("unlimited"))
.body(DATA + "enclaveOptions.enabled", equalTo("false"))
.body(DATA + "hibernationOptions.configured", equalTo("false"))
.body(DATA + "maintenanceOptions.autoRecovery", equalTo("default"))
.body(DATA + "privateDnsNameOptions.hostnameType", equalTo("ip-name"))
.body(DATA + "privateDnsNameOptions.enableResourceNameDnsARecord", equalTo("true"))
.body(DATA + "capacityReservationSpecification.capacityReservationPreference", equalTo("open"))
.body(DATA + "disableApiTermination", equalTo("false"))
.body(DATA + "instanceInitiatedShutdownBehavior", equalTo("terminate"));
}
@Test
void iamInstanceProfileKeepsTheFormItWasGiven() {
// Terraform sets .name and read back .arn, so iam_instance_profile.name never converged.
String byName = uniqueName("profile-name-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", byName)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.IamInstanceProfile.Name", "audit-ip")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
describeLatest(byName)
.body(DATA + "iamInstanceProfile.name", equalTo("audit-ip"));
assertFalse(describeBody(byName).contains("<arn>"),
"a profile submitted as Name must not read back carrying an arn");
String byArn = uniqueName("profile-arn-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", byArn)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.IamInstanceProfile.Arn",
"arn:aws:iam::000000000000:instance-profile/explicit")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
describeLatest(byArn)
.body(DATA + "iamInstanceProfile.arn",
equalTo("arn:aws:iam::000000000000:instance-profile/explicit"));
assertFalse(describeBody(byArn).contains("<name>"),
"a profile submitted as Arn must not read back carrying a name");
}
@Test
void networkInterfacesSurviveAsNetworkInterfacesInsteadOfBeingPromoted() {
// Groups used to be hoisted into top-level SecurityGroupIds and the whole
// NetworkInterfaces block discarded. On AWS the two are mutually exclusive, so the
// network_interfaces block simply vanished from Terraform state.
String name = uniqueName("eni-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", "0")
.formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", "subnet-0123456789abcdef0")
.formParam("LaunchTemplateData.NetworkInterface.1.AssociatePublicIpAddress", "true")
.formParam("LaunchTemplateData.NetworkInterface.1.DeleteOnTermination", "true")
.formParam("LaunchTemplateData.NetworkInterface.1.SecurityGroupId.1", "sg-1111111111111111a")
.formParam("LaunchTemplateData.NetworkInterface.1.SecurityGroupId.2", "sg-2222222222222222b")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
describeLatest(name)
.body(DATA + "networkInterfaceSet.item.deviceIndex", equalTo("0"))
.body(DATA + "networkInterfaceSet.item.subnetId", equalTo("subnet-0123456789abcdef0"))
.body(DATA + "networkInterfaceSet.item.associatePublicIpAddress", equalTo("true"))
.body(DATA + "networkInterfaceSet.item.deleteOnTermination", equalTo("true"))
.body(DATA + "networkInterfaceSet.item.groupSet.item",
contains("sg-1111111111111111a", "sg-2222222222222222b"));
// Not promoted to the top level: that promotion is what made the block disappear.
assertFalse(describeBody(name).contains("securityGroupIdSet"),
"interface groups must not be hoisted into top-level SecurityGroupIds");
}
@Test
void createLaunchTemplateVersionInheritsOptionsBlocksItDoesNotRestate() {
String name = uniqueName("version-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.MetadataOptions.HttpTokens", "required")
.formParam("LaunchTemplateData.BlockDeviceMapping.1.DeviceName", "/dev/xvda")
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.VolumeSize", "20")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "CreateLaunchTemplateVersion")
.formParam("LaunchTemplateName", name)
.formParam("SourceVersion", "1")
.formParam("LaunchTemplateData.InstanceType", "t3.small")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.instanceType",
equalTo("t3.small"))
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData"
+ ".metadataOptions.httpTokens", equalTo("required"));
describeLatest(name)
.body(DATA + "instanceType", equalTo("t3.small"))
.body(DATA + "metadataOptions.httpTokens", equalTo("required"))
.body(DATA + "blockDeviceMappingSet.item.deviceName", equalTo("/dev/xvda"))
.body(DATA + "blockDeviceMappingSet.item.ebs.volumeSize", equalTo("20"));
}
@Test
void createLaunchTemplateVersionWithoutSourceVersionDoesNotInherit() {
// AWS documents "no SourceVersion" as "no inheritance" — the new version must start from
// an empty LaunchTemplateData, not merge onto the latest version the way an explicit
// SourceVersion does (see createLaunchTemplateVersionInheritsOptionsBlocksItDoesNotRestate
// above, which covers the explicit-SourceVersion case).
String name = uniqueName("no-source-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.KeyName", "app-key")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "CreateLaunchTemplateVersion")
.formParam("LaunchTemplateName", name)
// No SourceVersion parameter at all.
.formParam("LaunchTemplateData.InstanceType", "t3.small")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.instanceType",
equalTo("t3.small"));
String body = describeBody(name);
assertFalse(body.contains("<imageId>"),
"an omitted SourceVersion must not inherit ImageId from the latest version");
assertFalse(body.contains("<keyName>"),
"an omitted SourceVersion must not inherit KeyName from the latest version");
}
@Test
void versionDescriptionRoundTripsThroughCreateAndDescribe() {
String name = uniqueName("described-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("VersionDescription", "initial rollout")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId", org.hamcrest.Matchers.notNullValue());
given()
.formParam("Action", "CreateLaunchTemplateVersion")
.formParam("LaunchTemplateName", name)
.formParam("SourceVersion", "1")
.formParam("LaunchTemplateData.InstanceType", "t3.small")
.formParam("VersionDescription", "bump instance type")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.versionDescription",
equalTo("bump instance type"));
given()
.formParam("Action", "DescribeLaunchTemplateVersions")
.formParam("LaunchTemplateName", name)
.formParam("Versions.1", "1")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.versionDescription",
equalTo("initial rollout"));
describeLatest(name)
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.versionDescription",
equalTo("bump instance type"));
}
@Test
void securityGroupsByNameAreAcceptedAndIgnored() {
// By-name SecurityGroups stay out of scope (see docs/services/ec2.md): resolving names to
// IDs would need lookup machinery no other EC2 action here has either. The request must
// still succeed, and SecurityGroupIds — the supported form — must be unaffected.
String name = uniqueName("sg-by-name-lt");
given()
.formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
.formParam("LaunchTemplateData.SecurityGroup.1", "my-app-sg")
.formParam("LaunchTemplateData.SecurityGroupId.1", "sg-1111111111111111a")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
describeLatest(name)
.body(DATA + "securityGroupIdSet.item", equalTo("sg-1111111111111111a"));
assertFalse(describeBody(name).contains("my-app-sg"),
"SecurityGroups (by name) is accepted and ignored, not stored");
}
}
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.ec2.model.Image;
import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;
import io.github.hectorvent.floci.services.ec2.model.KeyPair;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import io.github.hectorvent.floci.services.ec2.model.NatGateway;
import io.github.hectorvent.floci.services.ec2.model.RouteTable;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
@@ -244,6 +245,84 @@ class Ec2ServicePersistenceTest {
assertEquals(0, afterDelete.getRoutes().size(), "delete must actually remove the legacy route");
}
/**
* Regression test for the pre-unified-data schema migration in LaunchTemplate /
* LaunchTemplateData: a launch template persisted before that PR stored the IAM instance
* profile as a bare {@code iamInstanceProfileArn} string and instance tags as a flat
* {@code instanceTags} list, both directly on LaunchTemplate and, separately, on each entry
* of its {@code versions} map. Without the legacy {@code @JsonSetter}s those two keys are
* unrecognized by the current model and ignoreUnknown drops them, so a template that used to
* carry an IAM profile and instance tags would come back from a restart with neither.
*
* <p>This writes a hand-built ec2-launch-templates.json in the pre-migration shape directly
* (rather than producing it by running old code), then loads a fresh Ec2Service over it and
* asserts the profile ARN and instance tag survive - covering both the versions-map entry
* (the path DescribeLaunchTemplateVersions and AutoScaling actually read) and the top-level
* fields (the path ensureLaunchTemplateVersions falls back to for a template with no
* versions map at all, i.e. one only ever read via {@code getData()} pre-migration).
*/
@Test
void legacyIamProfileAndInstanceTagsSurviveRestart(@TempDir Path dir) throws java.io.IOException {
String legacyJson = """
{
"us-east-1::lt-legacy-versioned": {
"launchTemplateId": "lt-legacy-versioned",
"launchTemplateName": "legacy-versioned",
"defaultVersionNumber": "1",
"latestVersionNumber": "1",
"region": "us-east-1",
"iamInstanceProfileArn": "arn:aws:iam::000000000000:instance-profile/legacy-profile",
"instanceTags": [ { "key": "Name", "value": "legacy-versioned" } ],
"versions": {
"1": {
"imageId": "ami-legacy",
"instanceType": "t3.micro",
"iamInstanceProfileArn": "arn:aws:iam::000000000000:instance-profile/legacy-profile",
"instanceTags": [ { "key": "Name", "value": "legacy-versioned" } ]
}
}
},
"us-east-1::lt-legacy-no-versions": {
"launchTemplateId": "lt-legacy-no-versions",
"launchTemplateName": "legacy-no-versions",
"defaultVersionNumber": "1",
"latestVersionNumber": "1",
"region": "us-east-1",
"imageId": "ami-legacy",
"instanceType": "t3.micro",
"iamInstanceProfileArn": "arn:aws:iam::000000000000:instance-profile/legacy-profile",
"instanceTags": [ { "key": "Name", "value": "legacy-no-versions" } ],
"versions": {}
}
}
""";
Files.writeString(dir.resolve("ec2-launch-templates.json"), legacyJson);
Ec2Service restarted = newService(dir);
LaunchTemplateData versioned = restarted
.describeLaunchTemplateVersions(REGION, "lt-legacy-versioned", null, List.of())
.getFirst()
.getData();
assertEquals("arn:aws:iam::000000000000:instance-profile/legacy-profile",
restarted.iamInstanceProfileArn(versioned),
"IAM instance profile on a legacy versions-map entry must survive restart");
assertEquals(List.of("legacy-versioned"),
versioned.getInstanceTags().stream().map(Tag::getValue).toList(),
"instance tags on a legacy versions-map entry must survive restart");
LaunchTemplateData noVersions = restarted
.describeLaunchTemplateVersions(REGION, "lt-legacy-no-versions", null, List.of())
.getFirst()
.getData();
assertEquals("arn:aws:iam::000000000000:instance-profile/legacy-profile",
restarted.iamInstanceProfileArn(noVersions),
"IAM instance profile on a legacy template with no versions map must survive restart");
assertEquals(List.of("legacy-no-versions"),
noVersions.getInstanceTags().stream().map(Tag::getValue).toList(),
"instance tags on a legacy template with no versions map must survive restart");
}
private BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setSnapshotId(snapshotId);
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
import io.github.hectorvent.floci.services.ec2.model.PrefixListId;
@@ -221,28 +222,92 @@ class Ec2ServiceTest {
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
LaunchTemplate template = service.createLaunchTemplate("us-east-1", "app-template",
"ami-source", "t3.micro", "app-key", List.of("sg-source"),
"source-user-data", "c291cmNlLXVzZXItZGF0YQ==",
"arn:aws:iam::000000000000:instance-profile/app-profile",
List.of(), List.of(new Tag("Role", "source")));
LaunchTemplateData source = new LaunchTemplateData();
source.setImageId("ami-source");
source.setInstanceType("t3.micro");
source.setKeyName("app-key");
source.setSecurityGroupIds(List.of("sg-source"));
source.setUserData("source-user-data");
source.setEncodedUserData("c291cmNlLXVzZXItZGF0YQ==");
source.setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(
"arn:aws:iam::000000000000:instance-profile/app-profile", null));
source.setTagSpecifications(List.of(
new LaunchTemplateData.TagSpecification("instance", List.of(new Tag("Role", "source")))));
LaunchTemplate template = service.createLaunchTemplate("us-east-1", "app-template", source, List.of());
service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null,
"1", null, "t3.small", null, List.of(), null, null, null, List.of());
LaunchTemplateData override = new LaunchTemplateData();
override.setInstanceType("t3.small");
service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null, "1", override);
LaunchTemplate version = service.describeLaunchTemplateVersions(
"us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst();
assertEquals("ami-source", version.getImageId());
assertEquals("t3.small", version.getInstanceType());
assertEquals("app-key", version.getKeyName());
assertEquals(List.of("sg-source"), version.getSecurityGroupIds());
assertEquals("source-user-data", version.getUserData());
assertEquals("c291cmNlLXVzZXItZGF0YQ==", version.getEncodedUserData());
assertEquals("arn:aws:iam::000000000000:instance-profile/app-profile", version.getIamInstanceProfileArn());
LaunchTemplateData data = version.getData();
assertEquals("ami-source", data.getImageId());
assertEquals("t3.small", data.getInstanceType());
assertEquals("app-key", data.getKeyName());
assertEquals(List.of("sg-source"), data.getSecurityGroupIds());
assertEquals("source-user-data", data.getUserData());
assertEquals("c291cmNlLXVzZXItZGF0YQ==", data.getEncodedUserData());
assertEquals("arn:aws:iam::000000000000:instance-profile/app-profile",
data.getIamInstanceProfile().getArn());
assertEquals("2", version.getLatestVersionNumber());
assertEquals(1, version.getInstanceTags().size());
assertEquals("Role", version.getInstanceTags().getFirst().getKey());
assertEquals("source", version.getInstanceTags().getFirst().getValue());
assertEquals(1, data.getInstanceTags().size());
assertEquals("Role", data.getInstanceTags().getFirst().getKey());
assertEquals("source", data.getInstanceTags().getFirst().getValue());
}
@Test
void launchTemplateVersionWithoutSourceVersionDoesNotInheritFromLatest() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
LaunchTemplateData source = new LaunchTemplateData();
source.setImageId("ami-source");
source.setInstanceType("t3.micro");
source.setKeyName("app-key");
source.setSecurityGroupIds(List.of("sg-source"));
LaunchTemplate template = service.createLaunchTemplate("us-east-1", "no-source-template", source, List.of());
LaunchTemplateData override = new LaunchTemplateData();
override.setInstanceType("t3.small");
// No SourceVersion at all — AWS documents this as "no source specified, no inheritance",
// not as an implicit fallback onto the latest version.
service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null, null, override);
LaunchTemplate version = service.describeLaunchTemplateVersions(
"us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst();
LaunchTemplateData data = version.getData();
assertEquals("t3.small", data.getInstanceType());
assertNull(data.getImageId(), "omitted SourceVersion must not inherit ImageId from version 1");
assertNull(data.getKeyName(), "omitted SourceVersion must not inherit KeyName from version 1");
assertEquals(List.of(), data.getSecurityGroupIds(),
"omitted SourceVersion must not inherit SecurityGroupIds from version 1");
}
@Test
void launchTemplateVersionDescriptionRoundTrips() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class),
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory());
LaunchTemplateData source = new LaunchTemplateData();
source.setImageId("ami-source");
LaunchTemplate template = service.createLaunchTemplate(
"us-east-1", "described-template", source, List.of(), "initial version");
LaunchTemplateData override = new LaunchTemplateData();
override.setInstanceType("t3.small");
LaunchTemplate created = service.createLaunchTemplateVersion(
"us-east-1", template.getLaunchTemplateId(), null, "1", override, "second version");
assertEquals("second version", created.getVersionDescription());
LaunchTemplate v1 = service.describeLaunchTemplateVersions(
"us-east-1", template.getLaunchTemplateId(), null, List.of("1")).getFirst();
LaunchTemplate v2 = service.describeLaunchTemplateVersions(
"us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst();
assertEquals("initial version", v1.getVersionDescription());
assertEquals("second version", v2.getVersionDescription());
}
@Test