fix(autoscaling): preserve launch template user data (#5607)

* fix(autoscaling): preserve launch template user data

* test(autoscaling): share launch-template SDK fixtures
This commit is contained in:
David Phillips authored and GitHub committed 2026-10-14 07:24:34 -04:00
1 parent 966da1d7fa
commit b488d0c418
5 files changed
+206 -10

No files matched your search

@@ -0,0 +1,53 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup;
import software.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest;
import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.InstanceAttributeName;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("Auto Scaling launch-template user data")
class AutoScalingTemplateUserDataTest {
@Test
@DisplayName("Launch templates preserve original encoded instance user data")
void originalEncodingReachesLaunchedInstance() throws InterruptedException {
String encoded = "/w";
String name = TestFixtures.uniqueName("asg-template-data");
try (AutoScalingClient asg = TestFixtures.autoScalingClient(); Ec2Client ec2 = TestFixtures.ec2Client()) {
ec2.createLaunchTemplate(r -> r.launchTemplateName(name).launchTemplateData(d -> d
.imageId("ami-amazonlinux2023").instanceType("t3.micro").userData(encoded)));
try {
LaunchTemplateSpecification template = LaunchTemplateSpecification.builder()
.launchTemplateName(name).version("1").build();
CreateAutoScalingGroupRequest.Builder create = CreateAutoScalingGroupRequest.builder()
.autoScalingGroupName(name).minSize(0).maxSize(1).desiredCapacity(1)
.availabilityZones(TestFixtures.availabilityZone()).launchTemplate(template);
asg.createAutoScalingGroup(create.build());
try {
TestFixtures.await(() -> !describe(asg, name).instances().isEmpty(),
name, "one launched instance", Duration.ofSeconds(30).toNanos(), 250);
AutoScalingGroup group = describe(asg, name);
assertThat(group.instances()).hasSize(1);
String id = group.instances().get(0).instanceId();
assertThat(ec2.describeInstanceAttribute(r -> r.instanceId(id)
.attribute(InstanceAttributeName.USER_DATA)).userData().value()).isEqualTo(encoded);
} finally {
asg.deleteAutoScalingGroup(r -> r.autoScalingGroupName(name).forceDelete(true));
}
} finally {
ec2.deleteLaunchTemplate(r -> r.launchTemplateName(name));
}
}
}
private static AutoScalingGroup describe(AutoScalingClient asg, String name) {
return asg.describeAutoScalingGroups(r -> r.autoScalingGroupNames(name)).autoScalingGroups().get(0);
}
}
+5
View File
@@ -155,6 +155,11 @@ gzip and expansion beyond 10 MiB; this is Floci's execution safety limit, not an
Invalid marked data in an older saved configuration is contained as a launch failure so reconciliation
can still save the group and check refresh progress.
Direct and mixed launch templates retain the selected version's original user-data
encoding for instance attributes and metadata, including compressed and binary
payloads. Execution still uses decoded text. Older templates that store only
execution text retain that text through a UTF-8 fallback.
Auto Scaling groups preserve either a launch configuration, a top-level launch template, or a `MixedInstancesPolicy`. These launch sources are mutually exclusive in create/update requests. When a mixed instances policy is supplied, Floci stores and returns:
- `LaunchTemplate.LaunchTemplateSpecification.LaunchTemplateId`
@@ -612,7 +612,7 @@ public class AutoScalingReconciler {
version.getData().getInstanceTags(),
Ec2UserDataDecoder.decodeIfMissing(
version.getData().getUserData(), version.getData().getEncodedUserData()),
null,
version.getData().getEncodedUserData(),
ec2Service.iamInstanceProfileArn(version.getData()),
asg.getLaunchTemplateId(),
asg.getLaunchTemplateName(),
@@ -644,7 +644,7 @@ public class AutoScalingReconciler {
version.getData().getInstanceTags(),
Ec2UserDataDecoder.decodeIfMissing(
version.getData().getUserData(), version.getData().getEncodedUserData()),
null,
version.getData().getEncodedUserData(),
ec2Service.iamInstanceProfileArn(version.getData()),
specification.getLaunchTemplateId() == null
? mixedLaunchTemplate.getLaunchTemplateId()
@@ -19,11 +19,15 @@ import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
import io.github.hectorvent.floci.services.elbv2.model.TargetHealth;
import io.github.hectorvent.floci.services.ssm.SsmCommandService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -128,8 +132,20 @@ class AutoScalingReconcilerTest {
any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any());
}
@Test
void scaleOutUsesRequestedLaunchTemplateVersionData() {
static Stream<Arguments> templateUserData() {
return Stream.of(
Arguments.of(null, "IyEvYmluL2Jhc2gKZWNobyBoaQo=", "#!/bin/bash\necho hi\n",
"IyEvYmluL2Jhc2gKZWNobyBoaQo="),
Arguments.of("legacy text", null, "legacy text", "bGVnYWN5IHRleHQ="),
Arguments.of("YQ==", null, "YQ==", "WVE9PQ=="),
Arguments.of(null, null, null, null),
Arguments.of(null, "", null, ""));
}
@ParameterizedTest
@MethodSource("templateUserData")
void scaleOutUsesRequestedLaunchTemplateVersionData(String storedText, String storedEncoding,
String expectedText, String expectedEncoding) {
AutoScalingService asgService = scalingService();
Ec2Service ec2Service = mock(Ec2Service.class);
ElbV2Service elbV2Service = mock(ElbV2Service.class);
@@ -151,7 +167,8 @@ class AutoScalingReconcilerTest {
version.setLatestVersionNumber("1");
version.getData().setImageId("ami-version-1");
version.getData().setInstanceType("t3.micro");
version.getData().setEncodedUserData("IyEvYmluL2Jhc2gKZWNobyBoaQo=");
version.getData().setUserData(storedText);
version.getData().setEncodedUserData(storedEncoding);
version.getData().setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(
"arn:aws:iam::000000000000:instance-profile/app-profile", null));
when(ec2Service.iamInstanceProfileArn(version.getData()))
@@ -170,9 +187,9 @@ class AutoScalingReconcilerTest {
reservation.setInstances(List.of(ec2Instance));
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
anyList(), eq("#!/bin/bash\necho hi\n"),
anyList(), eq(expectedText),
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any())).thenReturn(reservation);
isNull(), eq(0), isNull(), isNull(), isNull(), eq(expectedEncoding))).thenReturn(reservation);
reconciler.reconcile(asg);
@@ -183,10 +200,11 @@ class AutoScalingReconcilerTest {
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.captor();
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-1"), eq("t3.micro"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
tags.capture(), eq("#!/bin/bash\necho hi\n"),
tags.capture(), eq(expectedText),
eq("arn:aws:iam::000000000000:instance-profile/app-profile"), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any());
assertNull(version.getData().getUserData());
isNull(), eq(0), isNull(), isNull(), isNull(), eq(expectedEncoding));
assertEquals(storedText, version.getData().getUserData());
assertEquals(storedEncoding, version.getData().getEncodedUserData());
assertEquals(propagatedTags.size(), tags.getValue().size());
assertEquals("app.ClusterId", tags.getValue().get(0).getKey());
assertEquals("development", tags.getValue().get(0).getValue());
@@ -0,0 +1,120 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingReconciler;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.ec2.model.Instance;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.net.http.HttpResponse;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@QuarkusTest
class AutoScalingTemplateUserDataIntegrationTest {
@Inject Ec2Service ec2;
@Inject AutoScalingReconciler reconciler;
@InjectSpy AutoScalingService asg;
@BeforeEach
void isolateDirectReconciliation() {
// The custom background executor lists every group with null region and names.
doReturn(List.of()).when(asg).describeAutoScalingGroups(isNull(), isNull());
}
@AfterEach
void restoreBackgroundEnumeration() {
reset(asg);
}
static Stream<Arguments> launchSources() {
return Stream.of("template", "mixed").flatMap(source ->
Stream.of(null, "", "YQ==", "YQ", "/w", "H4sIAAAAAAAC/1NW1E/KzNMvzuBKTc7IV8hIzcnJ5wIAedQ/FxUAAAA=")
.map(data -> Arguments.of(source, data)));
}
@ParameterizedTest
@MethodSource("launchSources")
void launchPreservesOriginalEncodingAndImdsBytes(String source, String encoded) throws Exception {
String name = "userdata-" + UUID.randomUUID().toString().substring(0, 8);
RequestSpecification create = request("ec2", "CreateLaunchTemplate");
String prefix = "LaunchTemplateData.";
create.formParam("LaunchTemplateName", name)
.formParam(prefix + "ImageId", "ami-amazonlinux2023")
.formParam(prefix + "InstanceType", "t3.micro");
if (encoded != null) {
create.formParam(prefix + "UserData", encoded);
}
create.post("/").then().statusCode(200);
try {
RequestSpecification group = request("autoscaling", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name).formParam("MinSize", 0)
.formParam("MaxSize", 1).formParam("DesiredCapacity", 0)
.formParam("AvailabilityZones.member.1", "us-east-1a");
String template = "mixed".equals(source)
? "MixedInstancesPolicy.LaunchTemplate.LaunchTemplateSpecification." : "LaunchTemplate.";
group.formParam(template + "LaunchTemplateName", name).formParam(template + "Version", "1");
group.post("/").then().statusCode(200);
try {
request("autoscaling", "SetDesiredCapacity").formParam("AutoScalingGroupName", name)
.formParam("DesiredCapacity", 1).post("/").then().statusCode(200);
reconciler.reconcile(asg.describeAutoScalingGroups("us-east-1", List.of(name)).getFirst());
String id = request("autoscaling", "DescribeAutoScalingGroups")
.formParam("AutoScalingGroupNames.member.1", name).post("/").then().statusCode(200)
.extract().path("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult."
+ "AutoScalingGroups.member.Instances.member.InstanceId");
assertNotNull(id);
Instance instance = ec2.describeInstances("us-east-1", List.of(id), Map.of()).getFirst()
.getInstances().getFirst();
String actual = request("ec2", "DescribeInstanceAttribute").formParam("InstanceId", id)
.formParam("Attribute", "userData").post("/").then().statusCode(200)
.extract().xmlPath().getString("DescribeInstanceAttributeResponse.userData.value");
try (Ec2MetadataTestFixture metadata = new Ec2MetadataTestFixture()) {
metadata.start(null, mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), instance);
HttpResponse<byte[]> response = metadata.get("/latest/user-data", null,
HttpResponse.BodyHandlers.ofByteArray());
assertAll(
() -> assertEquals(encoded == null ? "" : encoded, actual),
() -> assertEquals(normalize(Ec2UserDataDecoder.decode(encoded)), normalize(instance.getUserData())),
() -> assertEquals(encoded == null || encoded.isEmpty() ? 404 : 200, response.statusCode()),
() -> {
if (encoded != null && !encoded.isEmpty()) {
assertArrayEquals(Base64.getDecoder().decode(encoded), response.body());
}
});
}
} finally {
request("autoscaling", "DeleteAutoScalingGroup").formParam("AutoScalingGroupName", name)
.formParam("ForceDelete", true).post("/").then().statusCode(200);
}
} finally {
request("ec2", "DeleteLaunchTemplate")
.formParam("LaunchTemplateName", name)
.post("/").then().statusCode(200);
}
}
private static String normalize(String value) {
return value == null ? "" : value;
}
private static RequestSpecification request(String service, String action) {
return given().header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260215/us-east-1/"
+ service + "/aws4_request, SignedHeaders=host, Signature=abc").formParam("Action", action);
}
}