From 9c9792a019639c2018a6b3a42df9dfb60cff781d Mon Sep 17 00:00:00 2001 From: Oleksandr Nikolaichuk <57410473+Sekator778@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:59:49 +0300 Subject: [PATCH] fix(cloudformation): update an EKS nodegroup in place unless the engine says it must be replaced (#8734) An AWS::EKS::Nodegroup update no longer creates another nodegroup. One that changes no create-only property keeps its name and ARN, and its stack-managed tags are reconciled while tags added outside the stack stay; a failed update puts them back. A change to a property the registry marks create-only replaces the nodegroup and deletes the old one once the update commits. EksService cannot apply the other mutable properties, so the cluster and the nodegroup accept any change the engine reports beyond Tags with a warning. The nodegroup is created with its template tags, and a rolled-back replacement puts back the tag-key records of the entity it restores. Part of #6606 --- docs/services/cloudformation.md | 2 +- .../provisioners/CfnRollback.java | 6 + .../provisioners/EksCfnProvisioner.java | 234 ++++++++++++++---- .../provisioners/ReplacementCleanup.java | 7 +- .../CfnReplacementIntegrationTest.java | 14 ++ .../CloudFormationEksIntegrationTest.java | 76 ++++++ .../cloudformation/writable-property-gaps.tsv | 1 - tools/docs/cfn_resource_types.yaml | 1 + 8 files changed, 284 insertions(+), 57 deletions(-) diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 021fda9d80..954a5ba839 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -219,7 +219,7 @@ cross-resource references. | ECR | `Repository` | | ECS | `Cluster`, `TaskDefinition`, `Service`, `CapacityProvider`, `ClusterCapacityProviderAssociations` | | EFS | `FileSystem` (metadata only, there is no NFS data plane), `MountTarget` (`SecurityGroups` update in place, every other property replaces), `AccessPoint` (`AccessPointTags` update in place, every other property replaces) | -| EKS | `Cluster` (created with `Name`, `Version`, `RoleArn` and `Tags`, a replacement included; `EncryptionConfig` and `KubernetesNetworkConfig` are accepted and ignored on create; updated in place for `Tags`, keeping tags added outside the stack; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator cannot upgrade a cluster in place), `Nodegroup` | +| EKS | `Cluster` (created with `Name`, `Version`, `RoleArn` and `Tags`, a replacement included; `EncryptionConfig` and `KubernetesNetworkConfig` are accepted and ignored on create; updated in place for `Tags`, keeping tags added outside the stack; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator cannot upgrade a cluster in place), `Nodegroup` (created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place) | | RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` | | Aurora DSQL | `Cluster` | | ElastiCache | `CacheCluster` (starts a real container; modifying an existing cluster in place is not supported), `ReplicationGroup` (starts a real container; modifying an existing group in place is not supported), `SubnetGroup`, `User` (Tags are ignored), `UserGroup` (Tags are ignored), `ServerlessCache` (GetAtt uses the dotted Endpoint.* and ReaderEndpoint.* form) | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index 5f88ec7ab8..89d5f6c6f8 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -177,6 +177,12 @@ public final class CfnRollback { */ public static final String EKS_CLUSTER_UPDATE_SNAPSHOT_ATTR = "__FlociEksClusterUpdateSnapshot"; + /** + * The tags an EKS nodegroup carried before an in-place update changed them, so a failed stack + * update can put them back. Written and spent by {@code EksCfnProvisioner}. + */ + public static final String EKS_NODEGROUP_UPDATE_SNAPSHOT_ATTR = "__FlociEksNodegroupUpdateSnapshot"; + public static final String STACK_SET_UPDATE_SNAPSHOT_ATTR = "__FlociStackSetUpdateSnapshot"; /** diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EksCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EksCfnProvisioner.java index 3af1c58af8..e17b8f8b8d 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EksCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EksCfnProvisioner.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; +import java.util.function.Supplier; /** * CloudFormation provisioning for the EKS control-plane types. {@code AWS::EKS::Cluster} and @@ -40,10 +41,14 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { private static final List CLUSTER_ATTRIBUTES = List.of("Arn", "Endpoint", "CertificateAuthorityData", "OpenIdConnectIssuerUrl"); private static final ObjectMapper MAPPER = new ObjectMapper(); + /** Every attribute {@code publishNodegroup} writes for a nodegroup. */ + private static final List NODEGROUP_ATTRIBUTES = List.of("Id", "ClusterName", "NodegroupName", "Arn"); private static final String SNAPSHOT_ATTR = CfnRollback.EKS_CLUSTER_UPDATE_SNAPSHOT_ATTR; + private static final String NODEGROUP_SNAPSHOT_ATTR = CfnRollback.EKS_NODEGROUP_UPDATE_SNAPSHOT_ATTR; // The tag keys the last deployment resolved, reserved ones included, as Ec2Tags.recordKeys records // them, so an update removes only those and keeps a tag added outside the stack. private static final String TAG_KEYS_ATTR = "__FlociEksClusterTagKeys"; + private static final String NODEGROUP_TAG_KEYS_ATTR = "__FlociEksNodegroupTagKeys"; private final EksService eksService; @@ -81,7 +86,8 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { // Name, RoleArn, EncryptionConfig, BootstrapSelfManagedAddons, OutpostConfig, the network // family and CIDR and the bootstrap admin permission are create-only in the registry: a change // to one replaces the cluster. - boolean replaces = updates && ctx.changes(CLUSTER, props).requiresReplacement(); + PropertyChanges changes = updates ? ctx.changes(CLUSTER, props) : null; + boolean replaces = changes != null && changes.requiresReplacement(); String name = ctx.resolveOptional(props, "Name"); if (name == null || name.isBlank()) { // The name is the physical id, so an update that replaces nothing keeps it rather than @@ -94,7 +100,7 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { } Cluster live = updates && !replaces ? liveCluster(ctx.priorPhysicalId()) : null; if (live != null) { - updateInPlace(r, props, ctx, live); + updateInPlace(r, props, ctx, live, changes); return; } CreateClusterRequest request = new CreateClusterRequest(); @@ -138,8 +144,13 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { /** The cluster an update starts from, or null when it is gone and the update creates one. */ private Cluster liveCluster(String name) { + return orNullWhenGone(() -> eksService.describeCluster(name)); + } + + /** What {@code lookup} returns, or null when it reports the entity gone; any other failure is thrown. */ + private static T orNullWhenGone(Supplier lookup) { try { - return eksService.describeCluster(name); + return lookup.get(); } catch (AwsException e) { if ("ResourceNotFoundException".equals(e.getErrorCode())) { return null; @@ -151,25 +162,65 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { /** * The update AWS makes for the properties it does not replace on: the cluster keeps its name. * EksService has no UpdateClusterVersion or UpdateClusterConfig, so the one mutable property - * floci honors is Tags, and a changed Version is accepted with a warning and not applied. + * floci honors is Tags, and a change to any other property is accepted with a warning. */ - private void updateInPlace(StackResource r, JsonNode props, ProvisionContext ctx, Cluster live) { - JsonNode priorProps = ctx.priorProperties(); - String version = ctx.resolveOptional(props, "Version"); - String priorVersion = ctx.resolveOptional(priorProps, "Version"); - boolean versionChanged = version != null && (priorVersion == null || !version.trim().equals(priorVersion.trim())); - if (version != null && !version.isBlank() && versionChanged) { - LOG.warnv("EKS cluster {0}: in-place modification is not supported, the change to Version is ignored and" - + " the cluster keeps version {1}", live.getName(), live.getVersion()); + private void updateInPlace(StackResource r, JsonNode props, ProvisionContext ctx, Cluster live, + PropertyChanges changes) { + warnIgnoredChanges("cluster", live.getName(), changes); + updateTagsInPlace(r, props, ctx, live.getArn(), live.getTags(), live.getName(), TAG_KEYS_ATTR, SNAPSHOT_ATTR, + () -> publish(r, live), true); + } + + /** + * Nothing create-only changed on the in-place path, so every other property the engine reports + * as added, changed or dropped is one EksService has no call to apply: it is accepted with a + * warning. Tags are applied by {@link #updateTagsInPlace}. + */ + private static void warnIgnoredChanges(String kind, String name, PropertyChanges changes) { + List ignored = new ArrayList<>(); + for (PropertyChanges.PropertyChange change : changes.byName().values()) { + if (change.kind() != PropertyChanges.Kind.UNCHANGED && !"Tags".equals(change.name())) { + ignored.add(change.name()); + } } + if (!ignored.isEmpty()) { + LOG.warnv("EKS {0} {1}: in-place modification is not supported, changes to {2} are ignored", + kind, name, String.join(", ", ignored)); + } + } + + /** + * The tag half of an in-place update, shared by cluster and nodegroup: drives the tags the stack + * owns to the template's, snapshots them for the rollback and publishes the live entity. + * {@code warnReserved} reports a reserved tag change that is ignored, for a type that reads one at create. + */ + private void updateTagsInPlace(StackResource r, JsonNode props, ProvisionContext ctx, String arn, + Map currentTags, String name, String keysAttr, + String snapshotAttr, Runnable publish, boolean warnReserved) { Map templateTags = ctx.resolveTags(props, "Tags"); Map desired = ReservedTags.stripReservedTags(templateTags); - Map liveTags = live.getTags() == null ? Map.of() : live.getTags(); + Map liveTags = currentTags == null ? Map.of() : currentTags; // The keys the last deployment wrote, as it resolved them: the previous template read with // this update's parameters would name the key a parameter has since changed. - Set recorded = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx); + Set recorded = Ec2Tags.ownedKeys(r, keysAttr, ctx); Set owned = userKeys(recorded); - // Only a reserved key added or removed is seen: the record holds keys, not values. + if (warnReserved) { + warnReservedTagChanges(name, templateTags, desired, recorded, owned); + } + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("arn", arn); + Ec2Tags.snapshotOwned(snapshot, owned, desired, liveTags, r.getAttributes().get(keysAttr)); + publish.run(); + r.getAttributes().put(snapshotAttr, snapshot.toString()); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> restore(r, snapshot, keysAttr), () -> { + converge(arn, desired, Ec2Tags.touched(owned, desired)); + Ec2Tags.recordKeys(r, keysAttr, templateTags); + }); + } + + /** Only a reserved key added or removed is seen: the record holds keys, not values. */ + private static void warnReservedTagChanges(String name, Map templateTags, + Map desired, Set recorded, Set owned) { Set reservedNow = new TreeSet<>(templateTags.keySet()); reservedNow.removeAll(desired.keySet()); Set reservedBefore = new TreeSet<>(recorded); @@ -179,20 +230,11 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { reservedChanged.removeIf(key -> reservedNow.contains(key) && reservedBefore.contains(key)); reservedChanged.forEach(key -> LOG.warnv( "EKS cluster {0}: the reserved tag {1} is read at create only, the change on update is ignored", - live.getName(), key)); - ObjectNode snapshot = MAPPER.createObjectNode(); - snapshot.put("arn", live.getArn()); - Ec2Tags.snapshotOwned(snapshot, owned, desired, liveTags, r.getAttributes().get(TAG_KEYS_ATTR)); - publish(r, live); - r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString()); - CfnRollback.guarded(r, ctx, false, () -> { }, () -> restore(r, snapshot), () -> { - converge(live.getArn(), desired, Ec2Tags.touched(owned, desired)); - Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, templateTags); - }); + name, key)); } /** - * Drives the cluster's tags to {@code tags}: the one path an update and its rollback take. + * Drives the tags of a cluster or nodegroup to {@code tags}: the one path an update and its rollback take. */ private void converge(String arn, Map tags, Collection managedKeys) { CfnRollback.reconcileTags(managedKeys, tags, dropped -> eksService.untagResource(arn, dropped), @@ -205,29 +247,35 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { return new TreeSet<>(ReservedTags.stripReservedTags(byKey).keySet()); } - private void restore(StackResource r, JsonNode snapshot) { + private void restore(StackResource r, JsonNode snapshot, String keysAttr) { List touched = new ArrayList<>(); snapshot.path("touched").forEach(key -> touched.add(key.asText())); converge(CfnRollback.snapshotText(snapshot, "arn"), CfnRollback.snapshotTags(snapshot), touched); - Ec2Tags.restoreRecord(r, TAG_KEYS_ATTR, snapshot); + Ec2Tags.restoreRecord(r, keysAttr, snapshot); + } + + private static String snapshotAttr(StackResource resource) { + return NODEGROUP.equals(resource.getResourceType()) ? NODEGROUP_SNAPSHOT_ATTR : SNAPSHOT_ATTR; } @Override public boolean rollbackUpdate(StackResource resource) { - JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR); + boolean nodegroup = NODEGROUP.equals(resource.getResourceType()); + String snapshotAttr = snapshotAttr(resource); + JsonNode snapshot = CfnRollback.updateSnapshot(resource, snapshotAttr); if (snapshot == null) { return ReplacementCleanup.rollback(resource, this::delete); } - // A cluster the update created because the prior one was gone is deleted instead. - if (CfnRollback.undoCreatedByUpdate(resource, snapshot, SNAPSHOT_ATTR, null, - (createdId, region) -> delete(CLUSTER, createdId, region))) { - // The prior cluster is gone and these attributes described the one just deleted. - CLUSTER_ATTRIBUTES.forEach(resource.getAttributes()::remove); + // An entity the update created because the prior one was gone is deleted instead. + if (CfnRollback.undoCreatedByUpdate(resource, snapshot, snapshotAttr, null, + (createdId, region) -> delete(resource.getResourceType(), createdId, region))) { + // The prior entity is gone and these attributes described the one just deleted. + (nodegroup ? NODEGROUP_ATTRIBUTES : CLUSTER_ATTRIBUTES).forEach(resource.getAttributes()::remove); return true; } // Spent only once the restore succeeded: one that throws leaves it for the next attempt. - restore(resource, snapshot); - resource.getAttributes().remove(SNAPSHOT_ATTR); + restore(resource, snapshot, nodegroup ? NODEGROUP_TAG_KEYS_ATTR : TAG_KEYS_ATTR); + resource.getAttributes().remove(snapshotAttr); return true; } @@ -243,18 +291,22 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { @Override public UpdateCleanupResult completeUpdate(StackResource resource) { - resource.getAttributes().remove(SNAPSHOT_ATTR); + resource.getAttributes().remove(snapshotAttr(resource)); return ReplacementCleanup.complete(resource, this::delete); } @Override public void clearUpdate(StackResource resource) { - resource.getAttributes().remove(SNAPSHOT_ATTR); + resource.getAttributes().remove(snapshotAttr(resource)); ReplacementCleanup.clear(resource); } @Override public void delete(String resourceType, String physicalId, String region) { + if (NODEGROUP.equals(resourceType)) { + deleteNodegroup(physicalId, Map.of()); + return; + } if (!CLUSTER.equals(resourceType)) { throw new IllegalArgumentException("Unsupported resource type: " + resourceType); } @@ -263,17 +315,60 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { } private void provisionNodegroup(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(NODEGROUP_SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + boolean updates = ctx.isUpdate() && !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), r.getAttributes()); + // CapacityType, NodegroupName, RemoteAccess, NodeRole, ClusterName, InstanceTypes, DiskSize, + // AmiType and Subnets are create-only in the registry: a change to one replaces the nodegroup. + PropertyChanges changes = updates ? ctx.changes(NODEGROUP, props) : null; + boolean replaces = changes != null && changes.requiresReplacement(); String clusterName = ctx.resolveOptional(props, "ClusterName"); - Nodegroup request = new Nodegroup(); + String[] prior = updates ? nodegroupNames(ctx.priorPhysicalId(), r.getAttributes()) : null; + if (updates && prior == null) { + LOG.warnv("EKS nodegroup {0}: the prior physical id names no nodegroup, treated as gone", + ctx.priorPhysicalId()); + } String nodegroupName = ctx.resolveOptional(props, "NodegroupName"); if (nodegroupName == null || nodegroupName.isBlank()) { - nodegroupName = ctx.generatePhysicalName(r.getLogicalId(), 100, false); + // The name is part of the physical id, so an update that replaces nothing keeps it rather + // than creating a second nodegroup and orphaning the first. + nodegroupName = prior != null && !replaces ? prior[1] + : ctx.generatePhysicalName(r.getLogicalId(), 100, false); } + if (replaces && ctx.reusesPriorEntity(clusterName + "/" + nodegroupName)) { + throw CfnExceptions.customNamedReplacement(nodegroupName); + } + Nodegroup live = prior != null && !replaces ? liveNodegroup(prior[0], prior[1]) : null; + if (live != null) { + updateNodegroupInPlace(r, props, ctx, live, changes); + return; + } + Nodegroup request = new Nodegroup(); request.setNodegroupName(nodegroupName); request.setNodeRole(ctx.resolveOptional(props, "NodeRole")); request.setSubnets(ctx.resolveStringList(props, "Subnets")); + Map templateTags = ctx.resolveTags(props, "Tags"); + request.setTags(ReservedTags.stripReservedTags(templateTags)); Nodegroup nodegroup = eksService.createNodeGroup(clusterName, request); + // The nodegroup this resource named before is gone or replaced; its attributes must not outlive it. + NODEGROUP_ATTRIBUTES.forEach(r.getAttributes()::remove); + publishNodegroup(r, nodegroup); + Ec2Tags.recordKeys(r, NODEGROUP_TAG_KEYS_ATTR, templateTags); + if (updates && !replaces) { + // The nodegroup the update started from is gone, so this one is the update's to undo. + CfnRollback.recordCreatedByUpdate(r, ctx, NODEGROUP_SNAPSHOT_ATTR); + } + if (ctx.isUpdate()) { + ReplacementCleanup.record(r, ctx, attributesBefore, replaces); + } + } + + private void publishNodegroup(StackResource r, Nodegroup nodegroup) { // Ref (and the readOnly Id) is the composite the registry primary identifier declares, // clusterName/nodegroupName, matching AWS. The plain names stay as their own attributes: // ClusterName and NodegroupName back delete() and Fn::GetAtt. @@ -287,23 +382,56 @@ public class EksCfnProvisioner implements CfnResourceProvisioner { } } + /** + * {clusterName, nodegroupName} of a nodegroup: from the composite physical id, or, for a plain + * name a stack from before the composite id holds, from the {@code ClusterName} and + * {@code NodegroupName} attributes. Null when neither names it. + */ + private static String[] nodegroupNames(String physicalId, Map attributes) { + int slash = physicalId == null ? -1 : physicalId.indexOf('/'); + if (slash > 0 && slash < physicalId.length() - 1) { + return new String[] {physicalId.substring(0, slash), physicalId.substring(slash + 1)}; + } + String cluster = attributes.get("ClusterName"); + String nodegroup = attributes.get("NodegroupName"); + if (cluster != null && !cluster.isBlank() && nodegroup != null && !nodegroup.isBlank()) { + return new String[] {cluster, nodegroup}; + } + return null; + } + + private void deleteNodegroup(String physicalId, Map attributes) { + String[] names = nodegroupNames(physicalId, attributes); + if (names == null) { + LOG.warnv("EKS nodegroup {0}: no cluster and nodegroup name to delete it by, treated as gone", physicalId); + return; + } + CfnDeletes.safeDelete("EKS nodegroup", physicalId, () -> eksService.deleteNodeGroup(names[0], names[1]), + "ResourceNotFoundException"); + } + + /** The nodegroup an update starts from, or null when it or its cluster is gone and the update creates one. */ + private Nodegroup liveNodegroup(String clusterName, String nodegroupName) { + return orNullWhenGone(() -> eksService.describeNodeGroup(clusterName, nodegroupName)); + } + + /** + * The update AWS makes for the properties it does not replace on: the nodegroup keeps its name. + * EksService has no UpdateNodegroupConfig or UpdateNodegroupVersion, so the one mutable property + * floci honors is Tags; a change to any other updatable property is accepted with a warning. + */ + private void updateNodegroupInPlace(StackResource r, JsonNode props, ProvisionContext ctx, Nodegroup live, + PropertyChanges changes) { + warnIgnoredChanges("nodegroup", live.getNodegroupName(), changes); + updateTagsInPlace(r, props, ctx, live.getNodegroupArn(), live.getTags(), live.getNodegroupName(), + NODEGROUP_TAG_KEYS_ATTR, NODEGROUP_SNAPSHOT_ATTR, () -> publishNodegroup(r, live), false); + } + @Override public void delete(StackResource resource, String region) { switch (resource.getResourceType()) { case CLUSTER -> delete(CLUSTER, resource.getPhysicalId(), region); - case NODEGROUP -> { - // Deleting a nodegroup needs the cluster name and the nodegroup name, both stored as - // create-time attributes; the physical id is now the composite clusterName/nodegroupName, - // so it cannot be passed as the nodegroup name. - String clusterName = resource.getAttributes().get("ClusterName"); - String nodegroupName = resource.getAttributes().get("NodegroupName"); - if (clusterName != null && !clusterName.isBlank() - && nodegroupName != null && !nodegroupName.isBlank()) { - CfnDeletes.safeDelete("EKS nodegroup", resource.getPhysicalId(), - () -> eksService.deleteNodeGroup(clusterName, nodegroupName), - "ResourceNotFoundException"); - } - } + case NODEGROUP -> deleteNodegroup(resource.getPhysicalId(), resource.getAttributes()); default -> { // No other type reaches this provisioner's delete. } diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ReplacementCleanup.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ReplacementCleanup.java index ce7b9c0d27..757a806dbf 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ReplacementCleanup.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ReplacementCleanup.java @@ -177,10 +177,13 @@ public final class ReplacementCleanup { /** * Whether a revert puts back the prior value of an attribute: the public ones, and the hidden * {@link CfnRollback#USES_ATTR_PREFIX} ones, which describe the entity as the public ones do. - * Other {@code __Floci} keys are rollback bookkeeping that outlives the revert. + * So are the {@code __Floci...TagKeys} records of the tag keys the stack owns, which name the + * live entity's tags as {@link Ec2Tags#recordKeys} writes them. Other {@code __Floci} keys are + * rollback bookkeeping that outlives the revert. */ private static boolean restoredOnRevert(String key) { - return !key.startsWith("__Floci") || key.startsWith(CfnRollback.USES_ATTR_PREFIX); + return !key.startsWith("__Floci") || key.startsWith(CfnRollback.USES_ATTR_PREFIX) + || key.endsWith("TagKeys"); } /** Deletes a rolled-back replacement; one whose delete throws stays owed and named for the retry. */ diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java index 1ef2c0354a..34b7b3e32d 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java @@ -114,6 +114,10 @@ class CfnReplacementIntegrationTest { "True", true, "repl-sng-b"); private static final String EKS_CLUSTER = "\"RoleArn\": \"arn:aws:iam::000000000000:role/repl-eks\", "; + private static final String EKS_NODEGROUP_CLUSTER = "\"Cluster\": {\"Type\": \"AWS::EKS::Cluster\"," + + " \"Properties\": {\"RoleArn\": \"arn:aws:iam::000000000000:role/repl-eks\"}}"; + private static final String EKS_NODEGROUP = "\"ClusterName\": {\"Ref\": \"Cluster\"}," + + " \"Subnets\": [\"subnet-aaaa1111\"], "; private static final String SQS_TYPE = "AWS::SQS::Queue"; private static final String S3_TYPE = "AWS::S3::Bucket"; private static final String DDB_KEYS = "\"BillingMode\": \"PAY_PER_REQUEST\"," @@ -252,6 +256,16 @@ class CfnReplacementIntegrationTest { "\"RoleArn\": \"arn:aws:iam::000000000000:role/repl-eks-@V@\"", "\"RoleArn\": \"arn:aws:iam::000000000000:role/repl-eks-@V@\"", "True", false, null), + createOnlyRow("EKS nodegroup Tags", EKS_NODEGROUP_CLUSTER, "", "AWS::EKS::Nodegroup", + EKS_NODEGROUP + "\"NodeRole\": \"arn:aws:iam::000000000000:role/repl-ng\"," + + " \"Tags\": [{\"Key\": \"team\", \"Value\": \"@V@\"}]", + EKS_NODEGROUP + "\"NodeRole\": \"arn:aws:iam::000000000000:role/repl-ng\"," + + " \"Tags\": [{\"Key\": \"team\", \"Value\": \"@V@\"}]", + "False", false, null), + createOnlyRow("EKS nodegroup NodeRole", EKS_NODEGROUP_CLUSTER, "", "AWS::EKS::Nodegroup", + EKS_NODEGROUP + "\"NodeRole\": \"arn:aws:iam::000000000000:role/repl-ng-@V@\"", + EKS_NODEGROUP + "\"NodeRole\": \"arn:aws:iam::000000000000:role/repl-ng-@V@\"", + "True", false, null), new Row("deployed parameter renamed, same value", locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"), locationStack(stringParameter("NameB", HOSTED), "", REF_B, "e"), diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEksIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEksIntegrationTest.java index cabdbfcb9b..12cb969dd4 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEksIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEksIntegrationTest.java @@ -3,10 +3,14 @@ package io.floci.aws.services.cloudformation; import io.floci.aws.testing.AwsTestClients; import io.floci.aws.testing.CfnStackWaits; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import java.util.List; +import java.util.Map; + import static io.floci.aws.services.cloudformation.CfnStackTestSupport.createUpdateChangeSet; import static io.floci.aws.services.cloudformation.CfnStackTestSupport.executeAndAwaitUpdate; import static io.floci.aws.services.cloudformation.CfnStackTestSupport.physicalId; @@ -15,6 +19,7 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * End-to-end check that CloudFormation provisions EKS resources for real (into EksService) rather @@ -130,6 +135,77 @@ class CloudFormationEksIntegrationTest { } } + @Test + void anUnnamedNodegroupKeepsItsArnAndReconcilesStackTagsWhenOnlyTagsChange() { + String stack = "cfn-eksng-upd-" + Long.toString(System.nanoTime(), 36); + try (CloudFormationClient client = AwsTestClients.create( + CloudFormationClient.builder(), "test", Region.US_EAST_1)) { + CfnStackWaits.createStack(client, stack, nodegroup("one", "{\"Key\": \"old\", \"Value\": \"x\"}"), + "CREATE_COMPLETE"); + String base = "/clusters/" + physicalId(client, stack, "Cluster") + "/node-groups"; + List names = given().get(base).jsonPath().getList("nodegroups"); + assertEquals(1, names.size()); + String arn = given().get(base + "/" + names.getFirst()).jsonPath().getString("nodegroup.nodegroupArn"); + given().contentType("application/json").body(Map.of("tags", Map.of("ext", "1"))) + .post("/tags/" + arn).then().statusCode(200); + + createUpdateChangeSet(client, stack, "tags", nodegroup("two", "")); + executeAndAwaitUpdate(client, stack, "tags"); + + assertEquals(names, given().get(base).jsonPath().getList("nodegroups")); + JsonPath after = given().get(base + "/" + names.getFirst()).jsonPath(); + assertEquals(arn, after.getString("nodegroup.nodegroupArn")); + assertEquals("two", after.getString("nodegroup.tags.team")); + assertEquals("1", after.getString("nodegroup.tags.ext")); + assertNull(after.getString("nodegroup.tags.old")); + } finally { + CfnStackWaits.deleteStack(stack); + } + } + + @Test + void aDroppedTagIsGoneFromTheOriginalNodegroupAfterAReplacementRolledBack() { + String stack = "cfn-eksng-rb-" + Long.toString(System.nanoTime(), 36); + try (CloudFormationClient client = AwsTestClients.create( + CloudFormationClient.builder(), "test", Region.US_EAST_1)) { + CfnStackWaits.createStack(client, stack, rollbackStack("a", "env", "dev", false), "CREATE_COMPLETE"); + String base = "/clusters/" + physicalId(client, stack, "Cluster") + "/node-groups"; + List names = given().get(base).jsonPath().getList("nodegroups"); + + CfnStackWaits.updateStack(client, stack, rollbackStack("b", "team", "a", true), + "UPDATE_ROLLBACK_COMPLETE"); + assertEquals(names, given().get(base).jsonPath().getList("nodegroups")); + + CfnStackWaits.updateStack(client, stack, rollbackStack("a", null, null, false), "UPDATE_COMPLETE"); + assertEquals(names, given().get(base).jsonPath().getList("nodegroups")); + assertNull(given().get(base + "/" + names.getFirst()).jsonPath().getString("nodegroup.tags.env")); + } finally { + CfnStackWaits.deleteStack(stack); + } + } + + private static String rollbackStack(String roleSuffix, String tagKey, String tagValue, boolean laterFails) { + String tags = tagKey == null ? "" : ", \"Tags\": [{\"Key\": \"" + tagKey + + "\", \"Value\": \"" + tagValue + "\"}]"; + String cluster = "\"Cluster\": {\"Type\": \"AWS::EKS::Cluster\", \"Properties\": {\"RoleArn\":" + + " \"arn:aws:iam::000000000000:role/eks-cluster-role\"" + tags + "}}"; + String template = subjectStack(cluster, "", "AWS::EKS::Nodegroup", "\"ClusterName\": {\"Ref\": \"Cluster\"}," + + " \"NodeRole\": \"arn:aws:iam::000000000000:role/eks-node-role-" + roleSuffix + "\"," + + " \"Subnets\": [\"subnet-aaaa1111\"]" + tags); + return laterFails + ? template.substring(0, template.length() - 2) + CfnStackWaits.failingResourceAfter("Subject") + "}}" + : template; + } + + private static String nodegroup(String team, String extraTag) { + String cluster = "\"Cluster\": {\"Type\": \"AWS::EKS::Cluster\", \"Properties\": {\"RoleArn\":" + + " \"arn:aws:iam::000000000000:role/eks-cluster-role\"}}"; + return subjectStack(cluster, "", "AWS::EKS::Nodegroup", "\"ClusterName\": {\"Ref\": \"Cluster\"}," + + " \"NodeRole\": \"arn:aws:iam::000000000000:role/eks-node-role\"," + + " \"Subnets\": [\"subnet-aaaa1111\"], \"Tags\": [{\"Key\": \"team\", \"Value\": \"" + + team + "\"}" + (extraTag.isEmpty() ? "" : ", " + extraTag) + "]"); + } + private static String cluster(String role, String team) { return subjectStack("", "", "AWS::EKS::Cluster", "\"RoleArn\": \"arn:aws:iam::000000000000:role/" + role + "\", \"Tags\": [{\"Key\": \"team\", \"Value\": \"" + team + "\"}]"); diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index d08841c9f9..4f24267b66 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -321,7 +321,6 @@ AWS::EKS::Nodegroup NodeRepairConfig accepted and ignored AWS::EKS::Nodegroup ReleaseVersion accepted and ignored AWS::EKS::Nodegroup RemoteAccess accepted and ignored AWS::EKS::Nodegroup ScalingConfig accepted and ignored -AWS::EKS::Nodegroup Tags accepted and ignored AWS::EKS::Nodegroup Taints accepted and ignored AWS::EKS::Nodegroup UpdateConfig accepted and ignored AWS::EKS::Nodegroup Version accepted and ignored diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index e60fb409ad..9dc54f91ac 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -223,6 +223,7 @@ notes: AWS::Transfer::Server: 'management plane only; Ref returns the server ARN; Arn, ServerId and State attributes supported; AS2 managed egress IPs are not modeled; Domain replacement and IdentityProviderType changes are not supported' AWS::Transfer::User: 'management plane only; Ref returns the user ARN; Arn attribute supported; Policy and PosixProfile are not supported; a ServerId or UserName change replaces the user' AWS::EKS::Cluster: 'created with `Name`, `Version`, `RoleArn` and `Tags`, a replacement included; `EncryptionConfig` and `KubernetesNetworkConfig` are accepted and ignored on create; updated in place for `Tags`, keeping tags added outside the stack; a change to `Name`, `RoleArn`, `EncryptionConfig`, `BootstrapSelfManagedAddons`, `OutpostConfig`, `AccessConfig.BootstrapClusterCreatorAdminPermissions`, `KubernetesNetworkConfig.IpFamily` or `KubernetesNetworkConfig.ServiceIpv4Cidr` replaces the cluster, as the registry marks them create-only, and deletes the old one once the update commits; a change to `Version` is accepted with a warning and not applied, as the emulator cannot upgrade a cluster in place' + AWS::EKS::Nodegroup: 'created with `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets` and `Tags`; updated in place for `Tags`, keeping tags added outside the stack; a change to `ClusterName`, `NodegroupName`, `NodeRole`, `Subnets`, `AmiType`, `CapacityType`, `DiskSize`, `InstanceTypes` or `RemoteAccess` replaces the nodegroup, as the registry marks them create-only, and deletes the old one once the update commits; `ScalingConfig`, `Labels`, `Taints`, `UpdateConfig`, `Version`, `ReleaseVersion`, `ForceUpdateEnabled`, `LaunchTemplate`, `NodeRepairConfig` and `WarmPoolConfig` are accepted and not applied, whether changed or dropped, with a warning, as the emulator cannot update a nodegroup in place' AWS::IAM::User: 'template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete' AWS::IoT::DomainConfiguration: '`ServerCertificates` resolves to a JSON string' AWS::IoT::Policy: 'deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached'