Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(cloudformation): store ECS service network and load balancer config in the API shape (#1916)

iot-rocketb3a14980d0a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2866b788..6f1cd3d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudFormation — `AWS::EC2::VPCGatewayAttachment` updates in place** — a changed `InternetGatewayId` or `VpnGatewayId` moves the attachment under the same `IGW|vpc-…` / `VGW|vpc-…` physical id, `VpnGatewayId` is attached at all, and a `VpcId` change leaves the gateway attached to the new VPC, or to the old one when the update rolls back.
- **CloudFormation — `AWS::Lambda::Version` publishes through `PublishVersion`** — the version takes its `Description`, a version of a function unchanged since its latest version fails with the `AlreadyExists` error AWS reports, `FunctionScalingConfig` on a function without a capacity provider is refused, and a function keeps its `CapacityProviderConfig`. Contributed by @iot-rocket.
+- **CloudFormation — `AWS::ECS::Service` stores `NetworkConfiguration` and `LoadBalancers` in the ECS API shape** — `DescribeServices` returns them in camelCase on create and update, and a service from a template registers its tasks in its target groups.
- **SESv2 — `CreateEmailIdentity`/`GetEmailIdentity` return Easy DKIM tokens for a DOMAIN identity** — a domain identity created without `DkimSigningAttributes` answered an empty `Tokens` list with `Status: NOT_STARTED`. AWS provides a set of DKIM tokens for its CNAME records in that case (Easy DKIM), so the Terraform `aws_sesv2_email_identity` resource's `dkim_signing_attributes[0].tokens` indexing failed. A DOMAIN identity now gets three tokens, `SigningAttributesOrigin: AWS_SES` and `Status: PENDING`, unless `DkimSigningAttributes` brings its own key (BYODKIM); EMAIL_ADDRESS identities are unchanged.
- **API Gateway v2 (HTTP API) — a missing identity source is a 401 without caching too** — a REQUEST authorizer's short circuit for a declared identity source missing from the request only fired with `authorizerResultTtlInSeconds` caching on; with caching off the authorizer was invoked. AWS answers `401 {"message":"Unauthorized"}` (compact JSON) without invoking it either way, as observed on a deployed HTTP API with a TTL of 0. `$context.*` identity sources, which MiniStack does not model, do not count as missing without caching.
### Added
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index fdcb91e9..db40ede9 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -7655,8 +7655,8 @@ def _ecs_service_create(logical_id, props, stack_name):
"taskDefinition": props.get("TaskDefinition", ""),
"desiredCount": props.get("DesiredCount", 1),
"launchType": props.get("LaunchType", "EC2"),
- "loadBalancers": props.get("LoadBalancers", []),
- "networkConfiguration": props.get("NetworkConfiguration", {}),
+ "loadBalancers": _pascal_to_camel(props.get("LoadBalancers") or []),
+ "networkConfiguration": _pascal_to_camel(props.get("NetworkConfiguration") or {}),
"tags": [{"key": t["Key"], "value": t["Value"]} for t in props.get("Tags", [])],
}
deployment_configuration = _ecs_deployment_configuration(props)
@@ -7683,7 +7683,7 @@ def _ecs_service_update(physical_id, old_props, new_props, stack_name):
}
for cf_property, ecs_property in property_map.items():
if new_props.get(cf_property) != old_props.get(cf_property):
- request[ecs_property] = new_props.get(cf_property)
+ request[ecs_property] = _pascal_to_camel(new_props.get(cf_property))
if (new_props.get("DeploymentConfiguration")
!= old_props.get("DeploymentConfiguration")):
diff --git a/ministack/services/ecs.py b/ministack/services/ecs.py
index 5a5533e7..59cbabff 100644
--- a/ministack/services/ecs.py
+++ b/ministack/services/ecs.py
@@ -738,19 +738,14 @@ def _requested_subnet(data):
Nothing else read the request's network configuration until now, so this
cannot assume the shape the SDK would have sent: a body that names it as
anything but the documented object has no subnet to report.
-
- Both casings are read. A service created through CloudFormation keeps the
- template's `NetworkConfiguration` verbatim (provisioners.py, the
- AWS::ECS::Service handler) and replays it here, so the camelCase lookup
- alone would miss every CFN-defined service.
"""
network = data.get("networkConfiguration")
if not isinstance(network, dict):
return None
- config = network.get("awsvpcConfiguration") or network.get("AwsvpcConfiguration")
+ config = network.get("awsvpcConfiguration")
if not isinstance(config, dict):
return None
- subnets = config.get("subnets") or config.get("Subnets")
+ subnets = config.get("subnets")
if not isinstance(subnets, list) or not subnets:
return None
return subnets[0] if isinstance(subnets[0], str) else None
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index ad8e546f..c6f4fe5b 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -18018,6 +18018,72 @@ def test_cfn_ecs_cluster_settings_read_back_in_the_api_shape(cfn, ecs):
_delete_cfn_test_stack(cfn, stack_name)
+def test_cfn_ecs_service_network_and_load_balancers_read_back_in_the_api_shape(cfn, ecs, elbv2):
+ """NetworkConfiguration and LoadBalancers read back in camelCase, on create and on update."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-ecs-svc-shape-{suffix}"
+ tg_arn = elbv2.create_target_group(
+ Name=f"cfn-ecs-shape-{suffix}", Protocol="HTTP", Port=80,
+ VpcId="vpc-00000000", TargetType="ip")["TargetGroups"][0]["TargetGroupArn"]
+
+ def template(public):
+ return json.dumps({
+ "Resources": {
+ "Cluster": {"Type": "AWS::ECS::Cluster",
+ "Properties": {"ClusterName": stack_name}},
+ "TD": {
+ "Type": "AWS::ECS::TaskDefinition",
+ "Properties": {
+ "Family": stack_name,
+ "NetworkMode": "awsvpc",
+ "ContainerDefinitions": [{"Name": "app", "Image": "nginx", "Memory": 128}],
+ },
+ },
+ "Service": {
+ "Type": "AWS::ECS::Service",
+ "Properties": {
+ "Cluster": {"Ref": "Cluster"},
+ "ServiceName": stack_name,
+ "TaskDefinition": {"Ref": "TD"},
+ "DesiredCount": 0,
+ "NetworkConfiguration": {"AwsvpcConfiguration": {
+ "Subnets": ["subnet-0a1b2c3d"],
+ "SecurityGroups": ["sg-0a1b2c3d"],
+ "AssignPublicIp": public,
+ }},
+ "LoadBalancers": [{"TargetGroupArn": tg_arn,
+ "ContainerName": "app", "ContainerPort": 80}],
+ },
+ },
+ },
+ })
+
+ def described():
+ return ecs.describe_services(cluster=stack_name, services=[stack_name])["services"][0]
+
+ def network(public):
+ return {"awsvpcConfiguration": {"subnets": ["subnet-0a1b2c3d"],
+ "securityGroups": ["sg-0a1b2c3d"],
+ "assignPublicIp": public}}
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("DISABLED"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ service = described()
+ assert service["networkConfiguration"] == network("DISABLED")
+ assert service["loadBalancers"] == [
+ {"targetGroupArn": tg_arn, "containerName": "app", "containerPort": 80}]
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("ENABLED"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert described()["networkConfiguration"] == network("ENABLED")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ elbv2.delete_target_group(TargetGroupArn=tg_arn)
+
+
# ===========================================================================
# In-place update handlers — deploy, update a mutable property, assert the
# physical id survived and the new value is visible through the service API
diff --git a/tests/test_ecs.py b/tests/test_ecs.py
index 734e8c73..bcf55bfc 100644
--- a/tests/test_ecs.py
+++ b/tests/test_ecs.py
@@ -2820,33 +2820,34 @@ def test_ecs_awsvpc_attachment_carries_the_subnet_it_was_placed_in(monkeypatch):
assert details["privateIPv4Address"] == "172.30.0.11"
-def test_ecs_awsvpc_attachment_reads_the_cloudformation_casing(monkeypatch):
- """A CloudFormation service replays its template's `NetworkConfiguration`.
-
- The AWS::ECS::Service handler stores the template block verbatim, so it
- reaches RunTask in PascalCase. Reading only the SDK's casing would leave
- every CFN-defined service's tasks without a subnet.
- """
+def test_ecs_cloudformation_service_places_and_registers_its_tasks(monkeypatch):
+ """A CloudFormation service's tasks get the template's subnet and join its target group."""
+ from ministack.services import alb as _alb
from ministack.services import ecs as _ecs
+ from ministack.services.cloudformation.provisioners import _RESOURCE_HANDLERS
monkeypatch.setattr(_ecs, "_get_docker", lambda: _eni_probe_docker("172.30.0.41"))
+ tg_arn = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/tg-cfncase/abc123"
+ _alb._tgs[tg_arn] = {"TargetGroupArn": tg_arn, "Port": 80, "TargetType": "ip"}
+ _alb._targets[tg_arn] = []
_ecs._register_task_definition({
"family": "eni-cfncase-td",
"networkMode": "awsvpc",
"containerDefinitions": [{"name": "web", "image": "busybox"}],
})
- task_arn = json.loads(_ecs._run_task({
- "cluster": "eni-cfncase-c",
- "taskDefinition": "eni-cfncase-td",
- "networkConfiguration": {"AwsvpcConfiguration": {
- "Subnets": ["subnet-cfn00001"],
- }},
- })[2])["tasks"][0]["taskArn"]
-
- _wait_until(lambda: _ecs._tasks[task_arn].get("attachments"))
- details = {d["name"]: d["value"]
- for d in _ecs._tasks[task_arn]["attachments"][0]["details"]}
+ _RESOURCE_HANDLERS["AWS::ECS::Service"]["create"]("Service", {
+ "Cluster": "eni-cfncase-c",
+ "ServiceName": "eni-cfncase-svc",
+ "TaskDefinition": "eni-cfncase-td",
+ "DesiredCount": 1,
+ "NetworkConfiguration": {"AwsvpcConfiguration": {"Subnets": ["subnet-cfn00001"]}},
+ "LoadBalancers": [{"TargetGroupArn": tg_arn, "ContainerName": "web", "ContainerPort": 80}],
+ }, "eni-cfncase")
+ _wait_until(lambda: _alb._targets.get(tg_arn) == [{"Id": "172.30.0.41", "Port": 80}])
+ task = next(t for t in _ecs._tasks.values() if t.get("group") == "service:eni-cfncase-svc")
+ details = {d["name"]: d["value"] for d in task["attachments"][0]["details"]}
assert details["subnetId"] == "subnet-cfn00001"
+ _ecs._delete_service({"cluster": "eni-cfncase-c", "service": "eni-cfncase-svc", "force": True})
@pytest.mark.parametrize("network_configuration", [