fix(ec2): preserve reserved tags during API and stack updates (#5611)

Signed-off-by: Andre Kurait <akurait@amazon.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-14 13:39:45 -04:00
1 parent 12c8f969af
commit 90b9d37fd2
16 files changed
+470 -110

No files matched your search

@@ -54,6 +54,8 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
List<Tag> tags = Ec2Tags.validatedTags(desiredTags);
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
CloudFormationTemplateEngine engine = ctx.engine();
String region = ctx.region();
@@ -115,22 +117,11 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
publishInstanceAttributes(r, current);
storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone);
putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn);
Ec2Tags.reconcile(ec2Service, region, current.getInstanceId(), ctx.resolveTags(props, "Tags"));
Ec2Tags.reconcile(ec2Service, region, current.getInstanceId(), desiredTags);
ReplacementCleanup.record(r, ctx, attributesBefore);
return;
}
List<Tag> tags = new ArrayList<>();
JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = engine.resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.add(new Tag(key, engine.resolve(tag.path("Value"))));
}
}
}
// The launch-time public-IP override rides on the primary network
// interface spec; absent means the subnet's MapPublicIpOnLaunch default.
Boolean associatePublicIp = null;
@@ -151,10 +151,14 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
String entityId = prior.path("entityId").asText();
if (prior.has("tags")) {
Map<String, String> priorTags = new LinkedHashMap<>();
prior.get("tags").fields().forEachRemaining(f -> priorTags.put(f.getKey(), f.getValue().asText()));
prior.get("tags").fields().forEachRemaining(f -> {
if (!Ec2Service.isAwsTagKey(f.getKey())) {
priorTags.put(f.getKey(), f.getValue().asText());
}
});
List<Tag> added = new ArrayList<>();
prior.path("appliedKeys").forEach(key -> {
if (!priorTags.containsKey(key.asText())) {
if (!Ec2Service.isAwsTagKey(key.asText()) && !priorTags.containsKey(key.asText())) {
added.add(new Tag(key.asText(), null));
}
});
@@ -279,7 +283,9 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
Map<String, String> desired = ctx.resolveTags(props, "Tags");
Map<String, String> currentTags = new LinkedHashMap<>();
for (Tag tag : current == null ? List.<Tag>of() : current) {
currentTags.put(tag.getKey(), tag.getValue());
if (!Ec2Service.isAwsTagKey(tag.getKey())) {
currentTags.put(tag.getKey(), tag.getValue());
}
}
List<String> stale = ProvisionContext.staleTagKeys(currentTags, desired);
if (reused && ctx.isUpdate() && (!stale.isEmpty() || !desired.equals(currentTags))) {
@@ -62,6 +62,8 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> desiredTags = ctx.resolveTags(props, "Tags");
Ec2Tags.validatedTags(desiredTags);
CloudFormationTemplateEngine engine = ctx.engine();
String region = ctx.region();
String groupName = ctx.resolveOptional(props, "GroupName");
@@ -104,7 +106,7 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner {
EGRESS_RULES_ATTR,
perms -> ec2Service.authorizeSecurityGroupEgress(region, sg.getGroupId(), perms),
perms -> ec2Service.revokeSecurityGroupEgress(region, sg.getGroupId(), perms));
Ec2Tags.reconcile(ec2Service, region, sg.getGroupId(), ctx.resolveTags(props, "Tags"));
Ec2Tags.reconcile(ec2Service, region, sg.getGroupId(), desiredTags);
}
@Override
@@ -18,14 +18,24 @@ final class Ec2Tags {
private Ec2Tags() {
}
static List<Tag> validatedTags(Map<String, String> desired) {
List<Tag> tags = desired.entrySet().stream()
.map(entry -> new Tag(entry.getKey(), entry.getValue())).toList();
Ec2Service.validateUserTagKeys(tags);
return tags;
}
/**
* Brings a resource's tags to {@code desired}: removes the keys AWS currently has that the
* template no longer declares, then creates or overwrites the declared ones.
*/
static void reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
List<Tag> add = validatedTags(desired);
Map<String, String> current = new LinkedHashMap<>();
for (Map<String, String> entry : ec2Service.describeTags(region, Map.of("resource-id", List.of(resourceId)))) {
current.put(entry.get("key"), entry.get("value"));
if (!Ec2Service.isAwsTagKey(entry.get("key"))) {
current.put(entry.get("key"), entry.get("value"));
}
}
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
if (!stale.isEmpty()) {
@@ -35,11 +45,7 @@ final class Ec2Tags {
}
ec2Service.deleteTags(region, List.of(resourceId), remove);
}
if (!desired.isEmpty()) {
List<Tag> add = new ArrayList<>();
for (Map.Entry<String, String> entry : desired.entrySet()) {
add.add(new Tag(entry.getKey(), entry.getValue()));
}
if (!add.isEmpty()) {
ec2Service.createTags(region, List.of(resourceId), add);
}
}
@@ -592,6 +592,13 @@ public class Ec2QueryHandler {
}
}
}
if (tags.stream().anyMatch(tag -> Ec2Service.isAwsTagKey(tag.getKey()))) {
String code = switch (resourceType) {
case "vpc", "subnet", "security-group-rule", "spot-instances-request" -> "InvalidParameter";
default -> "InvalidParameterValue";
};
throw new AwsException(code, "Tag keys starting with 'aws:' are reserved for internal use", 400);
}
return tags;
}
@@ -618,8 +625,7 @@ public class Ec2QueryHandler {
// Apply tags supplied inline on a create call (TagSpecification) to the resource, so
// they round-trip on the next Describe* — otherwise the provider sees phantom tag drift.
private void applyResourceTags(MultivaluedMap<String, String> p, String region, String resourceType, String resourceId) {
List<Tag> tagList = parseTagsForResource(p, resourceType);
private void applyResourceTags(List<Tag> tagList, String region, String resourceId) {
if (!tagList.isEmpty()) {
service.createTags(region, List.of(resourceId), tagList);
}
@@ -627,9 +633,7 @@ public class Ec2QueryHandler {
// Each rule gets its own copy so mutating one rule's tag list can never leak into the
// others authorized in the same batch, and the copy also feeds the response XML.
private void applySecurityGroupRuleTags(MultivaluedMap<String, String> p, String region,
List<SecurityGroupRule> rules) {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
private void applySecurityGroupRuleTags(List<Tag> ruleTags, String region, List<SecurityGroupRule> rules) {
if (ruleTags.isEmpty()) {
return;
}
@@ -782,25 +786,8 @@ 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.
List<Tag> instanceTags = new ArrayList<>();
List<Tag> networkInterfaceTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
List<Tag> target = switch (resType) {
case "instance" -> instanceTags;
case "network-interface" -> networkInterfaceTags;
default -> null;
};
if (target != null) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
target.add(creationTag(k, v));
}
}
}
List<Tag> instanceTags = parseTagsForResource(p, "instance");
List<Tag> networkInterfaceTags = parseTagsForResource(p, "network-interface");
// Absent fields stay null so the launch default, or the launch template's value, applies.
LaunchTemplateData.MetadataOptions metadataOptions = parseMetadataOptions(p, "MetadataOptions.");
@@ -1565,23 +1552,9 @@ public class Ec2QueryHandler {
private Response handleCreateVpc(MultivaluedMap<String, String> p, String region) {
String cidrBlock = p.getFirst("CidrBlock");
boolean amazonProvidedIpv6 = "true".equalsIgnoreCase(p.getFirst("AmazonProvidedIpv6CidrBlock"));
List<Tag> vpcTags = parseTagsForResource(p, "vpc");
Vpc vpc = service.createVpc(region, cidrBlock, false, amazonProvidedIpv6, p.getFirst("InstanceTenancy"));
List<Tag> vpcTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
if ("vpc".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
vpcTags.add(creationTag(k, v));
}
}
}
if (!vpcTags.isEmpty()) {
service.createTags(region, List.of(vpc.getVpcId()), vpcTags);
}
applyResourceTags(vpcTags, region, vpc.getVpcId());
XmlBuilder xml = new XmlBuilder()
.start("CreateVpcResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3148,11 +3121,12 @@ public class Ec2QueryHandler {
// ─── Security Group handlers ───────────────────────────────────────────────
private Response handleCreateSecurityGroup(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "security-group");
String groupName = requireParameter(p, "GroupName");
String description = requireParameter(p, "GroupDescription");
String vpcId = p.getFirst("VpcId");
SecurityGroup sg = service.createSecurityGroup(region, groupName, description, vpcId);
applyResourceTags(p, region, "security-group", sg.getGroupId());
applyResourceTags(resourceTags, region, sg.getGroupId());
XmlBuilder xml = new XmlBuilder()
.start("CreateSecurityGroupResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3219,10 +3193,11 @@ public class Ec2QueryHandler {
}
private Response handleAuthorizeSecurityGroupIngress(MultivaluedMap<String, String> p, String region) {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<SecurityGroupRule> rules = service.authorizeSecurityGroupIngress(region, groupId, perms);
applySecurityGroupRuleTags(p, region, rules);
applySecurityGroupRuleTags(ruleTags, region, rules);
XmlBuilder xml = new XmlBuilder()
.start("AuthorizeSecurityGroupIngressResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3236,10 +3211,11 @@ public class Ec2QueryHandler {
}
private Response handleAuthorizeSecurityGroupEgress(MultivaluedMap<String, String> p, String region) {
List<Tag> ruleTags = parseTagsForResource(p, "security-group-rule");
String groupId = p.getFirst("GroupId");
List<IpPermission> perms = parseIpPermissions(p, "IpPermissions");
List<SecurityGroupRule> rules = service.authorizeSecurityGroupEgress(region, groupId, perms);
applySecurityGroupRuleTags(p, region, rules);
applySecurityGroupRuleTags(ruleTags, region, rules);
XmlBuilder xml = new XmlBuilder()
.start("AuthorizeSecurityGroupEgressResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3711,8 +3687,9 @@ public class Ec2QueryHandler {
// ─── Internet Gateway handlers ────────────────────────────────────────────
private Response handleCreateInternetGateway(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "internet-gateway");
InternetGateway igw = service.createInternetGateway(region);
applyResourceTags(p, region, "internet-gateway", igw.getInternetGatewayId());
applyResourceTags(resourceTags, region, igw.getInternetGatewayId());
XmlBuilder xml = new XmlBuilder()
.start("CreateInternetGatewayResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -3754,9 +3731,10 @@ public class Ec2QueryHandler {
// ─── Route Table handlers ─────────────────────────────────────────────────
private Response handleCreateRouteTable(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "route-table");
String vpcId = p.getFirst("VpcId");
RouteTable rt = service.createRouteTable(region, vpcId);
applyResourceTags(p, region, "route-table", rt.getRouteTableId());
applyResourceTags(resourceTags, region, rt.getRouteTableId());
XmlBuilder xml = new XmlBuilder()
.start("CreateRouteTableResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -4094,6 +4072,7 @@ public class Ec2QueryHandler {
// ─── Capacity Reservation handlers ────────────────────────────────────────
private Response handleCreateCapacityReservation(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "capacity-reservation");
CapacityReservation reservation = service.createCapacityReservation(
region,
p.getFirst("InstanceType"),
@@ -4109,7 +4088,7 @@ public class Ec2QueryHandler {
p.getFirst("InstanceMatchCriteria"),
p.getFirst("OutpostArn"),
p.getFirst("PlacementGroupArn"));
applyResourceTags(p, region, "capacity-reservation", reservation.getCapacityReservationId());
applyResourceTags(resourceTags, region, reservation.getCapacityReservationId());
XmlBuilder xml = new XmlBuilder()
.start("CreateCapacityReservationResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -4178,6 +4157,7 @@ public class Ec2QueryHandler {
// ─── Dedicated Host handlers ──────────────────────────────────────────────
private Response handleAllocateHosts(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "dedicated-host");
List<String> assetIds = getList(p, "AssetId");
List<Host> allocated = service.allocateHosts(
region,
@@ -4195,7 +4175,7 @@ public class Ec2QueryHandler {
.elem("requestId", UUID.randomUUID().toString())
.start("hostIdSet");
for (Host host : allocated) {
applyResourceTags(p, region, "dedicated-host", host.getHostId());
applyResourceTags(resourceTags, region, host.getHostId());
xml.elem("item", host.getHostId());
}
xml.end("hostIdSet").end("AllocateHostsResponse");
@@ -4312,8 +4292,9 @@ public class Ec2QueryHandler {
// ─── Elastic IP handlers ──────────────────────────────────────────────────
private Response handleAllocateAddress(MultivaluedMap<String, String> p, String region) {
List<Tag> resourceTags = parseTagsForResource(p, "elastic-ip");
Address addr = service.allocateAddress(region);
applyResourceTags(p, region, "elastic-ip", addr.getAllocationId());
applyResourceTags(resourceTags, region, addr.getAllocationId());
XmlBuilder xml = new XmlBuilder()
.start("AllocateAddressResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
@@ -5801,6 +5782,11 @@ public class Ec2QueryHandler {
if (key == null) {
break;
}
if (key.startsWith("aws:")) {
throw new AwsException("InvalidTagKey.Malformed",
"The tag key ‘" + key + "’ is not valid. "
+ "Tag keys starting with 'aws:' are reserved for internal use.", 400);
}
tagList.add(creationTag(key, p.getFirst(base + ".Tag." + j + ".Value")));
}
specs.add(new LaunchTemplateData.TagSpecification(resourceType, tagList));
@@ -6018,19 +6004,7 @@ public class Ec2QueryHandler {
String snapshotId = p.getFirst("SnapshotId");
List<Tag> volumeTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
if ("volume".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
volumeTags.add(creationTag(k, v));
}
}
}
List<Tag> volumeTags = parseTagsForResource(p, "volume");
Volume vol = service.createVolume(region, availabilityZone, volumeType, size,
encrypted, iops, throughput, snapshotId, volumeTags);
@@ -6287,28 +6261,8 @@ public class Ec2QueryHandler {
String userData = Ec2UserDataDecoder.decode(userDataEncoded);
String iamInstanceProfileArn = p.getFirst("LaunchSpecification.IamInstanceProfile.Arn");
// Parse TagSpecifications
List<Tag> spotRequestTags = new ArrayList<>();
List<Tag> instanceTags = new ArrayList<>();
for (int i = 1; ; i++) {
String resType = p.getFirst("TagSpecification." + i + ".ResourceType");
if (resType == null) break;
if ("spot-instances-request".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
spotRequestTags.add(creationTag(k, v));
}
} else if ("instance".equals(resType)) {
for (int j = 1; ; j++) {
String k = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Key");
if (k == null) break;
String v = p.getFirst("TagSpecification." + i + ".Tag." + j + ".Value");
instanceTags.add(creationTag(k, v));
}
}
}
List<Tag> spotRequestTags = parseTagsForResource(p, "spot-instances-request");
List<Tag> instanceTags = parseTagsForResource(p, "instance");
List<SpotInstanceRequest> requests = service.requestSpotInstances(region, spotPrice, instanceCount,
type, productDescription, imageId, instanceType, keyName, subnetId, securityGroupIds, userData, iamInstanceProfileArn,
@@ -7785,6 +7785,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// ─── Tags ──────────────────────────────────────────────────────────────────
public void createTags(String region, List<String> resourceIds, List<Tag> tagList) {
validateUserTagKeys(tagList);
createSystemTags(region, resourceIds, tagList);
}
/** Service-owned tags, separate from the public EC2 CreateTags operation. */
public void createSystemTags(String region, List<String> resourceIds, List<Tag> tagList) {
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
withTopologyLockIfNeeded(region, resourceId, () -> {
@@ -7822,6 +7828,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
public void deleteTags(String region, List<String> resourceIds, List<Tag> tagList) {
validateUserTagKeys(tagList);
ensureDefaultResources(region);
for (String resourceId : resourceIds) {
withTopologyLockIfNeeded(region, resourceId, () -> {
@@ -7832,6 +7839,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
});
if (stored != null) {
List<Tag> existing = new ArrayList<>(stored);
if (tagList.isEmpty()) {
existing.removeIf(tag -> !isAwsTagKey(tag.getKey()));
}
for (Tag tag : tagList) {
existing.removeIf(t -> t.getKey().equals(tag.getKey())
&& (tag.getValue() == null || tag.getValue().equals(t.getValue())));
@@ -7844,6 +7854,20 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
public static void validateUserTagKeys(List<Tag> tagList) {
for (Tag tag : tagList) {
if (isAwsTagKey(tag.getKey())) {
throw new AwsException("InvalidParameterValue",
"Value ( " + tag.getKey() + " ) for parameter key is invalid. "
+ "Tag keys starting with 'aws:' are reserved for internal use", 400);
}
}
}
public static boolean isAwsTagKey(String key) {
return key != null && key.toLowerCase(Locale.ROOT).startsWith("aws:");
}
private void updateResourceTags(String region, String resourceId, List<Tag> tagList) {
String storeKey = key(region, resourceId);
Instance inst = instances.get(storeKey).orElse(null);
@@ -444,7 +444,7 @@ public class EksService implements TagHandler, ResourceProvider, Ec2InstanceLaun
new Tag("kubernetes.io/cluster/" + clusterName, "owned"),
new Tag("aws:eks:cluster-name", clusterName)
);
ec2Service.createTags(region, List.of(sg.getGroupId()), tags);
ec2Service.createSystemTags(region, List.of(sg.getGroupId()), tags);
UserIdGroupPair selfPair = new UserIdGroupPair();
selfPair.setGroupId(sg.getGroupId());