fix(cloudformation): forward ECS service and task definition settings (#7644)

This commit is contained in:
Mario Toffia authored and GitHub committed 2026-11-07 09:51:01 -04:00
1 parent 6e75e4096e
commit 062389b370
10 files changed
+775 -140

No files matched your search

@@ -329,7 +329,11 @@ public class CloudFormationTemplateEngine {
return attribute.isTextual() ? resolveDynamicReferences(attribute.textValue()) : attribute;
}
if (node.has("Fn::Select")) {
return resolveNode(selectedElement(node.get("Fn::Select")));
// The chosen element becomes the value, so AWS::NoValue inside it is left out as it is
// from a value written in place. A directly chosen AWS::NoValue keeps resolving to "".
JsonNode selected = selectedElement(node.get("Fn::Select"));
JsonNode omitted = omitNoValue(selected);
return resolveNode(omitted.isMissingNode() ? selected : omitted);
}
if (node.has("Fn::FindInMap")) {
return resolveNode(findMappedValue(node.get("Fn::FindInMap")));
@@ -10,20 +10,26 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.ecs.EcsService;
import io.floci.aws.services.ecs.model.AwsVpcConfiguration;
import io.floci.aws.services.ecs.model.CapacityProviderStrategyItem;
import io.floci.aws.services.ecs.model.ClusterSetting;
import io.floci.aws.services.ecs.model.ContainerDefinition;
import io.floci.aws.services.ecs.model.CreateServiceRequest;
import io.floci.aws.services.ecs.model.EcsCluster;
import io.floci.aws.services.ecs.model.EcsLoadBalancer;
import io.floci.aws.services.ecs.model.EcsServiceModel;
import io.floci.aws.services.ecs.model.FirelensConfiguration;
import io.floci.aws.services.ecs.model.HealthCheck;
import io.floci.aws.services.ecs.model.KeyValuePair;
import io.floci.aws.services.ecs.model.LaunchType;
import io.floci.aws.services.ecs.model.LogConfiguration;
import io.floci.aws.services.ecs.model.NetworkConfiguration;
import io.floci.aws.services.ecs.model.NetworkMode;
import io.floci.aws.services.ecs.model.PortMapping;
import io.floci.aws.services.ecs.model.RegisterTaskDefinitionRequest;
import io.floci.aws.services.ecs.model.RuntimePlatform;
import io.floci.aws.services.ecs.model.Secret;
import io.floci.aws.services.ecs.model.TaskDefinition;
import io.floci.aws.services.ecs.model.UpdateServiceRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -32,6 +38,7 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
@@ -252,16 +259,18 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
if (family == null || family.isBlank()) {
family = ctx.generatePhysicalName(r.getLogicalId(), 255, false);
}
List<ContainerDefinition> containerDefs = parseContainerDefinitions(props.get("ContainerDefinitions"), ctx);
NetworkMode networkMode = parseEnum(NetworkMode.class, ctx.resolveOptional(props, "NetworkMode"));
String cpu = ctx.resolveOptional(props, "Cpu");
String memory = ctx.resolveOptional(props, "Memory");
String taskRoleArn = ctx.resolveOptional(props, "TaskRoleArn");
String executionRoleArn = ctx.resolveOptional(props, "ExecutionRoleArn");
List<String> requiresCompatibilities = ctx.resolveStringList(props, "RequiresCompatibilities");
RegisterTaskDefinitionRequest request = new RegisterTaskDefinitionRequest();
request.setFamily(family);
request.setContainerDefinitions(parseContainerDefinitions(props.get("ContainerDefinitions"), ctx));
request.setNetworkMode(parseEnum(NetworkMode.class, ctx.resolveOptional(props, "NetworkMode")));
request.setCpu(ctx.resolveOptional(props, "Cpu"));
request.setMemory(ctx.resolveOptional(props, "Memory"));
request.setTaskRoleArn(ctx.resolveOptional(props, "TaskRoleArn"));
request.setExecutionRoleArn(ctx.resolveOptional(props, "ExecutionRoleArn"));
request.setRequiresCompatibilities(ctx.resolveStringList(props, "RequiresCompatibilities"));
request.setRuntimePlatform(parseRuntimePlatform(props.path("RuntimePlatform")));
TaskDefinition td = ecsService.registerTaskDefinition(family, containerDefs, networkMode, cpu, memory,
taskRoleArn, executionRoleArn, requiresCompatibilities, ctx.region());
TaskDefinition td = ecsService.registerTaskDefinition(request, ctx.region());
r.setPhysicalId(td.getTaskDefinitionArn());
r.getAttributes().put("TaskDefinitionArn", td.getTaskDefinitionArn());
@@ -275,6 +284,9 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
* displaced one deleted once the stack update commits, through the replacement cleanup. Either
* way the resource completes only once the service is stable, as CloudFormation's does; an
* in-place update that does not stabilize is put back on the prior configuration.
* {@code AWS::ECS::Service} has no vendored property types, so a value a {@code String}
* parameter gives arrives as text and is converted where ECS expects an integer or a boolean,
* as CloudFormation's handler converts it (measured).
*/
private void provisionService(StackResource r, JsonNode props, ProvisionContext ctx) {
String clusterRef = ctx.resolveOptional(props, "Cluster");
@@ -285,6 +297,12 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
parseLoadBalancers(props != null ? props.get("LoadBalancers") : null, ctx);
NetworkConfiguration networkConfiguration =
parseNetworkConfiguration(props != null ? props.get("NetworkConfiguration") : null, ctx);
Map<String, Object> deploymentConfiguration =
parseDeploymentConfiguration(props != null ? props.get("DeploymentConfiguration") : null, ctx);
List<CapacityProviderStrategyItem> capacityProviderStrategy =
parseCapacityProviderStrategy(props != null ? props.get("CapacityProviderStrategy") : null, ctx);
List<Map<String, Object>> serviceRegistries =
parseServiceRegistries(props != null ? props.get("ServiceRegistries") : null, ctx);
String priorName = r.getAttributes().get("Name");
String serviceName = ctx.resolveOptional(props, "ServiceName");
@@ -298,17 +316,34 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
EcsServiceModel svc;
boolean inPlace = ctx.isUpdate() && serviceName.equals(priorName)
&& clusterName(clusterRef).equals(clusterOfServiceArn(ctx.priorPhysicalId()));
// Read before updateService, which changes this same model in place.
EcsServiceModel prior = inPlace ? ecsService.serviceByArn(ctx.priorPhysicalId()) : null;
String priorTaskDefinition = prior != null ? prior.getTaskDefinition() : null;
Integer priorDesiredCount = prior != null ? prior.getDesiredCount() : null;
NetworkConfiguration priorNetworkConfiguration = prior != null ? prior.getNetworkConfiguration() : null;
UpdateServiceRequest restore;
if (inPlace) {
svc = ecsService.updateService(clusterRef, serviceName, taskDefinition,
desiredCount, networkConfiguration, ctx.region());
UpdateServiceRequest update = new UpdateServiceRequest();
update.setCluster(clusterRef);
update.setService(serviceName);
update.setTaskDefinition(taskDefinition);
update.setDesiredCount(desiredCount);
update.setNetworkConfiguration(networkConfiguration);
update.setDeploymentConfiguration(deploymentConfiguration);
update.setCapacityProviderStrategy(capacityProviderStrategy);
update.setServiceRegistries(serviceRegistries);
// Built before updateService, which changes this same model in place.
restore = restoreRequest(update, ecsService.serviceByArn(ctx.priorPhysicalId()));
svc = ecsService.updateService(update, ctx.region());
} else {
svc = ecsService.createService(clusterRef, serviceName, taskDefinition,
desiredCount, launchType, loadBalancers, networkConfiguration, ctx.region());
CreateServiceRequest create = new CreateServiceRequest();
create.setCluster(clusterRef);
create.setServiceName(serviceName);
create.setTaskDefinition(taskDefinition);
create.setDesiredCount(desiredCount);
create.setLaunchType(launchType);
create.setLoadBalancers(loadBalancers);
create.setNetworkConfiguration(networkConfiguration);
create.setDeploymentConfiguration(deploymentConfiguration);
create.setCapacityProviderStrategy(capacityProviderStrategy);
create.setServiceRegistries(serviceRegistries);
restore = null;
svc = ecsService.createService(create, ctx.region());
}
r.setPhysicalId(svc.getServiceArn());
@@ -318,9 +353,8 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
try {
ecsService.awaitServiceStable(svc);
} catch (RuntimeException failure) {
restoreInPlace(r, failure, () -> ecsService.awaitServiceStable(ecsService.updateService(clusterRef,
svc.getServiceName(), priorTaskDefinition, priorDesiredCount, priorNetworkConfiguration,
ctx.region())));
restoreInPlace(r, failure, () -> ecsService.awaitServiceStable(
ecsService.updateService(restore, ctx.region())));
throw failure;
}
} else {
@@ -329,13 +363,42 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Puts a service updated in place back on the task definition, desired count and network
* configuration it had, when the update does not stabilize, and waits for the restored
* configuration to stabilize, as CloudFormation's rollback does. CloudFormationService restores
* the prior resource record and reports the rollback complete unless told otherwise, so without
* this the stack would claim a rollback while ECS still runs the failed configuration. A
* restore that fails or does not stabilize is attached to the original failure and recorded as
* a rollback failure.
* The update that puts {@code prior} back on what {@code update} changed: its task definition,
* desired count and network configuration, and each setting the update declared. A deployment
* configuration, capacity provider strategy or service registries the service did not have are
* put back empty, so a registry the update added is deregistered; a setting the update left
* unchanged is left unchanged again, so the restore rolls no deployment for registries nobody
* touched.
*/
private static UpdateServiceRequest restoreRequest(UpdateServiceRequest update, EcsServiceModel prior) {
UpdateServiceRequest restore = new UpdateServiceRequest();
restore.setCluster(update.getCluster());
restore.setService(update.getService());
if (prior == null) {
return restore;
}
restore.setTaskDefinition(prior.getTaskDefinition());
restore.setDesiredCount(prior.getDesiredCount());
restore.setNetworkConfiguration(prior.getNetworkConfiguration());
if (update.getDeploymentConfiguration() != null) {
restore.setDeploymentConfiguration(Objects.requireNonNullElse(prior.getDeploymentConfiguration(), Map.of()));
}
if (update.getCapacityProviderStrategy() != null) {
restore.setCapacityProviderStrategy(Objects.requireNonNullElse(prior.getCapacityProviderStrategy(), List.of()));
}
if (update.getServiceRegistries() != null) {
restore.setServiceRegistries(Objects.requireNonNullElse(prior.getServiceRegistries(), List.of()));
}
return restore;
}
/**
* Puts a service updated in place back on the configuration {@link #restoreRequest} captured
* when the update does not stabilize, and waits for the restored configuration to stabilize,
* as CloudFormation's rollback does. CloudFormationService restores the prior resource record
* and reports the rollback complete unless told otherwise, so without this the stack would
* claim a rollback while ECS still runs the failed configuration. A restore that fails or does
* not stabilize is attached to the original failure and recorded as a rollback failure.
*/
private void restoreInPlace(StackResource r, RuntimeException failure, Runnable restore) {
try {
@@ -466,11 +529,36 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
if (item.path("EntryPoint").isArray()) {
def.setEntryPoint(toStringList(item.path("EntryPoint")));
}
if (item.hasNonNull("User")) {
def.setUser(item.path("User").asText());
}
def.setHealthCheck(parseHealthCheck(item.path("HealthCheck")));
result.add(def);
}
return result;
}
private static HealthCheck parseHealthCheck(JsonNode node) {
if (!node.isObject()) {
return null;
}
return new HealthCheck(toStringList(node.path("Command")), optionalInt(node, "Interval"),
optionalInt(node, "Timeout"), optionalInt(node, "Retries"), optionalInt(node, "StartPeriod"));
}
private static Integer optionalInt(JsonNode node, String member) {
return node.hasNonNull(member) ? node.path(member).asInt() : null;
}
private static RuntimePlatform parseRuntimePlatform(JsonNode node) {
String cpuArchitecture = node.path("CpuArchitecture").asText(null);
String operatingSystemFamily = node.path("OperatingSystemFamily").asText(null);
if (cpuArchitecture == null && operatingSystemFamily == null) {
return null;
}
return new RuntimePlatform(cpuArchitecture, operatingSystemFamily);
}
private static LogConfiguration parseLogConfiguration(JsonNode node) {
if (node == null || !node.isObject() || !node.hasNonNull("LogDriver")) {
return null;
@@ -641,6 +729,108 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
return networkConfiguration;
}
private static List<Map<String, Object>> parseServiceRegistries(JsonNode node, ProvisionContext ctx) {
JsonNode resolved = ctx.engine().resolveNode(node);
if (resolved == null || !resolved.isArray()) {
return null;
}
List<Map<String, Object>> result = new ArrayList<>();
for (JsonNode item : resolved) {
// An entry that resolved to AWS::NoValue is not an object.
if (item.isObject()) {
Map<String, Object> registry = new LinkedHashMap<>();
putText(registry, "registryArn", item, "RegistryArn");
putInt(registry, "port", item, "Port");
putText(registry, "containerName", item, "ContainerName");
putInt(registry, "containerPort", item, "ContainerPort");
result.add(registry);
}
}
return result;
}
/** As the ECS handler reads it: an empty strategy is none. */
private static List<CapacityProviderStrategyItem> parseCapacityProviderStrategy(JsonNode node,
ProvisionContext ctx) {
JsonNode resolved = ctx.engine().resolveNode(node);
if (resolved == null || !resolved.isArray()) {
return null;
}
List<CapacityProviderStrategyItem> result = new ArrayList<>();
for (JsonNode item : resolved) {
// An entry that resolved to AWS::NoValue is not an object.
if (item.isObject()) {
result.add(new CapacityProviderStrategyItem(item.path("CapacityProvider").asText(),
item.path("Weight").asInt(0), item.path("Base").asInt(0)));
}
}
return result.isEmpty() ? null : result;
}
/**
* The members of a {@code DeploymentConfiguration} in the API's shape. Its canary, linear and
* lifecycle hook members are not forwarded.
*/
private static Map<String, Object> parseDeploymentConfiguration(JsonNode node, ProvisionContext ctx) {
JsonNode resolved = ctx.engine().resolveNode(node);
if (resolved == null || !resolved.isObject()) {
return null;
}
Map<String, Object> result = new LinkedHashMap<>();
putInt(result, "maximumPercent", resolved, "MaximumPercent");
putInt(result, "minimumHealthyPercent", resolved, "MinimumHealthyPercent");
JsonNode breaker = resolved.path("DeploymentCircuitBreaker");
if (breaker.isObject()) {
Map<String, Object> circuitBreaker = new LinkedHashMap<>();
putBoolean(circuitBreaker, "enable", breaker, "Enable");
putBoolean(circuitBreaker, "rollback", breaker, "Rollback");
putBoolean(circuitBreaker, "resetOnHealthyTask", breaker, "ResetOnHealthyTask");
JsonNode threshold = breaker.path("ThresholdConfiguration");
if (threshold.isObject()) {
Map<String, Object> thresholdConfiguration = new LinkedHashMap<>();
putText(thresholdConfiguration, "type", threshold, "Type");
putInt(thresholdConfiguration, "value", threshold, "Value");
circuitBreaker.put("thresholdConfiguration", thresholdConfiguration);
}
result.put("deploymentCircuitBreaker", circuitBreaker);
}
JsonNode alarms = resolved.path("Alarms");
if (alarms.isObject()) {
Map<String, Object> deploymentAlarms = new LinkedHashMap<>();
if (alarms.hasNonNull("AlarmNames")) {
// Read unresolved, so a list parameter is its items rather than their joined text,
// unless an intrinsic such as Fn::Select produced the member and only the resolved value holds it.
JsonNode names = ctx.engine().omitNoValue(node).path("Alarms").path("AlarmNames");
deploymentAlarms.put("alarmNames", ctx.engine().resolveStringList(
names.isMissingNode() ? alarms.get("AlarmNames") : names));
}
putBoolean(deploymentAlarms, "enable", alarms, "Enable");
putBoolean(deploymentAlarms, "rollback", alarms, "Rollback");
result.put("alarms", deploymentAlarms);
}
putText(result, "strategy", resolved, "Strategy");
putInt(result, "bakeTimeInMinutes", resolved, "BakeTimeInMinutes");
return result;
}
private static void putText(Map<String, Object> target, String key, JsonNode source, String member) {
if (source.hasNonNull(member)) {
target.put(key, source.path(member).asText());
}
}
private static void putInt(Map<String, Object> target, String key, JsonNode source, String member) {
if (source.hasNonNull(member)) {
target.put(key, source.path(member).asInt());
}
}
private static void putBoolean(Map<String, Object> target, String key, JsonNode source, String member) {
if (source.hasNonNull(member)) {
target.put(key, Boolean.parseBoolean(source.path(member).asText().trim()));
}
}
/** An absent or unknown enum value means "not set", as the switch arms treated it. */
private static <E extends Enum<E>> E parseEnum(Class<E> type, String value) {
if (value == null || value.isBlank()) {
@@ -1485,9 +1485,6 @@ public class EcsJsonHandler {
if (node == null || !node.isObject()) {
return null;
}
if (!node.hasNonNull("command") || !node.path("command").isArray() || node.path("command").isEmpty()) {
throw new AwsException("ClientException", "HealthCheck command is required.", 400);
}
List<String> command = jsonArrayToList(node.path("command"));
Integer interval = node.has("interval") ? node.path("interval").asInt() : null;
Integer timeout = node.has("timeout") ? node.path("timeout").asInt() : null;
@@ -49,6 +49,7 @@ import io.floci.aws.services.ecs.model.EcsTaskAddress;
import io.floci.aws.services.ecs.model.EphemeralStorage;
import io.floci.aws.services.ecs.model.Failure;
import io.floci.aws.services.ecs.model.FirelensConfiguration;
import io.floci.aws.services.ecs.model.HealthCheck;
import io.floci.aws.services.ecs.model.KeyValuePair;
import io.floci.aws.services.ecs.model.LaunchType;
import io.floci.aws.services.ecs.model.ListTasksRequest;
@@ -957,6 +958,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
public TaskDefinition registerTaskDefinition(RegisterTaskDefinitionRequest request, String region) {
List<ContainerDefinition> containerDefs = request.getContainerDefinitions();
boolean fargate = request.isFargate();
validateHealthChecks(containerDefs);
validateTaskSize(request, fargate);
validateEphemeralStorage(request.getEphemeralStorage());
validateContainerDependencies(containerDefs);
@@ -1135,6 +1137,18 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
}
private static void validateHealthChecks(List<ContainerDefinition> containerDefs) {
if (containerDefs == null) {
return;
}
for (ContainerDefinition def : containerDefs) {
HealthCheck healthCheck = def.getHealthCheck();
if (healthCheck != null && (healthCheck.command() == null || healthCheck.command().isEmpty())) {
throw new AwsException("ClientException", "HealthCheck command is required.", 400);
}
}
}
/**
* A {@code dependsOn} entry may only name another container of the same task definition, and
* the graph they form has to be acyclic: a cycle would leave every container in it waiting for
@@ -2948,6 +2962,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
throw new AwsException("ServiceNotActiveException",
"Service " + serviceName + " is not active.", 400);
}
// Resolved before anything is applied: a request naming a task definition that cannot
// launch fails without changing the service.
TaskDefinition resolved = request.getTaskDefinition() == null ? null
: resolveLaunchableTaskDefinition(request.getTaskDefinition(), region);
// Settle the outgoing deployment against the service as it stands, before this request
// changes its desired count or task definition: one whose tasks are up has finished,
// whether or not anything read it. recordServiceDeployment stops it if it has not.
@@ -3019,8 +3037,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
}
boolean taskDefChanged = false;
String platformVersionBefore = svc.getPlatformVersion();
if (request.getTaskDefinition() != null) {
TaskDefinition resolved = resolveLaunchableTaskDefinition(request.getTaskDefinition(), region);
if (resolved != null) {
taskDefChanged = !resolved.getTaskDefinitionArn().equals(svc.getTaskDefinition());
svc.setTaskDefinition(resolved.getTaskDefinitionArn());
applyServicePlatform(svc, resolved, request.getPlatformVersion() != null