diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 0957c56b10..87dd5c3c09 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -206,7 +206,7 @@ cross-resource references. | ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) | | Redshift | `Cluster` (single-node container; Port and non-dev DBName ignored; ManageMasterPassword unsupported), `ClusterParameterGroup`, `ClusterSubnetGroup`, `ClusterSecurityGroup` (accepted; no EC2-Classic security group model), `EventSubscription` | | Redshift Serverless | `Namespace` (Managed admin credentials use Secrets Manager; GetAtt uses the dotted Namespace.* form), `Workgroup` (starts a real container; one workgroup per namespace; capacity, VPC and price-performance settings are stored only; snapshot restore properties are ignored; GetAtt uses the dotted Workgroup.* form) | -| EC2 | `VPC` (deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place), `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` (`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement), `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | +| EC2 | `VPC` (`Tags` update in place, keeping tags added outside the stack; deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS), `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported; `Tags` update in place, keeping tags added outside the stack), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway` (zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place), `EIP`, `Instance` (`Tags` update in place, keeping tags added outside the stack), `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` (`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement), `KeyPair` (a created key's private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key), `PrefixList` (updated in place; an update that changes `AddressFamily`, or `MaxEntries` together with `Entries`, fails) | | Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` | | Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` | | Application Auto Scaling | `ScalableTarget` (`ScheduledActions` are accepted and not run; Floci has no scheduled scaling), `ScalingPolicy` | diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java index 9430b31544..a14852ca87 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2FlowLogCfnProvisioner.java @@ -1,9 +1,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; @@ -13,8 +11,6 @@ import io.github.hectorvent.floci.services.ec2.model.FlowLog; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; @@ -41,11 +37,7 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String SNAPSHOT_ATTR = CfnRollback.FLOW_LOG_UPDATE_SNAPSHOT_ATTR; - /** - * The tag keys the last deployment resolved and wrote, as a JSON array: the keys the stack owns. - * Recorded rather than re-resolved from the previous template, because a key taken from a - * parameter resolves to the new value on the next update. - */ + /** The tag keys the last deployment wrote, as {@link Ec2Tags#recordKeys} records them. */ static final String TAG_KEYS_ATTR = "__FlociEc2FlowLogTagKeys"; private final FlowLogService flowLogService; @@ -86,12 +78,12 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { requireUnchanged(existing, props, ctx); r.getAttributes().put("Id", existingId); // Only the keys the last deployment wrote are the stack's to remove. - Set owned = ownedTagKeys(r, ctx); + Set owned = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx); CfnRollback.guarded(r, ctx, false, () -> { }, () -> undoInPlace(r), () -> { snapshotTags(r, region, existingId, owned, desiredTags, priorTagKeys); Ec2Tags.reconcileOwned(ec2Service, region, existingId, owned, desiredTags); }); - recordTagKeys(r, desiredTags); + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags); return; } } @@ -111,8 +103,8 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { r.getAttributes().put("Id", flowLogId); // A tag write that still fails deletes the new log rather than leaving it outside the stack. CfnRollback.guarded(r, ctx, true, () -> flowLogService.deleteFlowLogs(region, List.of(flowLogId)), - () -> { }, () -> Ec2Tags.reconcile(ec2Service, region, flowLogId, desiredTags)); - recordTagKeys(r, desiredTags); + () -> { }, () -> Ec2Tags.reconcileOwned(ec2Service, region, flowLogId, Set.of(), desiredTags)); + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags); if (ctx.isUpdate()) { // The stack's log was removed outside it, so a rollback deletes this one and names the // prior id again rather than keeping the failed update's log. @@ -143,95 +135,42 @@ public class Ec2FlowLogCfnProvisioner implements CfnResourceProvisioner { JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR); if (snapshot != null && CfnRollback.undoCreatedByUpdate(resource, snapshot, SNAPSHOT_ATTR, "Id", (id, region) -> flowLogService.deleteFlowLogs(region, List.of(id)))) { - restoreTagKeys(resource, snapshot); + Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, snapshot); return true; } undoInPlace(resource); return true; } - /** Puts back the ownership record the snapshot carries, or its absence. */ - private static void restoreTagKeys(StackResource r, JsonNode snapshot) { - String tagKeys = CfnRollback.snapshotText(snapshot, "tagKeys"); - if (tagKeys == null) { - r.getAttributes().remove(TAG_KEYS_ATTR); - } else { - r.getAttributes().put(TAG_KEYS_ATTR, tagKeys); - } - } - /** - * The keys the last deployment recorded in {@link #TAG_KEYS_ATTR}. A log provisioned before - * that was recorded falls back to the previous template's keys, resolved as well as they still - * can be. - */ - private Set ownedTagKeys(StackResource r, ProvisionContext ctx) { - String recorded = r.getAttributes().get(TAG_KEYS_ATTR); - if (recorded == null) { - return ctx.resolveTags(ctx.priorProperties(), "Tags").keySet(); - } - Set keys = new LinkedHashSet<>(); - try { - MAPPER.readTree(recorded).forEach(key -> keys.add(key.asText())); - } catch (JsonProcessingException e) { - throw new IllegalStateException("Unreadable tag keys on " + r.getLogicalId(), e); - } - return keys; - } - - private static void recordTagKeys(StackResource r, Map desiredTags) { - ArrayNode keys = MAPPER.createArrayNode(); - desiredTags.keySet().forEach(keys::add); - r.getAttributes().put(TAG_KEYS_ATTR, keys.toString()); - } - - /** - * Records the values the touched keys (the owned ones and the declared ones) had before the - * update changes them, with the ownership record it replaces, only when a value or the owned - * key set is about to change, so an unchanged reuse leaves no snapshot. Tags outside that set - * are never written, so they are not recorded either. + * Records what the update is about to change on a reused log, only when a value or the owned key + * set changes, so an unchanged reuse leaves no snapshot. */ private void snapshotTags(StackResource r, String region, String flowLogId, Set owned, Map desiredTags, String priorTagKeys) { Map currentTags = Ec2Tags.current(ec2Service, region, flowLogId); - Set touched = new LinkedHashSet<>(owned); - touched.addAll(desiredTags.keySet()); - // A change of ownership alone (taking over a key that already holds the declared value) - // still needs the record put back, so it counts as a change too. - boolean changes = !owned.equals(desiredTags.keySet()) - || touched.stream().anyMatch(key -> desiredTags.containsKey(key) - ? !desiredTags.get(key).equals(currentTags.get(key)) - : currentTags.containsKey(key)); - if (!changes) { + if (!Ec2Tags.changesOwned(owned, desiredTags, currentTags)) { return; } ObjectNode prior = MAPPER.createObjectNode(); prior.put("region", region); prior.put("flowLogId", flowLogId); - prior.put("tagKeys", priorTagKeys); - touched.forEach(prior.putArray("touched")::add); - ObjectNode tags = prior.putObject("tags"); - touched.stream().filter(currentTags::containsKey).forEach(key -> tags.put(key, currentTags.get(key))); + Ec2Tags.snapshotOwned(prior, owned, desiredTags, currentTags, priorTagKeys); r.getAttributes().put(SNAPSHOT_ATTR, prior.toString()); } /** - * Puts the touched keys of a reused log back from the snapshot: a key it had gets its value - * again, and a key the update added is removed. The ownership record goes back too. The snapshot is removed only after the restore - * succeeds, so a failed one keeps it for the rollback walker's retry. + * Puts the touched keys of a reused log and its ownership record back from the snapshot. The + * snapshot is removed only after the restore succeeds, so a failed one keeps it for the rollback + * walker's retry. */ private void undoInPlace(StackResource r) { JsonNode prior = CfnRollback.updateSnapshot(r, SNAPSHOT_ATTR); if (prior == null) { return; } - Set touched = new LinkedHashSet<>(); - prior.path("touched").forEach(key -> touched.add(key.asText())); - Map priorTags = new LinkedHashMap<>(); - prior.path("tags").properties().forEach(f -> priorTags.put(f.getKey(), f.getValue().asText())); - Ec2Tags.reconcileOwned(ec2Service, prior.path("region").asText(), prior.path("flowLogId").asText(), - touched, priorTags); - restoreTagKeys(r, prior); + Ec2Tags.restoreOwned(ec2Service, prior.path("region").asText(), prior.path("flowLogId").asText(), r, + TAG_KEYS_ATTR, prior); r.getAttributes().remove(SNAPSHOT_ATTR); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java index 85c61e4a3a..1f7e9800b3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java @@ -50,6 +50,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { // The MetadataOptions members declared last time, the instance's own or its launch template's, so // an update can return the ones it no longer declares to their launch defaults. private static final String DECLARED_METADATA_OPTIONS_ATTR = "__FlociDeclaredMetadataOptions"; + // The tag keys the last deployment wrote, as Ec2Tags.recordKeys records them, so an update + // removes only those and keeps a tag added outside the stack. + static final String DECLARED_TAG_KEYS_ATTR = "__FlociDeclaredTagKeys"; // The __FlociDeclared records as they stood before a replacing update, for rollbackUpdate to put // back with the instance it restores; ReplacementCleanup leaves __Floci attributes alone. private static final String PRIOR_DECLARATIONS_ATTR = "__FlociPriorDeclarations"; @@ -155,7 +158,8 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { && Ec2CfnMetadataOptions.changes(optionsBefore, metadataOptionsToApply); boolean otherChange = reconcileMutableProperties(region, prior, instanceType, securityGroupIds, userData, iamInstanceProfileArn, attributesBefore.get(DECLARED_IAM_PROFILE_ATTR)); - boolean tagsChanged = Ec2Tags.reconcile(ec2Service, region, prior.getInstanceId(), desiredTags); + boolean tagsChanged = Ec2Tags.reconcileOwned(ec2Service, region, prior.getInstanceId(), + Ec2Tags.ownedKeys(r, DECLARED_TAG_KEYS_ATTR, ctx), desiredTags); // Saved on every update that keeps the instance, also one that changes no EC2 setting but // only what is declared, so a rollback can always put the declarations back. r.getAttributes().put(PRIOR_IN_PLACE_ATTR, priorInPlaceUpdate(region, @@ -173,6 +177,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone); putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn); putOrRemove(r, DECLARED_METADATA_OPTIONS_ATTR, Ec2CfnMetadataOptions.declaredMembers(metadataOptions)); + Ec2Tags.recordKeys(r, DECLARED_TAG_KEYS_ATTR, desiredTags); ReplacementCleanup.record(r, ctx, attributesBefore); return; } @@ -216,6 +221,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner { storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone); putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn); putOrRemove(r, DECLARED_METADATA_OPTIONS_ATTR, Ec2CfnMetadataOptions.declaredMembers(metadataOptions)); + Ec2Tags.recordKeys(r, DECLARED_TAG_KEYS_ATTR, desiredTags); // A createOnly change that landed a new instance id replaced the prior one: record it so // the stack cleans the displaced instance up after the update commits. ReplacementCleanup.record(r, ctx, attributesBefore); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java index c2e4f007cc..2d806afa2e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisioner.java @@ -47,6 +47,8 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { // standalone SecurityGroupIngress/Egress resource owns. static final String INGRESS_RULES_ATTR = "__FlociSgIngressRules"; static final String EGRESS_RULES_ATTR = "__FlociSgEgressRules"; + /** The tag keys the last deployment wrote, as {@link Ec2Tags#recordKeys} records them. */ + static final String TAG_KEYS_ATTR = "__FlociSgTagKeys"; private final Ec2Service ec2Service; @@ -110,7 +112,11 @@ 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(), desiredTags); + // AWS updates Tags in place and keeps a tag added outside the stack, so a reused group has + // only the keys the last deployment wrote removed; a new group carries no tags yet. + Set ownedTags = reconciled != null ? Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx) : Set.of(); + Ec2Tags.reconcileOwned(ec2Service, region, sg.getGroupId(), ownedTags, desiredTags); + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags); } @Override @@ -177,11 +183,6 @@ public class Ec2SecurityGroupCfnProvisioner implements CfnResourceProvisioner { return new LinkedHashSet<>(Arrays.asList(stored.split("\n", -1))); } - /** - * Reconciles the group's tags to the template on create and update: adds or overwrites the - * declared tags and removes any the template dropped. AWS treats SecurityGroup Tags as an - * in-place (no interruption) update. - */ /** * Resolves a peer group's name to its id, the same lookup {@code Ec2Service} performs when it * stores an authorized rule. Group names are unique per VPC rather than per region, so the diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java index 376f9ae1bd..029c1bfb35 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2Tags.java @@ -1,23 +1,33 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.ec2.Ec2Service; import io.github.hectorvent.floci.services.ec2.model.Tag; import java.util.ArrayList; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Set; /** * Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner}, * {@code Ec2SecurityGroupCfnProvisioner}, {@code Ec2VpcCfnProvisioner} and * {@code Ec2FlowLogCfnProvisioner}). They drive it from the desired tags resolved via - * {@link ProvisionContext#resolveTags}; the reconcile itself is identical. + * {@link ProvisionContext#resolveTags}; the reconcile itself is identical: an update changes only + * the keys the stack owns, recorded by {@link #recordKeys}, and keeps a tag added outside the stack, + * as AWS does. */ final class Ec2Tags { + private static final ObjectMapper MAPPER = new ObjectMapper(); + private Ec2Tags() { } @@ -30,8 +40,8 @@ final class Ec2Tags { /** * The user tags EC2 currently holds for the resource, keyed by tag key in DescribeTags order. - * Reserved {@code aws:} keys are never part of the user tag set, so neither {@link #reconcile} - * nor a rollback snapshot taken from this map can try to write one. + * Reserved {@code aws:} keys are never part of the user tag set, so neither + * {@link #reconcileOwned} nor a rollback snapshot taken from this map can try to write one. */ static Map current(Ec2Service ec2Service, String region, String resourceId) { Map current = new LinkedHashMap<>(); @@ -43,42 +53,18 @@ final class Ec2Tags { return current; } - /** - * 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. Returns whether the - * tags were anything other than {@code desired} before. - */ - static boolean reconcile(Ec2Service ec2Service, String region, String resourceId, Map desired) { - List add = validatedTags(desired); - Map current = current(ec2Service, region, resourceId); - List stale = ProvisionContext.staleTagKeys(current, desired); - boolean changed = !stale.isEmpty(); - for (Tag tag : add) { - changed |= !current.containsKey(tag.getKey()) || !Objects.equals(tag.getValue(), current.get(tag.getKey())); - } - if (!stale.isEmpty()) { - List remove = new ArrayList<>(); - for (String key : stale) { - remove.add(new Tag(key, current.get(key))); - } - ec2Service.deleteTags(region, List.of(resourceId), remove); - } - if (!add.isEmpty()) { - ec2Service.createTags(region, List.of(resourceId), add); - } - return changed; - } - /** * Brings the keys a template owns to {@code desired} and leaves every other tag alone, as AWS * keeps a tag added outside the stack: removes the {@code owned} keys {@code desired} no longer * declares, then creates or overwrites the declared ones. {@code owned} is the key set the - * previous template declared, or the keys an update touched when a rollback restores them. + * last deployment wrote, or the keys an update touched when a rollback restores them. Returns + * whether any of those tags were anything other than {@code desired} before. */ - static void reconcileOwned(Ec2Service ec2Service, String region, String resourceId, Set owned, - Map desired) { + static boolean reconcileOwned(Ec2Service ec2Service, String region, String resourceId, Set owned, + Map desired) { List add = validatedTags(desired); Map current = current(ec2Service, region, resourceId); + boolean changed = changesOwnedTags(owned, desired, current); List remove = new ArrayList<>(); for (String key : owned) { if (!desired.containsKey(key) && current.containsKey(key)) { @@ -91,5 +77,98 @@ final class Ec2Tags { if (!add.isEmpty()) { ec2Service.createTags(region, List.of(resourceId), add); } + return changed; + } + + /** + * The keys the last deployment recorded in {@code recordAttr}. A resource provisioned before + * that was recorded falls back to the previous template's keys, resolved as well as they still + * can be. Recorded rather than re-resolved, because a key taken from a parameter resolves to the + * new value on the next update. + */ + static Set ownedKeys(StackResource r, String recordAttr, ProvisionContext ctx) { + String recorded = r.getAttributes().get(recordAttr); + if (recorded == null) { + return ctx.resolveTags(ctx.priorProperties(), "Tags").keySet(); + } + Set keys = new LinkedHashSet<>(); + try { + MAPPER.readTree(recorded).forEach(key -> keys.add(key.asText())); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Unreadable tag keys on " + r.getLogicalId(), e); + } + return keys; + } + + /** + * Records the keys this deployment resolved and wrote, as a JSON array: the keys the stack owns. + * An empty array is recorded too: re-resolving the previous template could read keys this + * deployment never wrote (an {@code Fn::If} over the next update's conditions), so only a + * resource provisioned before records were kept falls back to that. + */ + static void recordKeys(StackResource r, String recordAttr, Map desired) { + ArrayNode keys = MAPPER.createArrayNode(); + desired.keySet().forEach(keys::add); + r.getAttributes().put(recordAttr, keys.toString()); + } + + /** + * Whether an update to {@code desired} changes a tag or the owned key set. A change of ownership + * alone (taking over a key that already holds the declared value) still needs the record put + * back, so it counts as a change too. + */ + static boolean changesOwned(Set owned, Map desired, Map current) { + return !owned.equals(desired.keySet()) || changesOwnedTags(owned, desired, current); + } + + private static boolean changesOwnedTags(Set owned, Map desired, + Map current) { + return touched(owned, desired).stream().anyMatch(key -> desired.containsKey(key) + ? !desired.get(key).equals(current.get(key)) + : current.containsKey(key)); + } + + /** + * Records in {@code snapshot} what {@link #restoreOwned} needs: the keys an update touches (the + * owned ones and the declared ones), the values they had, and the ownership record the update + * replaces. Tags outside the touched set are never written, so they are not recorded either. + */ + static void snapshotOwned(ObjectNode snapshot, Set owned, Map desired, + Map current, String priorRecord) { + Set touched = touched(owned, desired); + touched.forEach(snapshot.putArray("touched")::add); + ObjectNode tags = snapshot.putObject("tags"); + touched.stream().filter(current::containsKey).forEach(key -> tags.put(key, current.get(key))); + snapshot.put("tagKeys", priorRecord); + } + + /** + * Puts the touched keys back from a {@link #snapshotOwned} snapshot: a key the resource had gets + * its value again, and a key the update added is removed. The ownership record goes back too. + */ + static void restoreOwned(Ec2Service ec2Service, String region, String resourceId, StackResource r, + String recordAttr, JsonNode snapshot) { + Set touched = new LinkedHashSet<>(); + snapshot.path("touched").forEach(key -> touched.add(key.asText())); + Map priorTags = new LinkedHashMap<>(); + snapshot.path("tags").properties().forEach(f -> priorTags.put(f.getKey(), f.getValue().asText())); + reconcileOwned(ec2Service, region, resourceId, touched, priorTags); + restoreRecord(r, recordAttr, snapshot); + } + + /** Puts back the ownership record a snapshot carries in {@code tagKeys}, or its absence. */ + static void restoreRecord(StackResource r, String recordAttr, JsonNode snapshot) { + String tagKeys = CfnRollback.snapshotText(snapshot, "tagKeys"); + if (tagKeys == null) { + r.getAttributes().remove(recordAttr); + } else { + r.getAttributes().put(recordAttr, tagKeys); + } + } + + private static Set touched(Set owned, Map desired) { + Set touched = new LinkedHashSet<>(owned); + touched.addAll(desired.keySet()); + return touched; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java index a7184e3cfc..f09ecc2ae5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisioner.java @@ -14,7 +14,6 @@ import io.github.hectorvent.floci.services.ec2.model.VpcIpv6CidrBlockAssociation import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -33,16 +32,17 @@ import java.util.stream.Collectors; * Ipv6CidrBlocks. List-valued attributes are comma-joined like the other provisioners' lists. * *

Tags are reconciled to the template's {@code Tags} the way {@link Ec2Tags} does for the - * instance and security-group provisioners: a key the template dropped is deleted. Stack-level + * instance and security-group provisioners: a key the last deployment wrote that the template + * dropped is deleted, and a tag added outside the stack is kept, as on AWS. Stack-level * tags and the {@code aws:cloudformation:*} system tags are not applied here, matching every other * EC2 provisioner in this package. * *

A replacement leaves the displaced VPC to the {@link ReplacementCleanup} record: it is deleted * once the update commits, or the resource is pointed back at it when a later resource fails the * update and it rolls back. An in-place change to a reused VPC is snapshotted before it is written - * (tenancy, the DNS attributes and the tag set), so the same rollback puts them back; a provision - * that fails mid-way restores its own snapshot before the failure propagates. The stack delete - * removes the VPC; it tolerates only {@code InvalidVpcID.NotFound}, so a VPC that still has + * (tenancy, the DNS attributes and the tag keys it touches), so the same rollback puts them back; a + * provision that fails mid-way restores its own snapshot before the failure propagates. The stack + * delete removes the VPC; it tolerates only {@code InvalidVpcID.NotFound}, so a VPC that still has * dependents outside the stack fails the delete with {@code DependencyViolation}, as on AWS. */ @ApplicationScoped @@ -53,9 +53,12 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { private static final ObjectMapper MAPPER = new ObjectMapper(); /** * What an in-place update changed on a reused VPC, recorded before the change so a stack - * rollback can put it back. Internal, like the other {@code __Floci} attributes. + * rollback can put it back, or, for a replacement, the tag-key record it replaced. Internal, + * like the other {@code __Floci} attributes. */ static final String IN_PLACE_PRIOR_ATTR = "__FlociEc2VpcPrior"; + /** The tag keys the last deployment wrote, as {@link Ec2Tags#recordKeys} records them. */ + static final String TAG_KEYS_ATTR = "__FlociEc2VpcTagKeys"; private final Ec2Service ec2Service; @@ -85,6 +88,9 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { Map desiredTags = ctx.resolveTags(props, "Tags"); Vpc reconciled = existingVpcToReconcile(ctx.isUpdate() ? ctx.priorPhysicalId() : null, cidr, desiredTenancy, region); boolean reused = reconciled != null; + // Only the keys the last deployment wrote are the stack's to remove; a new VPC has no tags. + String priorTagKeys = r.getAttributes().get(TAG_KEYS_ATTR); + Set ownedTags = reused ? Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx) : Set.of(); Vpc vpc = reused ? reconciled : ec2Service.createVpc(region, cidr, false, false, desiredTenancy); String vpcId = vpc.getVpcId(); r.setPhysicalId(vpcId); @@ -92,15 +98,25 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { CfnRollback.guarded(r, ctx, !reused, () -> ec2Service.deleteVpc(region, vpcId), () -> undoInPlace(r), () -> { if (reused) { - snapshotInPlace(r, vpc, desiredTenancy, dnsSupport, dnsHostnames, desiredTags, region); + snapshotInPlace(r, vpc, desiredTenancy, dnsSupport, dnsHostnames, ownedTags, desiredTags, + priorTagKeys, region); } if (reused && isDedicatedToDefault(vpc, desiredTenancy)) { ec2Service.modifyVpcTenancy(region, vpcId, desiredTenancy); } ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport", String.valueOf(dnsSupport)); ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames", String.valueOf(dnsHostnames)); - Ec2Tags.reconcile(ec2Service, region, vpcId, desiredTags); + Ec2Tags.reconcileOwned(ec2Service, region, vpcId, ownedTags, desiredTags); }); + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, desiredTags); + if (!reused && ctx.isUpdate()) { + // A replacement's rollback names the prior VPC again with its public attributes; the + // tag-key record it owns goes back from here. + ObjectNode replaced = MAPPER.createObjectNode(); + replaced.put("replaced", true); + replaced.put("tagKeys", priorTagKeys); + r.getAttributes().put(IN_PLACE_PRIOR_ATTR, replaced.toString()); + } if (vpc.getCidrBlock() != null) { r.getAttributes().put("CidrBlock", vpc.getCidrBlock()); @@ -158,6 +174,12 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { */ @Override public boolean rollbackUpdate(StackResource resource) { + JsonNode prior = CfnRollback.updateSnapshot(resource, IN_PLACE_PRIOR_ATTR); + if (prior != null && prior.path("replaced").asBoolean(false)) { + // Put back before the replacement's delete, which can throw after the prior VPC is named + // again. + Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, prior); + } if (ReplacementCleanup.rollback(resource, this::delete)) { resource.getAttributes().remove(IN_PLACE_PRIOR_ATTR); return true; @@ -176,17 +198,18 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { /** * Records what the update is about to change on a reused VPC, only when something differs: an - * unchanged reuse leaves no snapshot and rolls back as complete. The tag set comes from - * DescribeTags, the same source {@link Ec2Tags#reconcile} compares against. + * unchanged reuse leaves no snapshot and rolls back as complete. The tags come from + * DescribeTags, the same source {@link Ec2Tags#reconcileOwned} compares against. */ private void snapshotInPlace(StackResource r, Vpc vpc, String desiredTenancy, boolean dnsSupport, - boolean dnsHostnames, Map desiredTags, String region) { + boolean dnsHostnames, Set ownedTags, Map desiredTags, + String priorTagKeys, String region) { Map currentTags = Ec2Tags.current(ec2Service, region, vpc.getVpcId()); boolean tenancyChanges = isDedicatedToDefault(vpc, desiredTenancy); boolean changed = tenancyChanges || vpc.isEnableDnsSupport() != dnsSupport || vpc.isEnableDnsHostnames() != dnsHostnames - || !currentTags.equals(desiredTags); + || Ec2Tags.changesOwned(ownedTags, desiredTags, currentTags); if (!changed) { return; } @@ -198,16 +221,16 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { } prior.put("enableDnsSupport", vpc.isEnableDnsSupport()); prior.put("enableDnsHostnames", vpc.isEnableDnsHostnames()); - ObjectNode tags = prior.putObject("tags"); - currentTags.forEach(tags::put); + Ec2Tags.snapshotOwned(prior, ownedTags, desiredTags, currentTags, priorTagKeys); r.getAttributes().put(IN_PLACE_PRIOR_ATTR, prior.toString()); } /** - * Puts the DNS attributes and the tag set back, then the tenancy last. The only tenancy change - * applied in place is {@code dedicated} to {@code default}, and EC2 refuses the reverse, so a - * rollback of that change fails on the ModifyVpcTenancy call after everything else is restored - * and the stack reports UPDATE_ROLLBACK_FAILED for the VPC rather than claiming it is back. + * Puts the DNS attributes, the touched tag keys and their record back, then the tenancy last. + * The only tenancy change applied in place is {@code dedicated} to {@code default}, and EC2 + * refuses the reverse, so a rollback of that change fails on the ModifyVpcTenancy call after + * everything else is restored and the stack reports UPDATE_ROLLBACK_FAILED for the VPC rather + * than claiming it is back. */ private void restoreInPlace(StackResource resource, String snapshot) { ObjectNode prior; @@ -216,13 +239,15 @@ public class Ec2VpcCfnProvisioner implements CfnResourceProvisioner { } catch (JsonProcessingException e) { throw new IllegalStateException("Unreadable in-place snapshot on " + resource.getLogicalId(), e); } + if (prior.path("replaced").asBoolean(false)) { + Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, prior); + return; + } String region = prior.path("region").asText(); String vpcId = prior.path("vpcId").asText(); ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsSupport", prior.path("enableDnsSupport").asText()); ec2Service.modifyVpcAttribute(region, vpcId, "enableDnsHostnames", prior.path("enableDnsHostnames").asText()); - Map priorTags = new LinkedHashMap<>(); - prior.path("tags").fields().forEachRemaining(f -> priorTags.put(f.getKey(), f.getValue().asText())); - Ec2Tags.reconcile(ec2Service, region, vpcId, priorTags); + Ec2Tags.restoreOwned(ec2Service, region, vpcId, resource, TAG_KEYS_ATTR, prior); if (prior.hasNonNull("instanceTenancy")) { ec2Service.modifyVpcTenancy(region, vpcId, prior.get("instanceTenancy").asText()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2OwnedTagsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2OwnedTagsIntegrationTest.java new file mode 100644 index 0000000000..33aece479f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2OwnedTagsIntegrationTest.java @@ -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 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 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 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 createStackWithExternalTags() { + cfn.createStack(request -> request.stackName(stackName).templateBody(template(true))); + stackCreated = true; + CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE"); + Map 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 outputs() { + Map 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 tags(String resourceId) { + Map 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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java index 71fcb5b17c..0d040edcc8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java @@ -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 declared = Map.of("__FlociDeclaredMetadataOptions", "HttpTokens"); + Map 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java index 5d2a7683cb..059a0747cb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2SecurityGroupCfnProvisionerTest.java @@ -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 diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java index 61b1a4f67f..a06ab7d507 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2VpcCfnProvisionerTest.java @@ -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)); diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 80baeeae2e..ec036864f6 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -193,8 +193,9 @@ notes: AWS::Lambda::EventInvokeConfig: also what a SAM function's `EventInvokeConfig` expands into AWS::Lambda::WebFunction: control plane only; the endpoint domain does not serve requests yet AWS::Lambda::WebFunctionRevision: every property is createOnly, so a change mints a new revision - AWS::EC2::VPC: 'deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS' - AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported + AWS::EC2::VPC: '`Tags` update in place, keeping tags added outside the stack; deleted on stack teardown; a VPC with dependents outside the stack, including anything still holding a network interface in its subnets (an instance that is not terminated, a NAT gateway that is not deleted or failed, a standalone interface, an interface endpoint), fails the delete with `DependencyViolation`, as on AWS' + AWS::EC2::SecurityGroup: 'inline `SecurityGroupIngress`/`SecurityGroupEgress` supported; `Tags` update in place, keeping tags added outside the stack' + AWS::EC2::Instance: '`Tags` update in place, keeping tags added outside the stack' AWS::EC2::FlowLog: '`Tags` are applied and updated in place, keeping tags added outside the stack; any other change fails, since it needs a replacement' AWS::EC2::KeyPair: 'a created key''s private key is stored in the `SecureString` parameter `/ec2/keypair/`, as on AWS, and deleted with the key' AWS::EC2::NatGateway: 'zonal; `AvailabilityMode` regional fails; a change to the `Secondary*` address properties updates the gateway in place'