Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(batch): add UpdateComputeEnvironment for Terraform update_policy (#1088) (#1096)
vvaidebb50918ef738
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 46ff2971..9226ddf0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Added+- **Batch — `UpdateComputeEnvironment`** — Terraform `aws_batch_compute_environment` with an `update_policy` block calls `UpdateComputeEnvironment`, which previously failed with `InvalidAction: Unsupported batch path: /v1/updatecomputeenvironment`. The endpoint now resolves compute environments by name or ARN, applies present fields (`state`, `serviceRole`, shallow-merged `computeResources`, `updatePolicy`, `unmanagedvCpus`, `context`), and returns them from `DescribeComputeEnvironments`. Reported by @smoores-dev (#1088).+## [1.4.3] — 2026-07-18### Addeddiff --git a/README.md b/README.mdindex 6c457729..da081056 100644--- a/README.md+++ b/README.md@@ -578,7 +578,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i| **Organizations** | DescribeOrganization, ListRoots, ListAccounts, ListAccountsForParent, DescribeAccount, CreateOrganizationalUnit, DescribeOrganizationalUnit, DeleteOrganizationalUnit, ListOrganizationalUnitsForParent, ListParents, TagResource, UntagResource, ListTagsForResource | Single-master-account org auto-initialised on first call; nested OUs with `Path` field (additive 2026-03 AWS change); the `aws_organizations_organizational_unit` Read calls `ListParents` (single parent, `ROOT`/`ORGANIZATIONAL_UNIT`, to populate `parent_id`) **and** `ListTagsForResource` on every refresh, so both — plus `TagResource`/`UntagResource` — round-trip and a multi-OU hierarchy applies cleanly + idempotently; `FeatureSet=ALL` || **Account** | GetAccountInformation, GetContactInformation, ListRegions, GetRegionOptStatus | rest-json `/getAccountInformation`, etc.; returns `AccountState=ACTIVE` (additive 2026-04 AWS change); 31-region opt-in matrix || **WAF (Classic + Regional)** | List* (17 ops), Get*, GetChangeToken, GetChangeTokenStatus, GetPermissionPolicy, Create*/Update*/Delete* (stubbed) | Minimal v1 stub — empty lists for all `List*`, valid ChangeToken on Create/Update/Delete; for full features use **wafv2** (also supported) |-| **Batch** | CreateComputeEnvironment, DescribeComputeEnvironments, CreateJobQueue, DescribeJobQueues, RegisterJobDefinition, DescribeJobDefinitions, SubmitJob, DescribeJobs, ListJobs | Control-plane stub — submitted jobs immediately transition to `SUCCEEDED`; multi-revision job definitions; `jobQueue` lookup by name or ARN; account-scoped state |+| **Batch** | CreateComputeEnvironment, UpdateComputeEnvironment, DescribeComputeEnvironments, CreateJobQueue, DescribeJobQueues, RegisterJobDefinition, DescribeJobDefinitions, SubmitJob, DescribeJobs, ListJobs | Control-plane stub — submitted jobs immediately transition to `SUCCEEDED`; multi-revision job definitions; `jobQueue` lookup by name or ARN; account-scoped state |---diff --git a/ministack/services/batch.py b/ministack/services/batch.pyindex a26fe72a..981bfbc1 100644--- a/ministack/services/batch.py+++ b/ministack/services/batch.py@@ -82,6 +82,42 @@ def _job_arn(job_id):return f"arn:aws:batch:{get_region()}:{get_account_id()}:job/{job_id}"+_CE_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,128}$")+++def _compute_environment_name_from_ref(ref):+ if not ref:+ return "", error_response_json(+ "ClientException", "computeEnvironment is required", 400+ )+ if not ref.startswith("arn:"):+ return ref, None+ try:+ spec = parse_arn(ref)+ except ArnParseError:+ return "", error_response_json(+ "ClientException", f"Object does not exist: {ref}", 400+ )+ if spec.service != "batch" or spec.account_id != get_account_id():+ return "", error_response_json(+ "ClientException", f"Object does not exist: {ref}", 400+ )+ if spec.region != get_region():+ return "", error_response_json(+ "ClientException", f"Object does not exist: {ref}", 400+ )+ if not spec.resource.startswith("compute-environment/"):+ return "", error_response_json(+ "ClientException", f"Object does not exist: {ref}", 400+ )+ name = spec.resource.split("/", 1)[1]+ if not _CE_NAME_RE.fullmatch(name):+ return "", error_response_json(+ "ClientException", f"Object does not exist: {ref}", 400+ )+ return name, None++def _job_queue_name_from_ref(ref):if not ref or not ref.startswith("arn:"):return ref, None@@ -139,11 +175,47 @@ def _create_compute_environment(p):"serviceRole": p.get("serviceRole", ""),"tags": p.get("tags", {}),}+ if "unmanagedvCpus" in p:+ rec["unmanagedvCpus"] = p["unmanagedvCpus"]+ if "context" in p:+ rec["context"] = p["context"]_compute_envs[name] = recreturn _json(200, {"computeEnvironmentName": name,"computeEnvironmentArn": rec["computeEnvironmentArn"]})+def _update_compute_environment(p):+ name, error = _compute_environment_name_from_ref(p.get("computeEnvironment"))+ if error:+ return error+ rec = _compute_envs.get(name)+ if rec is None:+ return error_response_json(+ "ClientException", f"Object does not exist: {name}", 400+ )+ if "state" in p:+ rec["state"] = p["state"]+ if "serviceRole" in p:+ rec["serviceRole"] = p["serviceRole"]+ if "computeResources" in p and p["computeResources"] is not None:+ existing = rec.get("computeResources") or {}+ if not isinstance(existing, dict):+ existing = {}+ merged = dict(existing)+ merged.update(p["computeResources"])+ rec["computeResources"] = merged+ if "updatePolicy" in p:+ rec["updatePolicy"] = p["updatePolicy"]+ if "unmanagedvCpus" in p:+ rec["unmanagedvCpus"] = p["unmanagedvCpus"]+ if "context" in p:+ rec["context"] = p["context"]+ return _json(200, {+ "computeEnvironmentName": name,+ "computeEnvironmentArn": rec["computeEnvironmentArn"],+ })++def _describe_compute_environments(p):names = p.get("computeEnvironments") or []if names:@@ -275,6 +347,7 @@ def _list_jobs(p):_DISPATCH = {"/v1/createcomputeenvironment": _create_compute_environment,+ "/v1/updatecomputeenvironment": _update_compute_environment,"/v1/describecomputeenvironments": _describe_compute_environments,"/v1/createjobqueue": _create_job_queue,"/v1/describejobqueues": _describe_job_queues,diff --git a/tests/test_batch.py b/tests/test_batch.pyindex 974f4a25..30855453 100644--- a/tests/test_batch.py+++ b/tests/test_batch.py@@ -1,8 +1,10 @@+import os+import boto3import pytestfrom botocore.exceptions import ClientError-ENDPOINT = "http://localhost:4566"+ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")REGION = "us-east-1"@@ -159,3 +161,173 @@ def test_batch_account_isolation():b_qs = [q["jobQueueName"] for q in b.describe_job_queues()["jobQueues"]]assert name in a_qsassert name not in b_qs+++def test_batch_update_compute_environment_create_update_describe(batch):+ """UpdateComputeEnvironment persists fields that DescribeComputeEnvironments returns."""+ name = f"ce-upd-{_uid()}"+ role = "arn:aws:iam::000000000000:role/batch"+ new_role = "arn:aws:iam::000000000000:role/batch-updated"+ created = batch.create_compute_environment(+ computeEnvironmentName=name,+ type="MANAGED",+ state="ENABLED",+ serviceRole=role,+ computeResources={+ "type": "EC2",+ "minvCpus": 0,+ "maxvCpus": 4,+ "instanceTypes": ["m5.large"],+ "subnets": ["subnet-aaa"],+ "securityGroupIds": ["sg-aaa"],+ },+ )+ assert created["computeEnvironmentName"] == name+ assert created["computeEnvironmentArn"].endswith(f"compute-environment/{name}")+ assert "updatePolicy" not in batch.describe_compute_environments(+ computeEnvironments=[name]+ )["computeEnvironments"][0]++ updated = batch.update_compute_environment(+ computeEnvironment=name,+ state="DISABLED",+ serviceRole=new_role,+ updatePolicy={+ "jobExecutionTimeoutMinutes": 60,+ "terminateJobsOnUpdate": True,+ },+ unmanagedvCpus=2,+ context="tf-update",+ )+ assert updated["computeEnvironmentName"] == name+ assert updated["computeEnvironmentArn"] == created["computeEnvironmentArn"]++ described = batch.describe_compute_environments(computeEnvironments=[name])[+ "computeEnvironments"+ ]+ assert len(described) == 1+ ce = described[0]+ assert ce["state"] == "DISABLED"+ assert ce["serviceRole"] == new_role+ assert ce["updatePolicy"] == {+ "jobExecutionTimeoutMinutes": 60,+ "terminateJobsOnUpdate": True,+ }+ assert ce["unmanagedvCpus"] == 2+ assert ce["context"] == "tf-update"+++def test_batch_update_policy_is_update_only(batch):+ model = batch.meta.service_model+ create = model.operation_model("CreateComputeEnvironment").input_shape.members+ update = model.operation_model("UpdateComputeEnvironment").input_shape.members+ assert "updatePolicy" not in create+ assert "updatePolicy" in update++ from ministack.services import batch as batch_svc++ name = f"ce-policy-{_uid()}"+ policy = {+ "jobExecutionTimeoutMinutes": 30,+ "terminateJobsOnUpdate": False,+ }+ status, _, _ = batch_svc._create_compute_environment({+ "computeEnvironmentName": name,+ "type": "MANAGED",+ "serviceRole": "arn:aws:iam::000000000000:role/batch",+ "updatePolicy": policy,+ })+ assert status == 200+ assert "updatePolicy" not in batch_svc._compute_envs[name]++ status, _, _ = batch_svc._update_compute_environment({+ "computeEnvironment": name,+ "updatePolicy": policy,+ })+ assert status == 200+ assert batch_svc._compute_envs[name]["updatePolicy"] == policy+++def test_batch_update_compute_environment_by_arn(batch):+ name = f"ce-arn-{_uid()}"+ created = batch.create_compute_environment(+ computeEnvironmentName=name,+ type="MANAGED",+ serviceRole="arn:aws:iam::000000000000:role/batch",+ )+ arn = created["computeEnvironmentArn"]++ updated = batch.update_compute_environment(+ computeEnvironment=arn,+ state="DISABLED",+ )+ assert updated["computeEnvironmentName"] == name+ assert updated["computeEnvironmentArn"] == arn++ described = batch.describe_compute_environments(computeEnvironments=[name])[+ "computeEnvironments"+ ][0]+ assert described["state"] == "DISABLED"+++def test_batch_update_compute_environment_missing(batch):+ with pytest.raises(ClientError) as exc:+ batch.update_compute_environment(+ computeEnvironment=f"missing-ce-{_uid()}",+ state="DISABLED",+ )+ assert exc.value.response["Error"]["Code"] == "ClientException"+++def test_batch_update_compute_environment_response_shape(batch):+ name = f"ce-shape-{_uid()}"+ batch.create_compute_environment(+ computeEnvironmentName=name,+ type="MANAGED",+ serviceRole="arn:aws:iam::000000000000:role/batch",+ )+ updated = batch.update_compute_environment(+ computeEnvironment=name,+ state="ENABLED",+ )+ assert set(updated.keys()) == {"computeEnvironmentName", "computeEnvironmentArn", "ResponseMetadata"}+ assert updated["computeEnvironmentName"] == name+ assert updated["computeEnvironmentArn"].endswith(f"compute-environment/{name}")+++def test_batch_update_compute_environment_merges_compute_resources(batch):+ """Partial computeResources updates merge into existing resources (AWS ComputeResourceUpdate)."""+ name = f"ce-merge-{_uid()}"+ batch.create_compute_environment(+ computeEnvironmentName=name,+ type="MANAGED",+ serviceRole="arn:aws:iam::000000000000:role/batch",+ computeResources={+ "type": "EC2",+ "minvCpus": 0,+ "maxvCpus": 8,+ "desiredvCpus": 2,+ "instanceTypes": ["m5.large"],+ "subnets": ["subnet-aaa"],+ "securityGroupIds": ["sg-aaa"],+ },+ )++ batch.update_compute_environment(+ computeEnvironment=name,+ computeResources={+ "maxvCpus": 16,+ "desiredvCpus": 4,+ },+ )++ ce = batch.describe_compute_environments(computeEnvironments=[name])[+ "computeEnvironments"+ ][0]+ assert ce["computeResources"]["type"] == "EC2"+ assert ce["computeResources"]["minvCpus"] == 0+ assert ce["computeResources"]["maxvCpus"] == 16+ assert ce["computeResources"]["desiredvCpus"] == 4+ assert ce["computeResources"]["instanceTypes"] == ["m5.large"]+ assert ce["computeResources"]["subnets"] == ["subnet-aaa"]+ assert ce["computeResources"]["securityGroupIds"] == ["sg-aaa"]