fix(cloudformation): keep tags added outside the stack on EC2 VPCs, security groups and instances (#7534)

This commit is contained in:
Ronald Li 🛠️ authored and GitHub committed 2026-11-04 18:17:51 -04:00
1 parent b35e51374c
commit cfbf86b8a1
11 files changed
+428 -160

No files matched your search

@@ -0,0 +1,141 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.Output;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Tag;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The {@code Tags} of an {@code AWS::EC2::VPC}, {@code AWS::EC2::SecurityGroup} and
* {@code AWS::EC2::Instance} through the AWS SDK. A stack update changes only the keys the stack
* wrote: AWS keeps a tag added to the resource through EC2.
*/
@QuarkusTest
class CloudFormationEc2OwnedTagsIntegrationTest {
private static final List<String> OUTPUTS = List.of("VpcId", "GroupId", "InstanceId");
private final String stackName = "cfn-ec2-owned-tags-" + UUID.randomUUID();
private CloudFormationClient cfn;
private Ec2Client ec2;
private boolean stackCreated;
@BeforeEach
void clients() {
cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1);
ec2 = AwsTestClients.create(Ec2Client.builder(), "test", Region.US_EAST_1);
}
@AfterEach
void deleteStack() {
try {
if (stackCreated) {
cfn.deleteStack(request -> request.stackName(stackName));
}
} finally {
ec2.close();
cfn.close();
}
}
@Test
void droppingTheTemplatesTagsKeepsATagAddedThroughEc2() {
Map<String, String> ids = createStackWithExternalTags();
cfn.updateStack(request -> request.stackName(stackName).templateBody(template(false)));
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
for (String output : OUTPUTS) {
assertEquals(Map.of("external", "preserve"), tags(ids.get(output)), output);
}
assertEquals(ids, outputs(), "every resource is updated in place");
}
@Test
void aTagKeyFromAChangedParameterReplacesOnlyTheOldKey() {
Map<String, String> ids = createStackWithExternalTags();
cfn.updateStack(request -> request.stackName(stackName).templateBody(template(true))
.parameters(parameter -> parameter.parameterKey("TagKey").parameterValue("owner")));
CfnStackWaits.awaitStatus(cfn, stackName, "UPDATE_COMPLETE");
// Re-resolving the previous template would read owner too and leave team behind.
for (String output : OUTPUTS) {
assertEquals(Map.of("owner", "core", "external", "preserve"), tags(ids.get(output)), output);
}
}
/** A stack whose VPC, group and instance carry the template's {@code team=core} and an EC2-added tag. */
private Map<String, String> createStackWithExternalTags() {
cfn.createStack(request -> request.stackName(stackName).templateBody(template(true)));
stackCreated = true;
CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
Map<String, String> ids = outputs();
for (String output : OUTPUTS) {
String id = ids.get(output);
assertEquals(Map.of("team", "core"), tags(id), output);
ec2.createTags(request -> request.resources(id)
.tags(Tag.builder().key("external").value("preserve").build()));
}
return ids;
}
private static String template(boolean tagged) {
String tags = tagged ? """
,
"Tags": [{"Key": {"Ref": "TagKey"}, "Value": "core"}]""" : "";
return """
{
"Parameters": {"TagKey": {"Type": "String", "Default": "team"}},
"Resources": {
"Vpc": {"Type": "AWS::EC2::VPC", "Properties": {
"CidrBlock": "10.41.0.0/16"%1$s
}},
"Group": {"Type": "AWS::EC2::SecurityGroup", "Properties": {
"GroupDescription": "owned tags",
"VpcId": {"Ref": "Vpc"}%1$s
}},
"Server": {"Type": "AWS::EC2::Instance", "Properties": {
"ImageId": "ami-12345678",
"InstanceType": "t3.micro"%1$s
}}
},
"Outputs": {
"VpcId": {"Value": {"Ref": "Vpc"}},
"GroupId": {"Value": {"Ref": "Group"}},
"InstanceId": {"Value": {"Ref": "Server"}}
}
}
""".formatted(tags);
}
private Map<String, String> outputs() {
Map<String, String> outputs = new TreeMap<>();
for (Output output : cfn.describeStacks(request -> request.stackName(stackName)).stacks().getFirst()
.outputs()) {
outputs.put(output.outputKey(), output.outputValue());
}
return outputs;
}
private Map<String, String> tags(String resourceId) {
Map<String, String> tags = new TreeMap<>();
ec2.describeTags(request -> request.filters(filter -> filter.name("resource-id").values(resourceId)))
.tags().forEach(tag -> tags.put(tag.key(), tag.value()));
return tags;
}
}
@@ -80,7 +80,8 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("i-1", r.getPhysicalId());
assertEquals(Set.of("InstanceId", "PrivateIp", "PublicIp", "PrivateDnsName", "PublicDnsName",
"AvailabilityZone", "VpcId", "State.Code", "State.Name"), r.getAttributes().keySet());
"AvailabilityZone", "VpcId", "State.Code", "State.Name",
Ec2InstanceCfnProvisioner.DECLARED_TAG_KEYS_ATTR), r.getAttributes().keySet());
assertEquals("10.0.0.5", r.getAttributes().get("PrivateIp"));
assertEquals("us-east-1a", r.getAttributes().get("AvailabilityZone"));
assertEquals("vpc-1", r.getAttributes().get("VpcId"));
@@ -119,7 +120,8 @@ class Ec2InstanceCfnProvisionerTest {
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx());
assertEquals(Set.of("InstanceId"), r.getAttributes().keySet());
assertEquals(Set.of("InstanceId", Ec2InstanceCfnProvisioner.DECLARED_TAG_KEYS_ATTR),
r.getAttributes().keySet());
}
@Test
@@ -550,20 +552,21 @@ class Ec2InstanceCfnProvisionerTest {
}
@Test
void reusedInstanceReconcilesTagsInPlace() throws Exception {
void reusedInstanceRemovesOnlyTheTagKeysItOwns() throws Exception {
Instance i1 = new Instance();
i1.setInstanceId("i-1");
i1.setImageId("ami-1");
stubLaunch(i1);
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "Tags": [{"Key": "env", "Value": "prod"}]}
{"ImageId": "ami-1", "Tags": [{"Key": "env", "Value": "prod"}, {"Key": "old", "Value": "stale"}]}
"""), ctx(null));
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
.thenReturn(List.of(reservationOf(i1)));
// team was added through EC2, outside the stack, so AWS keeps it.
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(
tagEntry("i-1", "env", "prod"), tagEntry("i-1", "old", "stale"),
tagEntry("i-1", "env", "prod"), tagEntry("i-1", "old", "stale"), tagEntry("i-1", "team", "core"),
tagEntry("i-1", "aws:autoscaling:groupName", "group"),
tagEntry("i-1", "AWS:cloudformation:stack-id", "stack")));
provisioner.provision(r, props("""
@@ -575,6 +578,7 @@ class Ec2InstanceCfnProvisionerTest {
verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("i-1")), removed.capture());
assertEquals(1, removed.getValue().size());
assertEquals("old", removed.getValue().get(0).getKey());
assertEquals("[\"env\"]", r.getAttributes().get(Ec2InstanceCfnProvisioner.DECLARED_TAG_KEYS_ATTR));
}
@Test
@@ -700,7 +704,7 @@ class Ec2InstanceCfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("i-1", r.getPhysicalId());
assertEquals(Map.of("__FlociDeclaredMetadataOptions", "HttpTokens"), declarations(r));
assertEquals(Map.of("__FlociDeclaredMetadataOptions", "HttpTokens", "__FlociDeclaredTagKeys", "[]"), declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorDeclarations"));
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx("i-1"));
assertEquals("i-1", r.getPhysicalId());
@@ -724,7 +728,7 @@ class Ec2InstanceCfnProvisionerTest {
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals("i-1", r.getPhysicalId());
assertEquals(Map.of("__FlociDeclaredMetadataOptions", "HttpTokens"), declarations(r));
assertEquals(Map.of("__FlociDeclaredMetadataOptions", "HttpTokens", "__FlociDeclaredTagKeys", "[]"), declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorDeclarations"));
}
@@ -740,7 +744,7 @@ class Ec2InstanceCfnProvisionerTest {
.thenThrow(new AwsException("InternalError", "terminate failed", 500))
.thenThrow(new AwsException("InternalError", "terminate failed", 500))
.thenReturn(List.of());
Map<String, String> declared = Map.of("__FlociDeclaredMetadataOptions", "HttpTokens");
Map<String, String> declared = Map.of("__FlociDeclaredMetadataOptions", "HttpTokens", "__FlociDeclaredTagKeys", "[]");
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
@@ -1030,7 +1034,7 @@ class Ec2InstanceCfnProvisionerTest {
first.setMetadataOptions(applied);
provisioner.provision(r, props("{\"ImageId\": \"ami-2\"}"), ctx(first.getInstanceId()));
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals(Map.of(), declarations(r));
assertEquals(Map.of(Ec2InstanceCfnProvisioner.DECLARED_TAG_KEYS_ATTR, "[]"), declarations(r));
return r;
}
@@ -1117,7 +1121,7 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void tagReconciliationValidatesBeforeDeletingStaleTags() {
assertThrows(AwsException.class, () -> Ec2Tags.reconcile(ec2, "us-east-1", "i-1",
assertThrows(AwsException.class, () -> Ec2Tags.reconcileOwned(ec2, "us-east-1", "i-1", Set.of("env"),
Map.of("env", "new", "aWs:reserved", "invalid")));
verifyNoInteractions(ec2);
@@ -58,7 +58,8 @@ class Ec2SecurityGroupCfnProvisionerTest {
"""), ctx(null));
assertEquals("sg-1", r.getPhysicalId());
assertEquals(Set.of("GroupId", "Id", "VpcId"), r.getAttributes().keySet());
assertEquals(Set.of("GroupId", "Id", "VpcId", Ec2SecurityGroupCfnProvisioner.TAG_KEYS_ATTR),
r.getAttributes().keySet());
assertEquals("sg-1", r.getAttributes().get("GroupId"));
assertEquals("sg-1", r.getAttributes().get("Id"));
assertEquals("vpc-1", r.getAttributes().get("VpcId"));
@@ -250,13 +251,15 @@ class Ec2SecurityGroupCfnProvisionerTest {
}
@Test
void updateRemovesAndReconcilesTags() throws Exception {
void updateRemovesOnlyTheTagKeysItOwns() throws Exception {
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
.thenReturn(List.of(group("sg-1", "web", "web tier", "vpc-1")));
// team was added through EC2, outside the stack, so AWS keeps it.
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(
tagEntry("sg-1", "env", "prod"), tagEntry("sg-1", "old", "stale")));
tagEntry("sg-1", "env", "prod"), tagEntry("sg-1", "old", "stale"), tagEntry("sg-1", "team", "core")));
StackResource r = resource("WebSg");
r.setPhysicalId("sg-1");
r.getAttributes().put(Ec2SecurityGroupCfnProvisioner.TAG_KEYS_ATTR, "[\"env\",\"old\"]");
provisioner.provision(r, props("""
{"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1",
@@ -268,6 +271,30 @@ class Ec2SecurityGroupCfnProvisionerTest {
verify(ec2).deleteTags(eq("us-east-1"), eq(List.of("sg-1")), removed.capture());
assertEquals(1, removed.getValue().size());
assertEquals("old", removed.getValue().get(0).getKey());
assertEquals("[\"env\"]", r.getAttributes().get(Ec2SecurityGroupCfnProvisioner.TAG_KEYS_ATTR));
}
@Test
void aDeploymentWithoutTagsOwnsNoKeysEvenIfThePreviousTemplateNowResolvesSome() throws Exception {
when(ec2.describeSecurityGroups("us-east-1", List.of("sg-1"), List.of(), Map.of()))
.thenReturn(List.of(group("sg-1", "web", "web tier", "vpc-1")));
when(ec2.describeTags(eq("us-east-1"), any())).thenReturn(List.of(tagEntry("sg-1", "external", "x")));
StackResource r = resource("WebSg");
r.setPhysicalId("sg-1");
String untagged = """
{"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1"}
""";
provisioner.provision(r, props(untagged), ctx("sg-1"));
assertEquals("[]", r.getAttributes().get(Ec2SecurityGroupCfnProvisioner.TAG_KEYS_ATTR));
// An Fn::If over the next update's conditions can make the previous Tags resolve to a key
// that deployment never wrote; the recorded empty set keeps it from being removed.
provisioner.provision(r, props(untagged), ctx("sg-1", props("""
{"GroupName": "web", "GroupDescription": "web tier", "VpcId": "vpc-1",
"Tags": [{"Key": "external", "Value": "x"}]}
""")));
verify(ec2, never()).deleteTags(anyString(), anyList(), anyList());
}
@Test
@@ -185,14 +185,16 @@ class Ec2VpcCfnProvisionerTest {
}
@Test
void anUnchangedVpcIsReusedAndItsTagSetReplaced() {
void anUnchangedVpcIsReusedAndOnlyTheTagKeysItOwnsAreReconciled() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
// external was added through EC2, outside the stack, so AWS keeps it.
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing")))).thenReturn(List.of(
Map.of("key", "Name", "value", "old"),
Map.of("key", "stale", "value", "x")));
Map.of("key", "stale", "value", "x"),
Map.of("key", "external", "value", "keep")));
StackResource r = provision("vpc-existing", """
StackResource r = provision("vpc-existing", Map.of(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR, "[\"Name\",\"stale\"]"), """
{"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "new"}]}""");
verify(ec2, never()).createVpc(anyString(), anyString(), anyBoolean(), anyBoolean(), any());
@@ -201,6 +203,7 @@ class Ec2VpcCfnProvisionerTest {
"reusing must keep the id every subnet and route table already references");
verify(ec2).deleteTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("stale=x")));
verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=new")));
assertEquals("[\"Name\"]", r.getAttributes().get(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR));
}
@Test
@@ -291,6 +294,43 @@ class Ec2VpcCfnProvisionerTest {
assertFalse(provisioner.hasReplacementUpdate(r), "nothing is owed a delete once the prior VPC stands again");
}
@Test
void aRolledBackReplacementPutsBackTheTagKeysThePriorVpcOwns() {
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of()))
.thenReturn(List.of(vpc("vpc-existing", "10.0.0.0/16")));
stubCreate(vpc("vpc-replaced", "10.1.0.0/16"));
StackResource r = provision("vpc-existing", Map.of("VpcId", "vpc-existing", Ec2VpcCfnProvisioner.TAG_KEYS_ATTR, "[\"team\"]"), """
{"CidrBlock": "10.1.0.0/16", "Tags": [{"Key": "owner", "Value": "platform"}]}""");
assertEquals("[\"owner\"]", r.getAttributes().get(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR));
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("vpc-existing", r.getPhysicalId());
assertEquals("[\"team\"]", r.getAttributes().get(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR),
"the prior VPC's next update must remove only the keys its own deployment wrote");
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void anOwnershipChangeAloneIsSnapshottedAndRolledBack() {
Vpc existing = vpc("vpc-existing", "10.0.0.0/16");
existing.setEnableDnsSupport(true);
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));
// team already holds the value the template now declares, so only the ownership changes.
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing"))))
.thenReturn(List.of(Map.of("key", "team", "value", "core")));
StackResource r = provision("vpc-existing", """
{"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "team", "Value": "core"}]}""");
assertEquals("[\"team\"]", r.getAttributes().get(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR));
assertTrue(provisioner.rollbackUpdate(r));
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR),
"a rollback hands team back to whoever tagged it, so a later drop keeps it");
verify(ec2, never()).deleteTags(any(), any(), any());
}
@Test
void anInPlaceChangeIsRolledBackToThePriorDnsAttributesTagsAndTenancy() {
Vpc existing = vpc("vpc-existing", "10.0.0.0/16");
@@ -299,11 +339,13 @@ class Ec2VpcCfnProvisionerTest {
existing.setEnableDnsHostnames(false);
when(ec2.describeVpcs(REGION, List.of("vpc-existing"), Map.of())).thenReturn(List.of(existing));
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing"))))
.thenReturn(List.of(Map.of("key", "Name", "value", "old"), Map.of("key", "team", "value", "net")))
.thenReturn(List.of(Map.of("key", "Name", "value", "old"), Map.of("key", "team", "value", "net"),
Map.of("key", "external", "value", "keep")))
// The snapshot reads the prior set once; every later read sees what the update wrote.
.thenReturn(List.of(Map.of("key", "Name", "value", "new"), Map.of("key", "env", "value", "test")));
.thenReturn(List.of(Map.of("key", "Name", "value", "new"), Map.of("key", "env", "value", "test"),
Map.of("key", "external", "value", "keep")));
StackResource r = provision("vpc-existing", """
StackResource r = provision("vpc-existing", Map.of(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR, "[\"Name\",\"team\"]"), """
{"CidrBlock": "10.0.0.0/16", "InstanceTenancy": "default", "EnableDnsHostnames": true,
"Tags": [{"Key": "Name", "Value": "new"}, {"Key": "env", "Value": "test"}]}""");
assertTrue(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR), "the prior state is snapshotted");
@@ -317,6 +359,9 @@ class Ec2VpcCfnProvisionerTest {
verify(ec2).deleteTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("env=test")));
verify(ec2).createTags(eq(REGION), eq(List.of("vpc-existing")), argThat(tags("Name=old", "team=net")));
verify(ec2).modifyVpcTenancy(REGION, "vpc-existing", "dedicated");
verify(ec2, never()).deleteTags(any(), any(),
argThat(actual -> actual.stream().anyMatch(tag -> "external".equals(tag.getKey()))));
assertEquals("[\"Name\",\"team\"]", r.getAttributes().get(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR), "the ownership record goes back too");
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@@ -349,7 +394,7 @@ class Ec2VpcCfnProvisionerTest {
when(ec2.describeTags(REGION, Map.of("resource-id", List.of("vpc-existing"))))
.thenReturn(List.of(Map.of("key", "Name", "value", "same")));
StackResource r = provision("vpc-existing", """
StackResource r = provision("vpc-existing", Map.of(Ec2VpcCfnProvisioner.TAG_KEYS_ATTR, "[\"Name\"]"), """
{"CidrBlock": "10.0.0.0/16", "Tags": [{"Key": "Name", "Value": "same"}]}""");
assertFalse(r.getAttributes().containsKey(Ec2VpcCfnProvisioner.IN_PLACE_PRIOR_ATTR));