From 907a2dfbf3739b9c31713728f083609bfb2ec40d Mon Sep 17 00:00:00 2001
From: lex00 <121451605+lex00@users.noreply.github.com>
Date: Wed, 12 Aug 2026 22:47:20 -0600
Subject: [PATCH] feat(cloudformation): provision AWS::ECS::CapacityProvider
and ClusterCapacityProviderAssociations (#1999)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* feat(cloudformation): provision AWS::ECS::CapacityProvider and ClusterCapacityProviderAssociations
Maps both onto the existing EcsService.createCapacityProvider /
putClusterCapacityProviders — provider name generation follows the other
provisioners, associations carry the provider list and default strategy
(weight/base).
Fixes #1998
* refactor(cloudformation): move ECS capacity provisioning into a per-service provisioner
The new resource types from #1998 landed as two more arms of
CloudFormationResourceProvisioner's switch. Move them into the per-service
structure introduced in #1825 so the monolith stops growing:
- EcsCapacityCfnProvisioner owns AWS::ECS::CapacityProvider and
AWS::ECS::ClusterCapacityProviderAssociations and injects only EcsService.
It is picked up by CloudFormationResourceRegistry through CDI, so both switch
arms and their provisionEcsCapacity* methods are gone.
Two review findings are fixed along the way:
- Delete is implemented. Previously stack deletion and create rollback hit the
default arm of the delete dispatch, so a stack could report DELETE_COMPLETE
while the capacity provider stayed registered and the cluster kept its
associations. Deleting the associations resource now detaches the providers
from the cluster, and deleting a capacity provider deregisters it. Both are
idempotent for the already-gone case (rollback, a persistent restore that
dropped the record) and propagate every other AwsException so a genuine
failure still settles the stack into DELETE_FAILED.
- Capacity provider properties are no longer discarded. Only
AutoScalingGroupArn was forwarded and tags were replaced with an empty map,
so ManagedScaling, ManagedTerminationProtection and ManagedDraining silently
vanished. The whole AutoScalingGroupProvider sub-tree is now carried across
with intrinsics resolved and keys decapitalized, which is the shape
CreateCapacityProvider stores, so a provider created by a stack holds the same
state as one created through the ECS API. Tags are parsed from the standard
Key/Value list.
EcsCapacityCfnProvisionerTest covers both types against a single mocked
EcsService, including the full ASG configuration, tags and every delete path.
CloudFormationEcsCapacityIntegrationTest additionally asserts the tags reach
DescribeCapacityProviders and that deleting the stack deregisters the provider.
* fix(cloudformation): update an existing ECS capacity provider instead of recreating it
UpdateStack re-executes every resource with the physical id it got at create
time, and createCapacityProvider rejects a name that already exists, so an
unchanged provider failed the whole update. With no Name declared the
provisioner also minted a fresh generated name on every pass and left the
previous provider behind.
An existing provider is now reused through updateCapacityProvider, an unnamed
one keeps the name its first execution generated, and a provider removed out of
band is recreated rather than reported as a failure. Name and
AutoScalingGroupArn are createOnly, so a change to either is reported as an
unsupported replacement, matching how AWS::IAM::Role handles RoleName.
updateCapacityProvider carries only the Auto Scaling settings, so Tags are
applied separately and a tag the template dropped is removed.
---
.../EcsCapacityCfnProvisioner.java | 276 ++++++++++++++
...udFormationEcsCapacityIntegrationTest.java | 231 ++++++++++++
.../EcsCapacityCfnProvisionerTest.java | 344 ++++++++++++++++++
3 files changed, 851 insertions(+)
create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java
create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEcsCapacityIntegrationTest.java
create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisionerTest.java
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java
new file mode 100644
index 0000000000..6ad70391d4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EcsCapacityCfnProvisioner.java
@@ -0,0 +1,276 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import io.github.hectorvent.floci.services.ecs.EcsService;
+import io.github.hectorvent.floci.services.ecs.model.CapacityProvider;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for ECS capacity: {@code AWS::ECS::CapacityProvider} and
+ * {@code AWS::ECS::ClusterCapacityProviderAssociations}. Injects only {@link EcsService}, per the
+ * per-service provisioner decomposition of {@code CloudFormationResourceProvisioner}.
+ *
+ *
CloudFormation spells these properties in PascalCase while {@code EcsService} stores the ECS
+ * JSON API's camelCase shape (that is what {@code CreateCapacityProvider} puts there). The whole
+ * {@code AutoScalingGroupProvider} sub-tree is therefore carried across with its keys
+ * decapitalized, so a capacity provider created by a stack holds the same state as one created
+ * through the API — including {@code ManagedScaling}, {@code ManagedTerminationProtection} and
+ * {@code ManagedDraining}.
+ */
+@ApplicationScoped
+public class EcsCapacityCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(EcsCapacityCfnProvisioner.class);
+
+ private static final String CAPACITY_PROVIDER = "AWS::ECS::CapacityProvider";
+ private static final String ASSOCIATIONS = "AWS::ECS::ClusterCapacityProviderAssociations";
+
+ private final EcsService ecsService;
+
+ @Inject
+ public EcsCapacityCfnProvisioner(EcsService ecsService) {
+ this.ecsService = ecsService;
+ }
+
+ @Override
+ public Set resourceTypes() {
+ return Set.of(CAPACITY_PROVIDER, ASSOCIATIONS);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case CAPACITY_PROVIDER -> provisionCapacityProvider(r, props, ctx);
+ case ASSOCIATIONS -> provisionAssociations(r, props, ctx);
+ default -> throw new IllegalStateException(
+ "EcsCapacityCfnProvisioner cannot handle " + r.getResourceType());
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ switch (resourceType) {
+ case CAPACITY_PROVIDER -> deleteCapacityProvider(physicalId);
+ // Deleting the association resource leaves the cluster in place with no capacity
+ // providers attached, which is what AWS does: the associations are the resource.
+ case ASSOCIATIONS -> clearAssociations(physicalId, region);
+ default -> { }
+ }
+ }
+
+ private void provisionCapacityProvider(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String existingName = r.getPhysicalId();
+ String declaredName = ctx.resolveOptional(props, "Name");
+ // An unnamed provider keeps the name its first execution generated. Minting a fresh one on
+ // every pass left the previous provider behind with nothing referencing it.
+ String name = declaredName != null && !declaredName.isBlank()
+ ? declaredName
+ : (existingName != null && !existingName.isBlank()
+ ? existingName
+ : ctx.generatePhysicalName(r.getLogicalId(), 255, false));
+
+ if (existingName != null && !existingName.isBlank() && !existingName.equals(name)) {
+ throw new AwsException("ValidationError",
+ "Updating Name requires resource replacement, which is not supported.", 400);
+ }
+
+ Map asgProvider = asgProvider(props, ctx);
+ Map tags = tags(props, ctx);
+
+ // UpdateStack re-executes every resource with the physical id it got at create time, and
+ // createCapacityProvider rejects a name that already exists, so an unchanged provider used
+ // to fail the whole update. An empty result also covers a provider removed out of band,
+ // which is recreated rather than reported as a failure.
+ CapacityProvider existing = existingName == null || existingName.isBlank()
+ ? null
+ : ecsService.describeCapacityProviders(List.of(existingName)).stream()
+ .findFirst().orElse(null);
+
+ if (existing == null) {
+ ecsService.createCapacityProvider(name, asgProvider, tags, ctx.region());
+ } else {
+ if (!Objects.equals(asgArn(existing.getAutoScalingGroupProvider()), asgArn(asgProvider))) {
+ throw new AwsException("ValidationError",
+ "Updating AutoScalingGroupArn requires resource replacement, which is not "
+ + "supported.", 400);
+ }
+ ecsService.updateCapacityProvider(name, asgProvider);
+ applyTags(existing, tags);
+ }
+ // Ref returns the capacity provider name; AWS exposes no Fn::GetAtt attributes here.
+ r.setPhysicalId(name);
+ }
+
+ /** AutoScalingGroupArn is createOnly, so a change to it is a replacement rather than an update. */
+ private static String asgArn(Map asgProvider) {
+ Object arn = asgProvider == null ? null : asgProvider.get("autoScalingGroupArn");
+ return arn == null ? null : arn.toString();
+ }
+
+ /**
+ * Tags are updatable in place. updateCapacityProvider carries only the Auto Scaling settings,
+ * so a tag the template dropped would otherwise survive the update.
+ */
+ private void applyTags(CapacityProvider existing, Map tags) {
+ Map current = existing.getTags() == null ? Map.of() : existing.getTags();
+ List dropped = current.keySet().stream()
+ .filter(key -> !tags.containsKey(key))
+ .toList();
+ if (!dropped.isEmpty()) {
+ ecsService.untagResource(existing.getCapacityProviderArn(), dropped);
+ }
+ if (!tags.isEmpty()) {
+ ecsService.tagResource(existing.getCapacityProviderArn(), tags);
+ }
+ }
+
+ private void provisionAssociations(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String cluster = ctx.resolveOptional(props, "Cluster");
+ List providers = new ArrayList<>();
+ if (props != null && props.has("CapacityProviders")) {
+ for (JsonNode entry : props.get("CapacityProviders")) {
+ String id = ctx.engine().resolve(entry);
+ if (id != null && !id.isBlank()) {
+ providers.add(id);
+ }
+ }
+ }
+ List