fix(autoscaling): tag member instances with aws:autoscaling:groupName (#6471)

* fix(autoscaling): tag member instances with aws:autoscaling:groupName

Auto Scaling adds the aws:autoscaling:groupName tag, valued with the
group's name, to every instance it launches or attaches, and removes it
when the instance is detached. Floci never set it, so filtering EC2
instances on tag:aws:autoscaling:groupName found none of a group's
members.

- Launches add the tag after the launch template's instance tags and the
  group's PropagateAtLaunch tags, so the group's actual name wins over
  any stored tag with that key.
- AttachInstances applies the group's PropagateAtLaunch tags and the
  group-name tag to the instances EC2 holds. It refuses the whole batch
  with ValidationError when an instance already belongs to a group, so
  one group cannot overwrite another group's tag, and an instance named
  twice in one request joins once. An ID EC2 has no instance for still
  joins, as before, but gets no tags, which would otherwise outlive it
  in EC2's DescribeTags.
- DetachInstances removes only the group-name tag, and only where it
  still names that group. It goes through a new service-owned EC2 tag
  delete, because the public DeleteTags refuses aws: keys.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(compat): cover the Auto Scaling group-name tag through the SDK

Drives launch, attach, a refused second attach and detach with the AWS
SDK for Java and checks the instance tags EC2 reports after each step.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-24 22:46:08 -04:00
1 parent 75d7923290
commit c517e4eb76
9 files changed
+610 -44

No files matched your search

@@ -0,0 +1,158 @@
package io.github.hectorvent.floci.services.autoscaling;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The {@code aws:autoscaling:groupName} tag over a member's lifecycle, as the EC2 Auto Scaling user
* guide describes it: the group adds it to the instances it launches and attaches, attaching also
* applies the group's PropagateAtLaunch tags, and detaching removes only that one tag.
*/
@QuarkusTest
class AutoScalingInstanceMembershipTagIntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=414141414141/20261022/us-east-1/autoscaling/aws4_request";
private static final String EC2_AUTH = AUTH.replace("/autoscaling/", "/ec2/");
private static final String GROUP_NAME_TAG = "aws:autoscaling:groupName";
@Inject
AutoScalingReconciler reconciler;
@Test
void groupNameTagFollowsLaunchAttachAndDetach() {
String name = "membership-" + UUID.randomUUID();
String other = name + "-other";
given().header("Authorization", EC2_AUTH).formParam("Action", "CreateLaunchTemplate")
.formParam("LaunchTemplateName", name)
.formParam("LaunchTemplateData.ImageId", "ami-12345678")
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
.formParam("LaunchTemplateData.TagSpecification.1.ResourceType", "instance")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Key", "Source")
.formParam("LaunchTemplateData.TagSpecification.1.Tag.1.Value", "template")
.post("/").then().statusCode(200);
given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name)
.formParam("LaunchTemplate.LaunchTemplateName", name).formParam("LaunchTemplate.Version", "1")
.formParam("MinSize", "0").formParam("MaxSize", "3").formParam("DesiredCapacity", "1")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.formParam("Tags.member.1.Key", "Team").formParam("Tags.member.1.Value", "blue")
.formParam("Tags.member.1.PropagateAtLaunch", "true")
.formParam("Tags.member.2.Key", "Private").formParam("Tags.member.2.Value", "group-only")
.formParam("Tags.member.2.PropagateAtLaunch", "false")
.post("/").then().statusCode(200);
given().header("Authorization", AUTH).formParam("Action", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", other)
.formParam("LaunchTemplate.LaunchTemplateName", name).formParam("LaunchTemplate.Version", "1")
.formParam("MinSize", "0").formParam("MaxSize", "3").formParam("DesiredCapacity", "0")
.formParam("AvailabilityZones.member.1", "us-east-1a")
.post("/").then().statusCode(200);
String standalone = null;
try {
reconciler.reconcileAll();
String launched = given().header("Authorization", AUTH)
.formParam("Action", "DescribeAutoScalingGroups").formParam("AutoScalingGroupNames.member.1", name)
.post("/").then().statusCode(200)
.body("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ ".AutoScalingGroups.member.Instances.member.size()", equalTo(1))
.extract().path("DescribeAutoScalingGroupsResponse.DescribeAutoScalingGroupsResult"
+ ".AutoScalingGroups.member.Instances.member.InstanceId");
assertEquals(Map.of("Source", "template", "Team", "blue"), userTags(launched));
assertEquals(name, instanceTags(launched).get(GROUP_NAME_TAG));
assertEquals(List.of(launched), instancesTaggedWith(name));
standalone = given().header("Authorization", EC2_AUTH).formParam("Action", "RunInstances")
.formParam("ImageId", "ami-12345678").formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1").formParam("MaxCount", "1")
.formParam("TagSpecification.1.ResourceType", "instance")
.formParam("TagSpecification.1.Tag.1.Key", "Team")
.formParam("TagSpecification.1.Tag.1.Value", "red")
.formParam("TagSpecification.1.Tag.2.Key", "Owner")
.formParam("TagSpecification.1.Tag.2.Value", "me")
.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
attach(name, standalone).statusCode(200);
assertEquals(Map.of("Owner", "me", "Team", "blue"), userTags(standalone));
assertEquals(name, instanceTags(standalone).get(GROUP_NAME_TAG));
// An ID EC2 has no instance for gets no tags, which would otherwise outlive it in DescribeTags.
String unknown = "i-0abcdef1234567890";
attach(other, unknown);
given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeTags")
.formParam("Filter.1.Name", "resource-id").formParam("Filter.1.Value.1", unknown)
.post("/").then().statusCode(200)
.body("DescribeTagsResponse.tagSet.item.size()", equalTo(0));
String alreadyMember = "[The Instance: " + standalone + " is already part of AutoScalingGroup:" + name + "]";
for (String group : List.of(name, other)) {
attach(group, standalone).statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo(alreadyMember));
}
assertEquals(name, instanceTags(standalone).get(GROUP_NAME_TAG));
given().header("Authorization", AUTH).formParam("Action", "DetachInstances")
.formParam("AutoScalingGroupName", name).formParam("InstanceIds.member.1", standalone)
.formParam("ShouldDecrementDesiredCapacity", "true")
.post("/").then().statusCode(200);
assertEquals(Map.of("Owner", "me", "Team", "blue"), instanceTags(standalone));
assertEquals(List.of(launched), instancesTaggedWith(name));
} finally {
for (String group : List.of(name, other)) {
given().header("Authorization", AUTH).formParam("Action", "DeleteAutoScalingGroup")
.formParam("AutoScalingGroupName", group).formParam("ForceDelete", "true").post("/");
}
if (standalone != null) {
given().header("Authorization", EC2_AUTH).formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", standalone).post("/");
}
given().header("Authorization", EC2_AUTH).formParam("Action", "DeleteLaunchTemplate")
.formParam("LaunchTemplateName", name).post("/");
}
}
private static ValidatableResponse attach(String group, String instanceId) {
return given().header("Authorization", AUTH).formParam("Action", "AttachInstances")
.formParam("AutoScalingGroupName", group).formParam("InstanceIds.member.1", instanceId)
.post("/").then();
}
private static Map<String, String> instanceTags(String instanceId) {
XmlPath xml = given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instanceId).post("/").then().statusCode(200).extract().xmlPath();
String item = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.tagSet.item";
List<String> keys = xml.getList(item + ".key");
List<String> values = xml.getList(item + ".value");
Map<String, String> tags = new HashMap<>();
for (int i = 0; i < keys.size(); i++) {
tags.put(keys.get(i), values.get(i));
}
return tags;
}
/** The instance's tags without the {@code aws:} ones AWS adds on its own, such as launch template ids. */
private static Map<String, String> userTags(String instanceId) {
Map<String, String> tags = instanceTags(instanceId);
tags.keySet().removeIf(key -> key.startsWith("aws:"));
return tags;
}
private static List<String> instancesTaggedWith(String group) {
return given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeInstances")
.formParam("Filter.1.Name", "tag:" + GROUP_NAME_TAG).formParam("Filter.1.Value.1", group)
.post("/").then().statusCode(200).extract().xmlPath()
.getList("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceId");
}
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.autoscaling;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.autoscaling.model.AsgInstance;
import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
import io.github.hectorvent.floci.services.autoscaling.model.CapacityReservationSpecification;
import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
import io.github.hectorvent.floci.services.autoscaling.model.ScalingActivity;
@@ -28,6 +29,7 @@ import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -39,6 +41,7 @@ import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyList;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.isNull;
@@ -183,7 +186,8 @@ class AutoScalingReconcilerTest {
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"));
List<Tag> propagatedTags = List.of(new Tag("app.ClusterId", "development"), new Tag("job-id", "2001"),
new Tag("aws:autoscaling:groupName", "app-asg"));
version.getData().setTagSpecifications(List.of(
new LaunchTemplateData.TagSpecification("instance", instanceTags)));
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
@@ -221,6 +225,74 @@ class AutoScalingReconcilerTest {
assertEquals("development", tags.getValue().get(0).getValue());
assertEquals("job-id", tags.getValue().get(1).getKey());
assertEquals("2001", tags.getValue().get(1).getValue());
assertEquals("aws:autoscaling:groupName", tags.getValue().get(2).getKey());
assertEquals("app-asg", tags.getValue().get(2).getValue());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void scaleOutTagsTheActualGroupNameOverConflictingTemplateAndGroupTags(boolean propagateGroupNameTag) {
AutoScalingService asgService = scalingService();
Ec2Service ec2Service = mock(Ec2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class));
AutoScalingGroup asg = launchTemplateAsg();
asg.getTags().put("aws:autoscaling:groupName", "spoofed-group");
asg.getTagPropagateAtLaunch().put("aws:autoscaling:groupName", propagateGroupNameTag);
asg.getTags().put("shared", "group-value");
asg.getTagPropagateAtLaunch().put("shared", true);
asg.getTags().put("control-plane-only", "private");
asg.getTagPropagateAtLaunch().put("control-plane-only", false);
stubLaunchTemplate(ec2Service, "ami-version-1", "t3.micro");
LaunchTemplate version = ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("1"))
.getFirst();
version.getData().setTagSpecifications(List.of(new LaunchTemplateData.TagSpecification("instance", List.of(
new Tag("aws:autoscaling:groupName", "spoofed-template"), new Tag("shared", "template-value"),
new Tag("template-only", "kept")))));
when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true);
when(ec2Service.runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(),
anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull()))
.thenReturn(reservation(ec2Instance("i-tagged", InstanceState.pending())));
reconciler.reconcile(asg);
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.captor();
verify(ec2Service).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
any(), any(), any(), tags.capture(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(),
any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), isNull());
assertEquals(Map.of("aws:autoscaling:groupName", "app-asg", "shared", "group-value", "template-only", "kept"),
tags.getValue().stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue)));
assertEquals("spoofed-group", asg.getTags().get("aws:autoscaling:groupName"));
}
@Test
void capacityFallbackRetryStillTagsTheGroupName() {
AutoScalingService asgService = scalingService();
Ec2Service ec2Service = mock(Ec2Service.class);
AutoScalingReconciler reconciler = new AutoScalingReconciler(asgService, ec2Service, mock(ElbV2Service.class));
AutoScalingGroup asg = launchTemplateAsg();
CapacityReservationSpecification capacity = new CapacityReservationSpecification();
capacity.setCapacityReservationPreference("capacity-reservations-first");
asg.setCapacityReservationSpecification(capacity);
stubLaunchTemplate(ec2Service, "ami-version-1", "t3.micro");
when(asgService.saveAutoScalingGroupIfPresent(asg)).thenReturn(true);
when(ec2Service.runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
any(), any(), any(), any(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(), any(),
anyBoolean(), any(), any(), any(), eq(false), isNull(), any()))
.thenThrow(new AwsException("InsufficientInstanceCapacity", "no reserved capacity", 400))
.thenReturn(reservation(ec2Instance("i-fallback", InstanceState.pending())));
reconciler.reconcile(asg);
ArgumentCaptor<List<Tag>> tags = ArgumentCaptor.captor();
verify(ec2Service, times(2)).runInstances(any(), any(), any(), any(Integer.class), any(Integer.class), any(),
any(), any(), any(), tags.capture(), any(), any(), any(), any(), any(Integer.class), any(), any(), any(),
any(), anyBoolean(), any(), any(), any(), eq(false), isNull(), any());
for (List<Tag> launchTags : tags.getAllValues()) {
assertEquals(Map.of("aws:autoscaling:groupName", "app-asg"),
launchTags.stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue)));
}
assertEquals("i-fallback", asg.getInstances().getFirst().getInstanceId());
}
@Test
@@ -238,7 +310,7 @@ class AutoScalingReconcilerTest {
Reservation reservation = new Reservation();
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), eq(List.of()),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), onlyGroupNameTag("app-asg"),
eq(null), eq(null), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
@@ -333,7 +405,7 @@ class AutoScalingReconcilerTest {
Reservation reservation = new Reservation();
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), eq(List.of()),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null), onlyGroupNameTag("app-asg"),
eq(null), eq(null), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
@@ -380,7 +452,7 @@ class AutoScalingReconcilerTest {
reservation.setInstances(List.of(ec2Instance));
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"),
eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),
anyList(), eq(null), eq(null), eq(associatePublicIp),
onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(associatePublicIp),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
@@ -388,7 +460,7 @@ class AutoScalingReconcilerTest {
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-lc"), eq("t3.micro"),
eq(1), eq(1), eq(null), anyList(), eq(null), eq(null),
anyList(), eq(null), eq(null), eq(associatePublicIp),
onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(associatePublicIp),
isNull(), eq(0), isNull(), isNull(), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
}
@@ -422,7 +494,7 @@ class AutoScalingReconcilerTest {
reservation.setInstances(List.of(ec2Instance));
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-7"), eq("t3.micro"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq(null), eq(null), eq(null),
onlyGroupNameTag("app-asg"), eq(null), eq(null), eq(null),
isNull(), eq(0), isNull(), isNull(), isNull(), any(),
anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
@@ -480,7 +552,7 @@ class AutoScalingReconcilerTest {
reservation.setInstances(List.of(ec2Instance));
when(ec2Service.runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
onlyGroupNameTag("app-asg"), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
isNull(), eq(0), isNull(), eq(metadata), isNull(), any(),
anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull())).thenReturn(reservation);
@@ -493,7 +565,7 @@ class AutoScalingReconcilerTest {
assertEquals("t3.small", asg.getInstances().getFirst().getInstanceType());
verify(ec2Service).runInstances(eq("us-east-1"), eq("ami-version-3"), eq("t3.small"),
eq(1), eq(1), eq(null), eq(List.of()), eq(null), eq(null),
eq(List.of()), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
onlyGroupNameTag("app-asg"), eq("#!/bin/bash\necho hi\n"), eq(null), eq(null),
isNull(), eq(0), isNull(), eq(metadata), isNull(), any(), anyBoolean(), isNull(), isNull(), any(), eq(false), isNull(), isNull());
assertNull(version.getData().getUserData());
}
@@ -1100,6 +1172,13 @@ class AutoScalingReconcilerTest {
return asg;
}
/** Matches the tags of a launch whose template and group add none of their own. */
private static List<Tag> onlyGroupNameTag(String groupName) {
return argThat(tags -> tags != null && tags.size() == 1
&& "aws:autoscaling:groupName".equals(tags.getFirst().getKey())
&& groupName.equals(tags.getFirst().getValue()));
}
private static void stubLaunchTemplate(Ec2Service ec2Service, String imageId, String instanceType) {
LaunchTemplate launchTemplate = new LaunchTemplate();
launchTemplate.setLaunchTemplateId("lt-123");
@@ -22,11 +22,13 @@ import io.github.hectorvent.floci.services.ec2.model.Instance;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -36,12 +38,19 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.anyList;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -136,6 +145,110 @@ class AutoScalingServiceTest {
assertNull(group.getLaunchConfigurationName());
}
@Test
void attachedInstancesReceiveThePropagatingTagsAndTheirGroupName() {
service.ec2Service = mock(Ec2Service.class);
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
group.getTags().put("env", "group");
group.getTags().put("hidden", "group");
group.getTags().put("aws:autoscaling:groupName", "spoofed");
group.getTagPropagateAtLaunch().putAll(Map.of("env", true, "hidden", false,
"aws:autoscaling:groupName", true));
ec2HoldsInstances("i-attached");
service.attachInstances(REGION, "test-asg", List.of("i-attached"));
ArgumentCaptor<List<Tag>> appliedTags = ArgumentCaptor.captor();
verify(service.ec2Service).createSystemTags(eq(REGION), eq(List.of("i-attached")), appliedTags.capture());
assertEquals(Map.of("env", "group", "aws:autoscaling:groupName", "test-asg"),
appliedTags.getValue().stream().collect(Collectors.toMap(Tag::getKey, Tag::getValue)));
assertEquals(List.of("i-attached"), group.getInstances().stream().map(AsgInstance::getInstanceId).toList());
}
@Test
void attachTagsOnlyTheInstancesEc2Holds() {
service.ec2Service = mock(Ec2Service.class);
ec2HoldsInstances("i-held");
service.attachInstances(REGION, "test-asg", List.of("i-held", "i-unknown"));
verify(service.ec2Service).createSystemTags(eq(REGION), eq(List.of("i-held")), anyList());
verify(service.ec2Service, times(1)).createSystemTags(anyString(), anyList(), anyList());
}
@Test
void attachCountsARepeatedInstanceOnce() {
service.ec2Service = mock(Ec2Service.class);
ec2HoldsInstances("i-repeated");
service.attachInstances(REGION, "test-asg", List.of("i-repeated", "i-repeated"));
verify(service.ec2Service).createSystemTags(eq(REGION), eq(List.of("i-repeated")), anyList());
assertEquals(List.of("i-repeated"), service.describeAutoScalingGroups(REGION, List.of("test-asg"))
.getFirst().getInstances().stream().map(AsgInstance::getInstanceId).toList());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void attachRejectsAnInstanceThatAlreadyBelongsToAGroupBeforeTaggingAnyOfTheBatch(boolean sameGroup) {
service.createAutoScalingGroup(REGION, "other-asg", null, "lt-original", null, "1", null,
0, 3, 0, 300, List.of(REGION + "a"), List.of(), List.of(), List.of(),
"EC2", 0, List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none());
service.ec2Service = mock(Ec2Service.class);
service.attachInstances(REGION, "test-asg", List.of("i-owned"));
clearInvocations(service.ec2Service);
String target = sameGroup ? "test-asg" : "other-asg";
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of(target)).getFirst();
int desired = group.getDesiredCapacity();
List<String> members = group.getInstances().stream().map(AsgInstance::getInstanceId).toList();
AwsException failure = assertThrows(AwsException.class,
() -> service.attachInstances(REGION, target, List.of("i-free", "i-owned")));
assertEquals("ValidationError", failure.getErrorCode());
assertEquals(400, failure.getHttpStatus());
assertEquals("[The Instance: i-owned is already part of AutoScalingGroup:test-asg]", failure.getMessage());
assertEquals(members, group.getInstances().stream().map(AsgInstance::getInstanceId).toList());
assertEquals(desired, group.getDesiredCapacity());
verifyNoInteractions(service.ec2Service);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void detachRemovesOnlyTheDetachedInstancesGroupNameTag(boolean decrementDesiredCapacity) {
service.ec2Service = mock(Ec2Service.class);
service.attachInstances(REGION, "test-asg", List.of("i-detached", "i-retained"));
service.detachInstances(REGION, "test-asg", List.of("i-detached"), decrementDesiredCapacity);
verify(service.ec2Service).deleteSystemTag(
REGION, List.of("i-detached"), "aws:autoscaling:groupName", "test-asg");
AutoScalingGroup group = service.describeAutoScalingGroups(REGION, List.of("test-asg")).getFirst();
assertEquals(List.of("i-retained"), group.getInstances().stream().map(AsgInstance::getInstanceId).toList());
assertEquals(decrementDesiredCapacity ? 1 : 2, group.getDesiredCapacity());
}
@Test
void detachingAnInstanceTheGroupDoesNotHoldChangesNoTags() {
service.ec2Service = mock(Ec2Service.class);
service.attachInstances(REGION, "test-asg", List.of("i-member"));
clearInvocations(service.ec2Service);
service.detachInstances(REGION, "test-asg", List.of("i-stranger"), false);
verify(service.ec2Service, never()).deleteSystemTag(anyString(), anyList(), anyString(), anyString());
assertEquals(List.of("i-member"), service.describeAutoScalingGroups(REGION, List.of("test-asg"))
.getFirst().getInstances().stream().map(AsgInstance::getInstanceId).toList());
}
private void ec2HoldsInstances(String... instanceIds) {
for (String id : instanceIds) {
Instance instance = new Instance();
instance.setInstanceId(id);
when(service.ec2Service.findInstanceForAccount("000000000000", REGION, id)).thenReturn(Optional.of(instance));
}
}
@Test
void anInstanceRefreshResolvesTheProfileOfTheTemplateItsGroupLaunchesFromOnceItApplies() {
Ec2Service ec2Service = mock(Ec2Service.class);
@@ -971,6 +1084,7 @@ class AutoScalingServiceTest {
StorageBackedMap<AutoScalingGroup> groups = new StorageBackedMap<>(storage);
groups.putAll(service.groups);
service.groups = groups;
service.ec2Service = mock(Ec2Service.class);
service.attachInstances(REGION, "test-asg", List.of("i-live"));
service.createOrUpdateTags(REGION, "test-asg", "auto-scaling-group", Map.of("k", "v"), Map.of());
@@ -202,6 +202,27 @@ class Ec2ServiceTest {
assertEquals(List.of(membership), instance.getTags());
}
@Test
void deleteSystemTagRemovesTheTagOnlyWhenItsValueMatches() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
Tag membership = new Tag("aws:autoscaling:groupName", "group-a");
Tag userTag = new Tag("env", "test");
List<String> ids = List.of(service.runInstances("us-east-1", "ami-test", "t3.micro",
1, 1, null, List.of(), null, null, List.of(membership, userTag), null, null)
.getInstances().getFirst().getInstanceId());
service.deleteSystemTag("us-east-1", ids, membership.getKey(), "group-b");
assertEquals(List.of(membership, userTag), service.describeInstances("us-east-1", ids, Map.of())
.getFirst().getInstances().getFirst().getTags());
service.deleteSystemTag("us-east-1", ids, membership.getKey(), "group-a");
assertEquals(List.of(userTag), service.describeInstances("us-east-1", ids, Map.of())
.getFirst().getInstances().getFirst().getTags());
assertEquals(List.of(userTag), service.resourceTags("us-east-1", ids.getFirst()));
}
@Test
void subnetAvailableAddressesTrackAllocationsAndRelease() {