fix(cloudformation): clear EC2 network tags and properties the new template drops (#7124)

A property the previous template declared and the new one drops is now
cleared on update for the EC2 network types: Tags on Subnet,
InternetGateway, RouteTable, NatGateway, EIP and PrefixList, and
MapPublicIpOnLaunch on Subnet, which goes back to false. A property the
stack never declared keeps what was set outside it. A failed update puts
the cleared tags and the flag back from the existing in-place snapshot.

Refs #6606
This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-10-31 16:46:29 -04:00
1 parent ad9de3022a
commit f55948cbcc
4 files changed
+199 -25

No files matched your search

+5 -1
View File
@@ -715,7 +715,11 @@ their create default (`XrayEnabled`, `AdditionalAuthenticationProviders`, a func
a resolver's `Kind`). Not cleared: the identifiers, `Tags` and `EnvironmentVariables`, which the
provisioner already drives to the template, required members (`AuthenticationType`, `Type`, a function's
`DataSourceName`), create-only members, an API key's `Expires`, a GraphQL API's `ApiType` and
`Visibility`, and a UNIT resolver's `DataSourceName`. Other services follow
`Visibility`, and a UNIT resolver's `DataSourceName`.
On the EC2 networking types (`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`),
a `Tags` property the previous template declared and the new one drops is cleared on `UpdateStack`, and
`Subnet`'s `MapPublicIpOnLaunch` goes back to `false`. A resource whose templates never declared `Tags` keeps the ones set outside the stack. Other services follow
[#6606](https://github.com/floci-io/floci/issues/6606).
## Template URLs
@@ -305,10 +305,12 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
/**
* Reconciles the template's {@code Tags} onto an entity: keys the template dropped are removed,
* the rest written. A template without a Tags property leaves whatever the entity carries.
* the rest written. A template without a Tags property clears them when the previous template
* declared Tags, and leaves whatever the entity carries when no template ever did.
*/
private void applyTags(StackResource r, boolean reused, String resourceId, List<Tag> current, JsonNode props, ProvisionContext ctx) {
if (props == null || !props.has("Tags")) {
boolean declared = props != null && props.has("Tags");
if (!declared && !ctx.droppedProperties(props).contains("Tags")) {
return;
}
Map<String, String> desired = ctx.resolveTags(props, "Tags");
@@ -465,13 +467,16 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
CfnRollback.guarded(r, ctx, !reuse, () -> ec2Service.deleteSubnet(ctx.region(), subnet.getSubnetId()),
() -> undoInPlace(r), () -> {
applyTags(r, reuse, subnet.getSubnetId(), reuse ? existing.getTags() : List.of(), props, ctx);
if (mapPublicIpOnLaunch != null) {
if (reuse && ctx.isUpdate() && existing.isMapPublicIpOnLaunch() != Boolean.parseBoolean(mapPublicIpOnLaunch)) {
// A flag the previous template declared and this one drops goes back to false, the launch default.
String desiredMapPublicIp = mapPublicIpOnLaunch == null && reuse && ctx.droppedProperties(props).contains("MapPublicIpOnLaunch")
? "false" : mapPublicIpOnLaunch;
if (desiredMapPublicIp != null) {
if (reuse && ctx.isUpdate() && existing.isMapPublicIpOnLaunch() != Boolean.parseBoolean(desiredMapPublicIp)) {
ObjectNode prior = inPlacePrior(r, subnet.getSubnetId(), ctx);
prior.put("mapPublicIpOnLaunch", String.valueOf(existing.isMapPublicIpOnLaunch()));
writeInPlacePrior(r, prior);
}
ec2Service.modifySubnetAttribute(ctx.region(), subnet.getSubnetId(), "mapPublicIpOnLaunch", mapPublicIpOnLaunch);
ec2Service.modifySubnetAttribute(ctx.region(), subnet.getSubnetId(), "mapPublicIpOnLaunch", desiredMapPublicIp);
}
});
}
@@ -719,7 +724,7 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
*
* <p>Entries and Tags are each brought to the template only when it declares them, or the
* previous template did: a template that drops them clears them, and entries or tags no template
* ever declared are left alone. The other types here keep their tags when Tags is dropped.
* ever declared are left alone.
*/
private void updatePrefixList(StackResource r, ManagedPrefixList existing, String name, String family,
int maxEntries, List<PrefixListEntry> entries, JsonNode props, ProvisionContext ctx) {
@@ -755,20 +760,12 @@ public class Ec2NetworkCfnProvisioner implements CfnResourceProvisioner {
}
writeInPlacePrior(r, prior);
}
JsonNode desiredTags = !props.has("Tags") && ctx.previouslyDeclared("Tags") ? untagged(props) : props;
CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> {
applyTags(r, true, prefixListId, existing.getTags(), desiredTags, ctx);
applyTags(r, true, prefixListId, existing.getTags(), props, ctx);
modifyPrefixList(ctx.region(), existing, name, maxEntries, changes);
});
}
/** {@code props} with an empty Tags list, which removes the tags a previous template declared. */
private static JsonNode untagged(JsonNode props) {
ObjectNode copy = props.deepCopy();
copy.putArray("Tags");
return copy;
}
/**
* Gives a prefix list {@code name} and {@code maxEntries} and applies {@code changes}, or does
* nothing when none of them changes it. EC2 refuses a request that removes and adds the same CIDR,
@@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -88,6 +89,53 @@ class CloudFormationEc2NetworkingIntegrationTest {
ec2("DeleteVpc", Map.of("VpcId", vpcId));
}
private static final String REMOVAL_STACK = "ec2-networking-removal-it";
/** A subnet, a route table and an internet gateway that declare their Tags, plus a route table that never does. */
private static String removalTemplate(String vpcId, boolean declared) {
String subnetProps = declared ? ", \"MapPublicIpOnLaunch\": true, \"Tags\": [{\"Key\": \"team\", \"Value\": \"subnet-net\"}]" : "";
String rtTags = declared ? ", \"Tags\": [{\"Key\": \"env\", \"Value\": \"rt-marker\"}]" : "";
String igwProps = declared ? "\"Properties\": {\"Tags\": [{\"Key\": \"env\", \"Value\": \"igw-marker\"}]}" : "\"Properties\": {}";
return """
{
"Resources": {
"Subnet": {"Type": "AWS::EC2::Subnet",
"Properties": {"VpcId": "%1$s", "CidrBlock": "10.44.0.0/24"%2$s}},
"Rt": {"Type": "AWS::EC2::RouteTable", "Properties": {"VpcId": "%1$s"%3$s}},
"Igw": {"Type": "AWS::EC2::InternetGateway", %4$s},
"Plain": {"Type": "AWS::EC2::RouteTable", "Properties": {"VpcId": "%1$s"}}
},
"Outputs": {"SubnetId": {"Value": {"Ref": "Subnet"}}, "PlainId": {"Value": {"Ref": "Plain"}}}
}
""".formatted(vpcId, subnetProps, rtTags, igwProps);
}
@Test
void anUpdateClearsWhatTheNewTemplateDropsAndKeepsWhatTheStackNeverDeclared() {
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.44.0.0/16")), "<vpcId>", "</vpcId>");
cloudFormation(REMOVAL_STACK, "CreateStack", removalTemplate(vpcId, true));
Map<String, String> out = XmlParser.extractPairs(describeStacks(REMOVAL_STACK, "CREATE_COMPLETE"),
"Outputs", "OutputKey", "OutputValue");
ec2("CreateTags", Map.of("ResourceId.1", out.get("PlainId"), "Tag.1.Key", "owner", "Tag.1.Value", "outside-owner"));
assertTrue(subnetXml(out.get("SubnetId")).contains("<value>subnet-net</value>"));
assertTrue(subnetXml(out.get("SubnetId")).contains("<mapPublicIpOnLaunch>true</mapPublicIpOnLaunch>"));
cloudFormation(REMOVAL_STACK, "UpdateStack", removalTemplate(vpcId, false));
describeStacks(REMOVAL_STACK, "UPDATE_COMPLETE");
String subnet = subnetXml(out.get("SubnetId"));
assertFalse(subnet.contains("subnet-net"), "the subnet's dropped tag must be gone: " + subnet);
assertTrue(subnet.contains("<mapPublicIpOnLaunch>false</mapPublicIpOnLaunch>"), "the dropped flag goes back to false");
String routeTables = ec2("DescribeRouteTables");
assertFalse(routeTables.contains("rt-marker"), "the route table's dropped tag must be gone");
assertTrue(routeTables.contains("outside-owner"), "a tag on a resource the stack never tagged stays");
assertFalse(ec2("DescribeInternetGateways").contains("igw-marker"), "the gateway's dropped tag must be gone");
cloudFormation(REMOVAL_STACK, "DeleteStack", null);
CfnStackWaits.awaitStackDeleted(REMOVAL_STACK);
ec2("DeleteVpc", Map.of("VpcId", vpcId));
}
/**
* CreateNatGateway with an Elastic IP another gateway holds succeeds on AWS and leaves the
* gateway failed; CloudFormation must still fail the resource rather than report it created.
@@ -498,11 +546,7 @@ class CloudFormationEc2NetworkingIntegrationTest {
}
private static void cloudFormation(String stack, String action, String templateBody) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
RequestSpecification request = cfn(action, stack).header("Authorization", CFN_AUTH);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
@@ -514,11 +558,8 @@ class CloudFormationEc2NetworkingIntegrationTest {
}
private static String describeStacks(String stack, String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
return cfn("DescribeStacks", stack)
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
@@ -830,6 +830,138 @@ class Ec2NetworkCfnProvisionerTest {
verify(ec2, never()).createTags(any(), any(), any());
}
/** Stubs one reused entity of each taggable type, every one carrying the given tags, and returns their resources. */
private List<StackResource> reusedEntitiesCarrying(List<Tag> tags) {
Subnet subnet = subnet();
subnet.setTags(tags);
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(subnet));
RouteTable rt = new RouteTable();
rt.setRouteTableId(RTB_ID);
rt.setVpcId(VPC_ID);
rt.setTags(tags);
when(ec2.describeRouteTables(REGION, List.of(RTB_ID), Map.of())).thenReturn(List.of(rt));
InternetGateway igw = new InternetGateway();
igw.setInternetGatewayId(IGW_ID);
igw.setTags(tags);
when(ec2.describeInternetGateways(REGION, List.of(IGW_ID), Map.of())).thenReturn(List.of(igw));
NatGateway nat = natGateway(NAT_ID);
nat.setSubnetId(SUBNET_ID);
nat.setAllocationId(ALLOC_ID);
nat.setTags(tags);
when(ec2.describeNatGateways(REGION, List.of(NAT_ID), Map.of())).thenReturn(List.of(nat));
Address addr = new Address();
addr.setAllocationId(ALLOC_ID);
addr.setPublicIp(PUBLIC_IP);
addr.setTags(tags);
when(ec2.describeAddresses(REGION, List.of(ALLOC_ID), Map.of())).thenReturn(List.of(addr));
return List.of(
prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID)),
prior("AWS::EC2::RouteTable", "Rtb", RTB_ID, Map.of("RouteTableId", RTB_ID)),
prior("AWS::EC2::InternetGateway", "Igw", IGW_ID, Map.of("InternetGatewayId", IGW_ID)),
prior("AWS::EC2::NatGateway", "Nat", NAT_ID, Map.of("NatGatewayId", NAT_ID)),
prior("AWS::EC2::EIP", "Eip", PUBLIC_IP, Map.of("AllocationId", ALLOC_ID, "PublicIp", PUBLIC_IP)));
}
/** Updates each of those resources to a template that has no Tags, after {@code previous} as the prior properties. */
private void updateWithoutTags(List<StackResource> resources, JsonNode previous) {
provisioner.provision(resources.get(0), mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"),
ctx(SUBNET_ID, previous));
provisioner.provision(resources.get(1), mapper.createObjectNode().put("VpcId", VPC_ID), ctx(RTB_ID, previous));
provisioner.provision(resources.get(2), mapper.createObjectNode(), ctx(IGW_ID, previous));
provisioner.provision(resources.get(3),
mapper.createObjectNode().put("SubnetId", SUBNET_ID).put("AllocationId", ALLOC_ID), ctx(NAT_ID, previous));
provisioner.provision(resources.get(4), mapper.createObjectNode(), ctx(PUBLIC_IP, previous));
}
@Test
void droppingTheTagsThePreviousTemplateDeclaredRemovesThemFromEveryTaggableType() {
List<StackResource> resources = reusedEntitiesCarrying(List.of(new Tag("team", "net"),
new Tag("aws:cloudformation:stack-id", "stack")));
updateWithoutTags(resources, withTags(mapper.createObjectNode(), "team", "net"));
for (String id : List.of(SUBNET_ID, RTB_ID, IGW_ID, NAT_ID, ALLOC_ID)) {
ArgumentCaptor<List<Tag>> removed = ArgumentCaptor.captor();
verify(ec2).deleteTags(eq(REGION), eq(List.of(id)), removed.capture());
assertEquals(List.of("team=null"), pairs(removed.getValue()), id);
}
verify(ec2, never()).createTags(any(), any(), any());
}
@Test
void tagsNoTemplateEverDeclaredStayOnEveryTaggableType() {
List<StackResource> resources = reusedEntitiesCarrying(List.of(new Tag("owner", "ops")));
updateWithoutTags(resources, mapper.createObjectNode());
verify(ec2, never()).deleteTags(any(), any(), any());
verify(ec2, never()).createTags(any(), any(), any());
}
@Test
void aStackRolledBackAfterItsTagsWereClearedGetsThemBack() {
List<StackResource> resources = reusedEntitiesCarrying(List.of(new Tag("team", "net"), new Tag("Name", "rt")));
updateWithoutTags(resources, withTags(mapper.createObjectNode(), "team", "net"));
StackResource routeTable = resources.get(1);
assertTrue(routeTable.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
assertTrue(provisioner.rollbackUpdate(routeTable));
ArgumentCaptor<List<Tag>> written = ArgumentCaptor.captor();
verify(ec2).createTags(eq(REGION), eq(List.of(RTB_ID)), written.capture());
assertEquals(List.of("team=net", "Name=rt"), pairs(written.getValue()));
assertFalse(routeTable.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void aFailedSubnetAttributeChangeAfterTheTagsWereClearedPutsThemBack() {
Subnet current = subnet();
current.setMapPublicIpOnLaunch(true);
current.setTags(List.of(new Tag("team", "net")));
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
doThrow(new AwsException("InvalidParameterValue", "nope", 400))
.when(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "false");
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
JsonNode previous = withTags(mapper.createObjectNode().put("MapPublicIpOnLaunch", true), "team", "net");
assertThrows(AwsException.class, () -> provisioner.provision(r,
mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"), ctx(SUBNET_ID, previous)));
verify(ec2).deleteTags(eq(REGION), eq(List.of(SUBNET_ID)), any());
assertEquals(List.of("team=net"), tagsWritten(SUBNET_ID));
verify(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "true");
assertFalse(r.getAttributes().containsKey(Ec2NetworkCfnProvisioner.IN_PLACE_PRIOR_ATTR));
}
@Test
void droppingMapPublicIpOnLaunchThePreviousTemplateDeclaredTurnsItOffAndARollbackTurnsItOn() {
Subnet current = subnet();
current.setMapPublicIpOnLaunch(true);
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
JsonNode previous = mapper.createObjectNode().put("MapPublicIpOnLaunch", true);
provisioner.provision(r, mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"),
ctx(SUBNET_ID, previous));
verify(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "false");
assertTrue(provisioner.rollbackUpdate(r));
verify(ec2).modifySubnetAttribute(REGION, SUBNET_ID, "mapPublicIpOnLaunch", "true");
}
@Test
void aSubnetWhoseTemplatesNeverDeclaredMapPublicIpOnLaunchKeepsTheValueItCarries() {
Subnet current = subnet();
current.setMapPublicIpOnLaunch(true);
when(ec2.describeSubnets(REGION, List.of(SUBNET_ID), Map.of())).thenReturn(List.of(current));
StackResource r = prior("AWS::EC2::Subnet", "Subnet", SUBNET_ID, Map.of("SubnetId", SUBNET_ID));
provisioner.provision(r, mapper.createObjectNode().put("VpcId", VPC_ID).put("CidrBlock", "10.0.1.0/24"),
ctx(SUBNET_ID, mapper.createObjectNode().put("VpcId", VPC_ID)));
verify(ec2, never()).modifySubnetAttribute(any(), any(), any(), any());
}
@Test
void requiredPropertiesAreValidatedBeforeAnyServiceCall() {
record Case(String type, ObjectNode props, String expected) { }