fix(ec2): tag the volumes RunInstances creates with the volume TagSpecification (#10281)

RunInstances now applies a ResourceType=volume TagSpecification to the EBS volumes the launch creates, and a launch template's network-interface and volume tags reach those resources as its instance tags already did, with a request tag replacing the template's tag of the same key. The merged list for each type is validated before the launch, so tags over the limit together leave nothing behind. CreateFleet's template tag merge uses the same helper.

Closes #8302
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-12-05 21:39:45 -04:00
1 parent 060a57a683
commit c5b1152cbc
3 files changed
+173 -17

No files matched your search

+1 -1
View File
@@ -472,7 +472,7 @@ naming different VPCs find nothing.
| Action | Description |
|--------|-------------|
| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. Security groups come from `SecurityGroupId.N` or, as Terraform sends them with an interface spec, from the primary interface's `NetworkInterface.1.SecurityGroupId.N`; both in one request is `InvalidParameterCombination`. A launch without groups uses the default security group of its subnet's VPC. |
| RunInstances | Creates one or more local EC2 instances, starting Docker-backed runtime when not in mock mode. Security groups come from `SecurityGroupId.N` or, as Terraform sends them with an interface spec, from the primary interface's `NetworkInterface.1.SecurityGroupId.N`; both in one request is `InvalidParameterCombination`. A launch without groups uses the default security group of its subnet's VPC. Each `TagSpecification` tags the resource type it names: `instance` the instances, `volume` the EBS volumes the launch creates and `network-interface` the interfaces it creates. A launch template's tags for each of those types apply too, a request tag replacing the template's tag of the same key. A rejected tag fails the launch before anything is created. |
| CreateFleet | Creates an instant local fleet from launch-template configurations and on-demand or spot overrides. DryRun returns the AWS-compatible `DryRunOperation` error without launching instances. |
| DescribeInstances | Lists or returns stored EC2 instances. |
| TerminateInstances | Terminates instances and updates their stored lifecycle state. |
@@ -594,6 +594,23 @@ public class Ec2QueryHandler {
return parseTagsForResource(p, resourceType, Set.of());
}
/**
* A launch template's tags for one resource type with the request's for the same type over them: a launch gets
* both, and a request tag replaces the template's tag of the same key. The two together count toward the
* resource's tag limit, so the merged list is checked here, before the launch creates anything.
*/
private static List<Tag> withTemplateTags(List<Tag> templateTags, List<Tag> requestTags) {
if (templateTags.isEmpty()) {
return requestTags;
}
Map<String, Tag> merged = new LinkedHashMap<>();
templateTags.forEach(tag -> merged.put(tag.getKey(), tag));
requestTags.forEach(tag -> merged.put(tag.getKey(), tag));
List<Tag> effective = new ArrayList<>(merged.values());
Ec2Service.validateNewResourceTags(effective);
return effective;
}
private List<Tag> parseTagsForResource(MultivaluedMap<String, String> p, String resourceType,
Set<String> allowedResourceTypes) {
List<Tag> tags = new ArrayList<>();
@@ -873,10 +890,12 @@ public class Ec2QueryHandler {
}
// Parse TagSpecifications. AWS applies each specification to exactly the resource
// type it names, so the interfaces RunInstances creates are tagged only by a
// ResourceType=network-interface specification - never by the instance's own tags.
// type it names, so the interfaces and volumes RunInstances creates are tagged only by a
// ResourceType=network-interface or ResourceType=volume specification - never by the
// instance's own tags.
List<Tag> instanceTags = parseTagsForResource(p, "instance");
List<Tag> networkInterfaceTags = parseTagsForResource(p, "network-interface");
List<Tag> volumeTags = parseTagsForResource(p, "volume");
// Resolved after tag parsing so reserved tags are refused before any service call.
String iamInstanceProfileArn = service.resolveLaunchIamInstanceProfileArn(
p.getFirst("IamInstanceProfile.Name"), p.getFirst("IamInstanceProfile.Arn"));
@@ -952,12 +971,10 @@ public class Ec2QueryHandler {
if (sgIds.isEmpty()) {
sgIds = new ArrayList<>(launchTemplateData.effectiveSecurityGroupIds());
}
if (!launchTemplateData.getInstanceTags().isEmpty()) {
Map<String, Tag> mergedTags = new LinkedHashMap<>();
launchTemplateData.getInstanceTags().forEach(tag -> mergedTags.put(tag.getKey(), tag));
instanceTags.forEach(tag -> mergedTags.put(tag.getKey(), tag));
instanceTags = new ArrayList<>(mergedTags.values());
}
instanceTags = withTemplateTags(launchTemplateData.getInstanceTags(), instanceTags);
networkInterfaceTags = withTemplateTags(launchTemplateData.tagsForResource("network-interface"),
networkInterfaceTags);
volumeTags = withTemplateTags(launchTemplateData.tagsForResource("volume"), volumeTags);
}
LaunchTemplateData.CapacityReservationSpecification capacitySpecification = launchTemplateData == null
@@ -1024,6 +1041,9 @@ public class Ec2QueryHandler {
service.createTags(region, eniIds, networkInterfaceTags);
}
}
if (!volumeTags.isEmpty() && !res.getLaunchVolumeIds().isEmpty()) {
service.createTags(region, res.getLaunchVolumeIds(), volumeTags);
}
XmlBuilder xml = new XmlBuilder()
.start("RunInstancesResponse", AwsNamespaces.EC2)
@@ -1291,13 +1311,7 @@ public class Ec2QueryHandler {
String overrideInstanceType, String overrideImageId,
String overrideSubnetId, String overrideAvailabilityZone,
List<Tag> fleetInstanceTags) {
Map<String, Tag> tags = new LinkedHashMap<>();
for (Tag tag : template.getInstanceTags()) {
tags.put(tag.getKey(), tag);
}
for (Tag tag : fleetInstanceTags) {
tags.put(tag.getKey(), tag);
}
List<Tag> tags = withTemplateTags(template.getInstanceTags(), fleetInstanceTags);
// The primary (device index 0) interface's subnet first; only when that names none does a
// fleet fall back, as it always has, to the first interface that names one.
LaunchTemplateData.NetworkInterface primary = template.primaryNetworkInterface();
@@ -1327,7 +1341,7 @@ public class Ec2QueryHandler {
template.effectiveAssociatePublicIpAddress(),
template.getMetadataOptions(),
template.effectiveSecurityGroupIds(),
new ArrayList<>(tags.values()),
new ArrayList<>(tags),
template.getBlockDeviceMappings(), template.getCapacityReservationSpecification());
}
@@ -0,0 +1,142 @@
package io.floci.aws.services.ec2;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.Instance;
import software.amazon.awssdk.services.ec2.model.LaunchTemplateTagSpecificationRequest;
import software.amazon.awssdk.services.ec2.model.ResourceType;
import software.amazon.awssdk.services.ec2.model.Tag;
import software.amazon.awssdk.services.ec2.model.TagSpecification;
import software.amazon.awssdk.services.ec2.model.Volume;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** RunInstances tags each resource it creates with the TagSpecification naming that resource's type. */
@QuarkusTest
class Ec2RunInstancesVolumeTagsIntegrationTest {
@Test
void eachCreatedResourceGetsTheTagsOfItsOwnType() {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "468201357924", Region.US_EAST_1)) {
Instance instance = ec2.runInstances(r -> r.imageId("ami-test").instanceType("t3.micro")
.minCount(1).maxCount(1).tagSpecifications(
spec(ResourceType.INSTANCE, "Scope", "instance"),
spec(ResourceType.VOLUME, "Scope", "volume"),
spec(ResourceType.NETWORK_INTERFACE, "Scope", "network-interface")))
.instances().getFirst();
try {
assertEquals(Map.of("Scope", "instance"), tagsOf(instance.tags()));
List<Volume> volumes = volumesOf(ec2, instance.instanceId());
assertFalse(volumes.isEmpty());
volumes.forEach(volume -> assertEquals(Map.of("Scope", "volume"), tagsOf(volume.tags())));
assertEquals(Map.of("Scope", "network-interface"), tagsOf(ec2.describeNetworkInterfaces(r -> r
.networkInterfaceIds(instance.networkInterfaces().getFirst().networkInterfaceId()))
.networkInterfaces().getFirst().tagSet()));
} finally {
ec2.terminateInstances(r -> r.instanceIds(instance.instanceId()));
}
}
}
@Test
void aLaunchTemplatesTagsReachTheirResourcesWithTheRequestsOverThem() {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "468201357925", Region.US_EAST_1)) {
String templateId = ec2.createLaunchTemplate(r -> r.launchTemplateName("volume-tags-" + UUID.randomUUID())
.launchTemplateData(d -> d.imageId("ami-test").instanceType("t3.micro").tagSpecifications(
templateSpec(ResourceType.INSTANCE, "instance"),
templateSpec(ResourceType.VOLUME, "volume"),
templateSpec(ResourceType.NETWORK_INTERFACE, "network-interface"))))
.launchTemplate().launchTemplateId();
try {
Instance instance = ec2.runInstances(r -> r.minCount(1).maxCount(1)
.launchTemplate(t -> t.launchTemplateId(templateId))
.tagSpecifications(spec(ResourceType.VOLUME, "Scope", "request-volume")))
.instances().getFirst();
try {
assertEquals(Map.of("Team", "template", "Scope", "instance"), tagsOf(instance.tags()));
volumesOf(ec2, instance.instanceId()).forEach(volume -> assertEquals(
Map.of("Team", "template", "Scope", "request-volume"), tagsOf(volume.tags())));
assertEquals(Map.of("Team", "template", "Scope", "network-interface"),
tagsOf(ec2.describeNetworkInterfaces(r -> r.networkInterfaceIds(
instance.networkInterfaces().getFirst().networkInterfaceId()))
.networkInterfaces().getFirst().tagSet()));
} finally {
ec2.terminateInstances(r -> r.instanceIds(instance.instanceId()));
}
} finally {
ec2.deleteLaunchTemplate(r -> r.launchTemplateId(templateId));
}
}
}
@Test
void aReservedVolumeTagKeyLaunchesNothing() {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "468201357926", Region.US_EAST_1)) {
assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> r.imageId("ami-test")
.instanceType("t3.micro").minCount(1).maxCount(1)
.tagSpecifications(spec(ResourceType.VOLUME, "aws:reserved", "value"))));
assertEquals(List.of(), ec2.describeInstances().reservations().stream()
.flatMap(reservation -> reservation.instances().stream()).toList());
assertEquals(List.of(), ec2.describeVolumes().volumes());
}
}
// Catches: template and request tags over the limit together only failing when the launch tags its volumes, after
// the instance and its volumes exist.
@Test
void templateAndRequestTagsOverTheLimitTogetherLaunchNothing() {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "468201357927", Region.US_EAST_1)) {
List<Tag> fiftyTags = IntStream.rangeClosed(1, 50)
.mapToObj(i -> Tag.builder().key("template-" + i).value("v").build()).toList();
String templateId = ec2.createLaunchTemplate(r -> r.launchTemplateName("volume-tag-limit-" + UUID.randomUUID())
.launchTemplateData(d -> d.imageId("ami-test").instanceType("t3.micro").tagSpecifications(
LaunchTemplateTagSpecificationRequest.builder().resourceType(ResourceType.VOLUME)
.tags(fiftyTags).build())))
.launchTemplate().launchTemplateId();
try {
Ec2Exception error = assertThrows(Ec2Exception.class, () -> ec2.runInstances(r -> r.minCount(1)
.maxCount(1).launchTemplate(t -> t.launchTemplateId(templateId))
.tagSpecifications(spec(ResourceType.VOLUME, "request", "v"))));
assertEquals("TagLimitExceeded", error.awsErrorDetails().errorCode());
assertEquals(List.of(), ec2.describeInstances().reservations().stream()
.flatMap(reservation -> reservation.instances().stream()).toList());
assertEquals(List.of(), ec2.describeVolumes().volumes());
} finally {
ec2.deleteLaunchTemplate(r -> r.launchTemplateId(templateId));
}
}
}
private static TagSpecification spec(ResourceType type, String key, String value) {
return TagSpecification.builder().resourceType(type).tags(Tag.builder().key(key).value(value).build()).build();
}
private static LaunchTemplateTagSpecificationRequest templateSpec(ResourceType type, String scope) {
return LaunchTemplateTagSpecificationRequest.builder().resourceType(type)
.tags(Tag.builder().key("Team").value("template").build(),
Tag.builder().key("Scope").value(scope).build())
.build();
}
private static List<Volume> volumesOf(Ec2Client ec2, String instanceId) {
return ec2.describeVolumes(r -> r.filters(f -> f.name("attachment.instance-id").values(instanceId))).volumes();
}
private static Map<String, String> tagsOf(List<Tag> tags) {
return tags.stream().collect(Collectors.toMap(Tag::key, Tag::value));
}
}