fix(cloudformation): keep an ECS service's desired count when an update leaves it out (#8279)

An AWS::ECS::Service update that left DesiredCount out set the service
back to 1. AWS omits it from the update ("For existing services, if a
desired count is not specified, it is omitted from the operation"), so a
count set through UpdateService now stays. A new service without it
still starts at 1, and a rollback puts the count back only when the
update sent one.
This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-14 17:46:51 -04:00
1 parent ade406bac2
commit 4de81e8370
5 files changed
+94 -32

No files matched your search

+2 -1
View File
@@ -850,7 +850,8 @@ a `NatGateway`'s `PrivateIpAddress`, a `PrefixList`'s `MaxEntries`, a `Stage`'s
the instance, but the instance type and the `MetadataOptions` members the template supplied go back to
their defaults, and the instance profile it supplied is disassociated. A service's `TaskDefinition`,
`NetworkConfiguration`, `ServiceName`, `LaunchType`, `LoadBalancers`, `CapacityProviderStrategy` and
`ServiceRegistries` are kept, and its `DesiredCount` goes back to 1. A service's dropped
`ServiceRegistries` are kept, and so is its `DesiredCount`: an update that leaves it out does not send it,
so the stored count stays, while a new service without one starts at 1. A service's dropped
`DeploymentConfiguration` is cleared. An empty `CapacityProviderStrategy` or `ServiceRegistries` in the
template clears it; a failed stabilisation puts the prior values back, and a deployment configuration
the service did not have goes back to none. A `Stage`'s dropped `StageVariables` become empty. A `Route`'s
@@ -291,7 +291,7 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
private void provisionService(StackResource r, JsonNode props, ProvisionContext ctx) {
String clusterRef = ctx.resolveOptional(props, "Cluster");
String taskDefinition = ctx.resolveOptional(props, "TaskDefinition");
int desiredCount = parseDesiredCount(ctx.resolveOptional(props, "DesiredCount"));
Integer desiredCount = parseDesiredCount(ctx.resolveOptional(props, "DesiredCount"));
LaunchType launchType = parseEnum(LaunchType.class, ctx.resolveOptional(props, "LaunchType"));
List<EcsLoadBalancer> loadBalancers =
parseLoadBalancers(props != null ? props.get("LoadBalancers") : null, ctx);
@@ -326,6 +326,7 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
update.setCluster(clusterRef);
update.setService(serviceName);
update.setTaskDefinition(taskDefinition);
// A missing count is left out of the update, as AWS omits it, so the stored count stays.
update.setDesiredCount(desiredCount);
update.setNetworkConfiguration(networkConfiguration);
update.setDeploymentConfiguration(deploymentConfiguration);
@@ -346,7 +347,7 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
create.setCluster(clusterRef);
create.setServiceName(serviceName);
create.setTaskDefinition(taskDefinition);
create.setDesiredCount(desiredCount);
create.setDesiredCount(desiredCount != null ? desiredCount : 1);
create.setLaunchType(launchType);
create.setLoadBalancers(loadBalancers);
create.setNetworkConfiguration(networkConfiguration);
@@ -389,13 +390,13 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
}
/**
* 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 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. The
* deployment configuration is not here: updateService cannot put back none, so the caller
* restores it exactly through replaceServiceDeploymentConfiguration.
* The update that puts {@code prior} back on what {@code update} changed: its task definition
* and network configuration, and each setting the update declared, the desired count among
* them. A 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. The deployment configuration is not here: updateService cannot put back none, so
* the caller restores it exactly through replaceServiceDeploymentConfiguration.
*/
private static UpdateServiceRequest restoreRequest(UpdateServiceRequest update, EcsServiceModel prior) {
UpdateServiceRequest restore = new UpdateServiceRequest();
@@ -405,7 +406,9 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
return restore;
}
restore.setTaskDefinition(prior.getTaskDefinition());
restore.setDesiredCount(prior.getDesiredCount());
if (update.getDesiredCount() != null) {
restore.setDesiredCount(prior.getDesiredCount());
}
restore.setNetworkConfiguration(prior.getNetworkConfiguration());
if (update.getCapacityProviderStrategy() != null) {
restore.setCapacityProviderStrategy(Objects.requireNonNullElse(prior.getCapacityProviderStrategy(), List.of()));
@@ -868,10 +871,10 @@ public class EcsCfnProvisioner implements CfnResourceProvisioner {
}
}
/** DesiredCount defaults to 1 when absent; anything present has to be an integer. */
private static int parseDesiredCount(String value) {
/** An absent DesiredCount is null (1 at create, left out at update); anything present has to be an integer. */
private static Integer parseDesiredCount(String value) {
if (value == null || value.isBlank()) {
return 1;
return null;
}
try {
return Integer.parseInt(value.trim());
@@ -10,10 +10,14 @@ import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static io.floci.aws.testing.CfnRequests.cfn;
import static org.hamcrest.Matchers.containsString;
@@ -358,17 +362,48 @@ class CloudFormationEcsForwardedSettingsIntegrationTest {
.body("services[0].capacityProviderStrategy[0].capacityProvider", equalTo("FARGATE_SPOT"));
}
@Test
void updateStack_droppedDesiredCount_setsTheDesiredCountToOne() {
String name = stackName();
submitService("CreateStack", name, 3);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
describeService(name).body("services[0].desiredCount", equalTo(3));
/**
* One row per case of the AWS::ECS::Service DesiredCount contract: a new service without it gets 1, and an
* update that leaves it out omits it from UpdateService, so the stored count stays. Columns: the declaration
* at create (null: none), the count set through the ECS API after create (null: none), the declaration at
* update (null: none), the count DescribeServices reports at the end.
*/
private static Stream<Arguments> desiredCountCases() {
String noValue = "{\"Fn::If\": [\"Never\", 3, {\"Ref\": \"AWS::NoValue\"}]}";
return Stream.of(
Arguments.of("createWithoutIt", null, null, null, 1),
Arguments.of("updateDropsIt", "3", null, null, 3),
Arguments.of("neverDeclaredButSetThroughTheApi", null, 4, null, 4),
Arguments.of("updateChoosesNoValue", "3", null, noValue, 3),
Arguments.of("updateDeclaresZero", "3", null, "0", 0));
}
submitTemplate("UpdateStack", name, serviceTemplate(name, 0).replace("\"DesiredCount\": 0,", ""));
@ParameterizedTest(name = "{0}")
@MethodSource("desiredCountCases")
void updateStack_desiredCount_followsTheContract(String row, String atCreate, Integer setThroughTheApi,
String atUpdate, int expected) {
String name = stackName();
submitTemplate("CreateStack", name, withDesiredCount(name, atCreate, REGISTRIES_SETTING));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
if (atCreate == null && setThroughTheApi == null) {
describeService(name).body("services[0].desiredCount", equalTo(expected));
return;
}
if (setThroughTheApi != null) {
ecs("UpdateService", "{\"cluster\": \"%1$s\", \"service\": \"%1$s-svc\", \"desiredCount\": %2$d}"
.formatted(name, setThroughTheApi));
}
submitTemplate("UpdateStack", name, withDesiredCount(name, atUpdate, STRATEGY_SETTING));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status());
describeService(name).body("services[0].desiredCount", equalTo(1));
describeService(name).body("services[0].desiredCount", equalTo(expected));
}
/** SERVICE_TEMPLATE with DesiredCount set to {@code value} (a JSON value), or without the property when null. */
private static String withDesiredCount(String stackName, String value, String setting) {
return serviceTemplate(stackName, 0, setting)
.replace("\"DesiredCount\": 0,", value == null ? "" : "\"DesiredCount\": " + value + ",");
}
private void createServiceStack(String name, String... settings) {
@@ -36,6 +36,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -340,12 +341,12 @@ class EcsCfnProvisionerTest {
&& request.getNetworkConfiguration() == null);
}
/** An UpdateService request for {@code service} in {@code cluster} with this task definition and desired count. */
/** An UpdateService request for {@code service} in {@code cluster} with this task definition and desired count (null: none sent). */
private static UpdateServiceRequest updating(String cluster, String service, String taskDefinition,
int desiredCount) {
Integer desiredCount) {
return argThat(request -> request != null && cluster.equals(request.getCluster())
&& service.equals(request.getService()) && taskDefinition.equals(request.getTaskDefinition())
&& Integer.valueOf(desiredCount).equals(request.getDesiredCount())
&& Objects.equals(desiredCount, request.getDesiredCount())
&& request.getNetworkConfiguration() == null);
}
@@ -424,7 +425,7 @@ class EcsCfnProvisionerTest {
@Test
void anUnnamedServiceKeepsTheNameItGotAtCreateTime() {
when(ecs.updateService(updating("web", "my-stack-Service-abc", TASK_DEF_ARN, 1), eq(REGION)))
when(ecs.updateService(updating("web", "my-stack-Service-abc", TASK_DEF_ARN, null), eq(REGION)))
.thenReturn(service("my-stack-Service-abc"));
StackResource r = resource("AWS::ECS::Service", "Service");
r.getAttributes().put("Name", "my-stack-Service-abc");
@@ -432,7 +433,7 @@ class EcsCfnProvisionerTest {
provisioner.provision(r, mapper.createObjectNode().put("Cluster", "web").put("TaskDefinition", TASK_DEF_ARN),
ctx("arn:aws:ecs:us-east-1:000000000000:service/web/my-stack-Service-abc"));
verify(ecs).updateService(updating("web", "my-stack-Service-abc", TASK_DEF_ARN, 1), eq(REGION));
verify(ecs).updateService(updating("web", "my-stack-Service-abc", TASK_DEF_ARN, null), eq(REGION));
}
@Test
@@ -480,7 +481,7 @@ class EcsCfnProvisionerTest {
@Test
void theClusterGivenAsAnArnStillCountsAsTheSameCluster() {
when(ecs.updateService(updating(CLUSTER_ARN, "front", TASK_DEF_ARN, 1), eq(REGION)))
when(ecs.updateService(updating(CLUSTER_ARN, "front", TASK_DEF_ARN, null), eq(REGION)))
.thenReturn(service("front"));
StackResource r = resource("AWS::ECS::Service", "Service");
r.getAttributes().put("Name", "front");
@@ -488,7 +489,7 @@ class EcsCfnProvisionerTest {
provisioner.provision(r, mapper.createObjectNode()
.put("Cluster", CLUSTER_ARN).put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN), ctx(SERVICE_ARN));
verify(ecs).updateService(updating(CLUSTER_ARN, "front", TASK_DEF_ARN, 1), eq(REGION));
verify(ecs).updateService(updating(CLUSTER_ARN, "front", TASK_DEF_ARN, null), eq(REGION));
assertFalse(provisioner.hasReplacementUpdate(r), "an in-place update owes no cleanup");
}
@@ -1260,6 +1261,28 @@ class EcsCfnProvisionerTest {
assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
@Test
void aRestoreAfterAnUpdateThatSentNoDesiredCountSendsNoneEither() {
EcsServiceModel prior = service("front");
prior.setTaskDefinition(TASK_DEF_ARN);
prior.setDesiredCount(2);
when(ecs.serviceByArn(SERVICE_ARN)).thenReturn(prior);
EcsServiceModel updated = service("front");
EcsServiceModel restored = service("front");
when(ecs.updateService(any(UpdateServiceRequest.class), eq(REGION))).thenReturn(updated, restored);
doThrow(new AwsException("NotStabilized", "did not stabilize", 500)).when(ecs).awaitServiceStable(updated);
StackResource r = resource("AWS::ECS::Service", "Service");
r.getAttributes().put("Name", "front");
assertThrows(AwsException.class, () -> provisioner.provision(r, mapper.createObjectNode()
.put("Cluster", "web").put("ServiceName", "front").put("TaskDefinition", TASK_DEF_ARN), ctx(SERVICE_ARN)));
ArgumentCaptor<UpdateServiceRequest> requests = ArgumentCaptor.forClass(UpdateServiceRequest.class);
verify(ecs, times(2)).updateService(requests.capture(), eq(REGION));
// A count an autoscaler or the API set during the wait must not be overwritten by the restore.
assertNull(requests.getAllValues().get(1).getDesiredCount(), "the update sent no count, so the restore restores none");
}
private static final String SERVICE_REGISTRIES = "ServiceRegistries";
private static final String CAPACITY_PROVIDER_STRATEGY = "CapacityProviderStrategy";
private static final String DEPLOYMENT_CONFIGURATION_PROPERTY = "DeploymentConfiguration";
@@ -1578,12 +1601,12 @@ class EcsCfnProvisionerTest {
}
@Test
void aDroppedDesiredCountSetsTheDesiredCountToOne() {
void aDroppedDesiredCountIsOmittedFromTheUpdate() {
ObjectNode prior = serviceProps().put("DesiredCount", "3");
UpdateServiceRequest request = updateFrom(prior, serviceProps());
assertEquals(1, request.getDesiredCount());
assertNull(request.getDesiredCount());
verifyNoDeploymentConfigurationReplacement();
}
@@ -136,7 +136,7 @@ AWS::EC2::Subnet VpcId create-only a drop is refused
AWS::ECS::Service CapacityProviderStrategy keep:AWS documents a removed strategy as no update; a declared empty list clears it
AWS::ECS::Service Cluster create-only
AWS::ECS::Service DeploymentConfiguration clear it is stored as none, so it reads back as never set; a declared {} is stored as given
AWS::ECS::Service DesiredCount default:1
AWS::ECS::Service DesiredCount keep:AWS omits it from the update, so the stored count stays
AWS::ECS::Service LaunchType keep:the provisioner leaves it out of the update, so the stored value stays
AWS::ECS::Service LoadBalancers keep:the provisioner leaves it out of the update, so the stored value stays
AWS::ECS::Service NetworkConfiguration keep:the update leaves a missing network configuration unchanged
1 AWS::ApiGatewayV2::Authorizer ApiId create-only a drop fails: the authorizer is not found
136 AWS::ECS::Service CapacityProviderStrategy keep:AWS documents a removed strategy as no update; a declared empty list clears it
137 AWS::ECS::Service Cluster create-only
138 AWS::ECS::Service DeploymentConfiguration clear it is stored as none, so it reads back as never set; a declared {} is stored as given
139 AWS::ECS::Service DesiredCount default:1 keep:AWS omits it from the update, so the stored count stays
140 AWS::ECS::Service LaunchType keep:the provisioner leaves it out of the update, so the stored value stays
141 AWS::ECS::Service LoadBalancers keep:the provisioner leaves it out of the update, so the stored value stays
142 AWS::ECS::Service NetworkConfiguration keep:the update leaves a missing network configuration unchanged