Skip to content

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

feat(organizations): add ListParents + tag ops for OU Terraform read-back (#1028)

Rajesh BAVANANTHAM15d9fe19f5f8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 78fbb349..fa65dd72 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
+### Added
+- **Organizations — `ListParents` + tag ops for the OU Terraform round-trip** — adds `ListParents(ChildId)` (returns the single parent AWS reports — `{"Parents": [{"Id", "Type"}]}`, `Type=ROOT` for the org root else `ORGANIZATIONAL_UNIT` — from the `_ParentId` already stored on every OU and account; unknown `ChildId` → `ChildNotFoundException`) **and** `TagResource` / `UntagResource` / `ListTagsForResource` for taggable org resources. The Terraform/OpenTofu `aws_organizations_organizational_unit` Read calls **both** `ListParents` (to populate `parent_id`, which `DescribeOrganizationalUnit` omits) and `ListTagsForResource` on every create + refresh — even for an untagged OU. With either missing, `apply` hard-stops on the read-back (`InvalidAction: Operation '<op>' not implemented`), so a multi-OU hierarchy never finished creating and was never idempotent; with both, it applies cleanly and re-applies as a no-op. No new state. Closes #990.
### Fixed
- **CloudTrail — `CreateTrail` persists `KmsKeyId`** — `CreateTrail` accepted `KmsKeyId` but dropped it (only `UpdateTrail` stored it), so `DescribeTrails`/`GetTrail` read it back empty and Terraform's `aws_cloudtrail` did not converge in a single apply: the first `plan` after `apply` showed a `kms_key_id` diff that only cleared on a second apply (via `UpdateTrail`). `CreateTrail` now stores and returns `KmsKeyId`, normalized to a full key ARN as real AWS echoes it (a bare key id is expanded; an ARN or `alias/...` is kept), and omits the field when no CMK is set so an unset trail shows no diff. `UpdateTrail` normalizes it the same way and likewise omits it from its response when unset. Contributed by @b-rajesh.
@@ -34,8 +36,6 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **EKS — `DescribeCluster` returns a host-reachable endpoint on every path** — `DescribeCluster` now advertises the host-published port, `https://{MINISTACK_HOST}:{port}` (`MINISTACK_HOST` defaults to `localhost`), uniformly on cluster create, OIDC-config restart, and persistence restore. Previously the failure-fallback and restore paths could leave a stale value, so `aws eks update-kubeconfig` + kubectl from the host got an unreachable endpoint. The k3s container publishes 6443 to that host port (`ports={"6443/tcp": port}`), so the endpoint works from the host and from containers that can route to `MINISTACK_HOST`, keeping the `ACTIVE`-cluster shape consistent for `aws eks update-kubeconfig` and Terraform. Contributed by @b-rajesh.
- **SQS — `SendMessage` rejects message bodies with XML 1.0 forbidden characters** — AWS SQS only accepts characters valid in XML 1.0 and returns `InvalidMessageContents` for anything else; MiniStack silently accepted them, so a payload that fails against real AWS passed locally. `SendMessage` (and every `SendMessageBatch` entry) now rejects bodies containing C0 control characters other than tab/LF/CR, the surrogate block `#xD800`–`#xDFFF`, and `#xFFFE`/`#xFFFF` with `InvalidMessageContents`. Contributed by @yamachu.
----
-
## [1.3.68] — 2026-06-25
### Fixed
diff --git a/README.md b/README.md
index d250f9e8..c5c2ce4d 100644
--- a/README.md
+++ b/README.md
@@ -524,7 +524,7 @@ MiniStack expands AWS SAM transforms (`Transform: AWS::Serverless-2016-10-31`) i
| **EventBridge Scheduler** | CreateSchedule, GetSchedule, UpdateSchedule, DeleteSchedule, ListSchedules, CreateScheduleGroup, GetScheduleGroup, DeleteScheduleGroup, ListScheduleGroups, TagResource, UntagResource, ListTagsForResource | 12 actions; schedule groups with cascading deletes; `rate()`, `cron()`, `at()` expressions; group/prefix/state filters on list; default group auto-created; CFN `AWS::Scheduler::Schedule` and `AWS::Scheduler::ScheduleGroup` supported |
| **EKS** | CreateCluster, DescribeCluster, ListClusters, DeleteCluster, CreateNodegroup, DescribeNodegroup, ListNodegroups, DeleteNodegroup, CreateAddon, DescribeAddon, ListAddons, UpdateAddon, DeleteAddon, AssociateEncryptionConfig, CreateAccessEntry, DescribeAccessEntry, ListAccessEntries, UpdateAccessEntry, DeleteAccessEntry, AssociateAccessPolicy, DisassociateAccessPolicy, ListAssociatedAccessPolicies, AssociateIdentityProviderConfig, DescribeIdentityProviderConfig, DisassociateIdentityProviderConfig, TagResource, UntagResource, ListTagsForResource | `CreateCluster` spawns a real **k3s** container (75 MB) with a full Kubernetes API server; `kubectl`, Helm, and any K8s tooling work out of the box; cascading delete removes nodegroups and k3s container; addon CRUD (e.g. `vpc-cni`, `coredns`, `kube-proxy`, `aws-ebs-csi-driver`) at `/clusters/{name}/addons` flips status to `ACTIVE` on create / update; `AssociateEncryptionConfig` at `/clusters/{name}/encryption-config/associate` records KMS encryption config (rejects re-association, AWS-shape `update` envelope); **Access Entries** (modern post-1.29 IAM bindings — replaces aws-auth ConfigMap) at `/clusters/{name}/access-entries[/{principalArn}[/access-policies[/{policyArn}]]]` for Crossplane / Terraform `aws_eks_access_entry` + `aws_eks_access_policy_association`; OIDC discovery + JWKS served at the cluster's `identity.oidc.issuer` URL so Terraform's `aws_iam_openid_connect_provider` (IRSA) works against ministack; **OIDC Identity Provider Config** (`AssociateIdentityProviderConfig` / `DescribeIdentityProviderConfig` / `DisassociateIdentityProviderConfig`) at `/clusters/{name}/identity-provider-configs/{verb}` — one OIDC IdP per cluster, issuer + clientId + claims forwarded to the k3s API server via `--kube-apiserver-arg=oidc-*` flags, tags reachable via `ListTagsForResource`; CFN `AWS::EKS::Cluster` and `AWS::EKS::Nodegroup` supported |
| **OpenSearch Service** | CreateDomain, DescribeDomain, DescribeDomains, DeleteDomain, ListDomainNames, UpdateDomainConfig, DescribeDomainConfig, DescribeDomainChangeProgress, ListVersions, GetCompatibleVersions, AddTags, ListTags, RemoveTags | Management plane on `/2021-01-01/*` (`boto3.client("opensearch")`, SigV4 scope `es`). Default data plane is a stub endpoint (`<domain>.ministack.local:9200`) — set `OPENSEARCH_DATAPLANE=1` to spawn one real `opensearchproject/opensearch` container per `CreateDomain` (same pattern as ElastiCache/RDS); `DescribeDomain.Endpoint` then points at that container and `_cluster/health`/`/_search` work end-to-end. Add `OPENSEARCH_DASHBOARDS=1` (with dataplane on) to also spawn a per-domain `opensearch-dashboards` sidecar; `DescribeDomain.DashboardEndpoint` is populated. ARNs follow `arn:aws:es:<region>:<account>:domain/<name>`; Terraform `aws_opensearch_domain` resource compatible. |
-| **Organizations** | DescribeOrganization, ListRoots, ListAccounts, ListAccountsForParent, DescribeAccount, CreateOrganizationalUnit, DescribeOrganizationalUnit, DeleteOrganizationalUnit, ListOrganizationalUnitsForParent | Single-master-account org auto-initialised on first call; nested OUs with `Path` field (additive 2026-03 AWS change); `FeatureSet=ALL` |
+| **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 |
diff --git a/ministack/services/organizations.py b/ministack/services/organizations.py
index 8a802fc3..a7431b38 100644
--- a/ministack/services/organizations.py
+++ b/ministack/services/organizations.py
@@ -33,6 +33,7 @@ _orgs = AccountScopedDict() # singleton "self" -> Organization dict
_accounts = AccountScopedDict() # account_id -> Account dict
_ous = AccountScopedDict() # ou_id -> OU dict (with ParentId)
_roots = AccountScopedDict() # root_id -> Root dict (single root)
+_tags = AccountScopedDict() # resource_id (ou-/account/r-/policy) -> {tag_key: tag_value}
def reset():
@@ -40,6 +41,7 @@ def reset():
_accounts.clear()
_ous.clear()
_roots.clear()
+ _tags.clear()
def get_state():
@@ -48,6 +50,7 @@ def get_state():
"accounts": copy.deepcopy(_accounts),
"ous": copy.deepcopy(_ous),
"roots": copy.deepcopy(_roots),
+ "tags": copy.deepcopy(_tags),
}
@@ -56,7 +59,7 @@ def restore_state(data):
return
for store, key in (
(_orgs, "orgs"), (_accounts, "accounts"),
- (_ous, "ous"), (_roots, "roots")
+ (_ous, "ous"), (_roots, "roots"), (_tags, "tags")
):
store.clear()
for k, v in (data.get(key) or {}).items():
@@ -158,6 +161,26 @@ def _list_accounts_for_parent(payload):
return _json(200, {"Accounts": out, "NextToken": None})
+def _list_parents(payload):
+ _ensure_org()
+ child_id = payload.get("ChildId")
+ if not child_id:
+ return error_response_json("InvalidInputException", "ChildId is required", 400)
+ # A child is either an OU (ou-*) or an account; both store ``_ParentId``.
+ # AWS returns exactly one parent and does not surface it on Describe*, so the
+ # provider must ListParents the child to learn it (fires on create + refresh).
+ rec = _ous.get(child_id) or _accounts.get(child_id)
+ if rec is None:
+ return error_response_json(
+ "ChildNotFoundException",
+ f"We can't find an organizational unit (OU) or account with the ChildId {child_id}",
+ 400,
+ )
+ parent_id = rec.get("_ParentId")
+ parent_type = "ROOT" if str(parent_id).startswith("r-") else "ORGANIZATIONAL_UNIT"
+ return _json(200, {"Parents": [{"Id": parent_id, "Type": parent_type}], "NextToken": None})
+
+
def _create_organizational_unit(payload):
_ensure_org()
parent_id = payload.get("ParentId")
@@ -178,6 +201,9 @@ def _create_organizational_unit(payload):
"_ParentId": parent_id,
}
_ous[ou_id] = rec
+ inline_tags = payload.get("Tags") or []
+ if inline_tags:
+ _tags[ou_id] = {t["Key"]: t.get("Value", "") for t in inline_tags if "Key" in t}
return _json(200, {"OrganizationalUnit": _public_ou(rec)})
@@ -198,9 +224,75 @@ def _delete_organizational_unit(payload):
return error_response_json("OrganizationalUnitNotFoundException",
f"OU {ou_id} not found", 400)
del _ous[ou_id]
+ _tags.pop(ou_id, None)
+ return _json(200, {})
+
+
+def _tag_list(resource_id):
+ return [{"Key": k, "Value": v} for k, v in (_tags.get(resource_id) or {}).items()]
+
+
+def _resource_exists(rid):
+ # Taggable org resources tracked today: OUs, accounts, and the root.
+ return (
+ _ous.get(rid) is not None
+ or _accounts.get(rid) is not None
+ or _roots.get(rid) is not None
+ )
+
+
+def _require_resource(rid):
+ """Shared validation for the tag ops. Returns an error 3-tuple, or None when the
+ ResourceId is present and known. AWS errors on an unknown target, so we match it
+ rather than return an empty/spurious result."""
+ if not rid:
+ return error_response_json("InvalidInputException", "ResourceId is required", 400)
+ if not _resource_exists(rid):
+ return error_response_json(
+ "TargetNotFoundException",
+ f"We can't find a resource with the ResourceId {rid}", 400,
+ )
+ return None
+
+
+def _tag_resource(payload):
+ _ensure_org()
+ rid = payload.get("ResourceId")
+ err = _require_resource(rid)
+ if err:
+ return err
+ current = dict(_tags.get(rid) or {})
+ for t in payload.get("Tags") or []:
+ if "Key" in t:
+ current[t["Key"]] = t.get("Value", "")
+ _tags[rid] = current
+ return _json(200, {})
+
+
+def _untag_resource(payload):
+ _ensure_org()
+ rid = payload.get("ResourceId")
+ err = _require_resource(rid)
+ if err:
+ return err
+ current = dict(_tags.get(rid) or {})
+ for k in payload.get("TagKeys") or []:
+ current.pop(k, None)
+ _tags[rid] = current
return _json(200, {})
+def _list_tags_for_resource(payload):
+ _ensure_org()
+ rid = payload.get("ResourceId")
+ err = _require_resource(rid)
+ if err:
+ return err
+ # A consumer's Read of any taggable org resource calls ListTagsForResource on
+ # create + refresh; without it the read-back fails and apply can't converge.
+ return _json(200, {"Tags": _tag_list(rid), "NextToken": None})
+
+
_DISPATCH = {
"DescribeOrganization": _describe_organization,
"ListRoots": _list_roots,
@@ -208,9 +300,13 @@ _DISPATCH = {
"DescribeAccount": _describe_account,
"ListOrganizationalUnitsForParent": _list_organizational_units_for_parent,
"ListAccountsForParent": _list_accounts_for_parent,
+ "ListParents": _list_parents,
"CreateOrganizationalUnit": _create_organizational_unit,
"DescribeOrganizationalUnit": _describe_organizational_unit,
"DeleteOrganizationalUnit": _delete_organizational_unit,
+ "TagResource": _tag_resource,
+ "UntagResource": _untag_resource,
+ "ListTagsForResource": _list_tags_for_resource,
}
diff --git a/tests/test_organizations.py b/tests/test_organizations.py
index 1059b15e..b4433851 100644
--- a/tests/test_organizations.py
+++ b/tests/test_organizations.py
@@ -81,3 +81,125 @@ def test_organizations_list_ous_for_parent():
assert any(x["Id"] == ou["Id"] for x in listed)
finally:
o.delete_organizational_unit(OrganizationalUnitId=ou["Id"])
+
+
+def test_organizations_list_parents_ou_under_root():
+ """Terraform Read path: ListParents on a top-level OU returns the ROOT parent."""
+ o = _client_for("555555555555")
+ root_id = o.list_roots()["Roots"][0]["Id"]
+ ou = o.create_organizational_unit(ParentId=root_id, Name="Platform")["OrganizationalUnit"]
+ try:
+ parents = o.list_parents(ChildId=ou["Id"])["Parents"]
+ assert len(parents) == 1
+ assert parents[0]["Id"] == root_id
+ assert parents[0]["Type"] == "ROOT"
+ finally:
+ o.delete_organizational_unit(OrganizationalUnitId=ou["Id"])
+
+
+def test_organizations_list_parents_nested_ou():
+ """A nested OU reports its parent OU with Type ORGANIZATIONAL_UNIT."""
+ o = _client_for("666666666666")
+ root_id = o.list_roots()["Roots"][0]["Id"]
+ parent = o.create_organizational_unit(ParentId=root_id, Name="Workloads")["OrganizationalUnit"]
+ child = o.create_organizational_unit(ParentId=parent["Id"], Name="Prod")["OrganizationalUnit"]
+ try:
+ parents = o.list_parents(ChildId=child["Id"])["Parents"]
+ assert len(parents) == 1
+ assert parents[0]["Id"] == parent["Id"]
+ assert parents[0]["Type"] == "ORGANIZATIONAL_UNIT"
+ finally:
+ o.delete_organizational_unit(OrganizationalUnitId=child["Id"])
+ o.delete_organizational_unit(OrganizationalUnitId=parent["Id"])
+
+
+def test_organizations_list_parents_account():
+ """ListParents resolves an account's parent (master account sits under root)."""
+ o = _client_for("777777777777")
+ root_id = o.list_roots()["Roots"][0]["Id"]
+ parents = o.list_parents(ChildId="777777777777")["Parents"]
+ assert len(parents) == 1
+ assert parents[0]["Id"] == root_id
+ assert parents[0]["Type"] == "ROOT"
+
+
+def test_organizations_list_parents_unknown_child():
+ o = _client_for("888888888888")
+ with pytest.raises(ClientError) as exc:
+ o.list_parents(ChildId="ou-xxxx-doesnotexist")
+ assert exc.value.response["Error"]["Code"] == "ChildNotFoundException"
+
+
+def test_organizations_tag_untag_list_resource():
+ """TagResource / UntagResource / ListTagsForResource round-trip on an OU — the tag
+ read-back the Terraform aws_organizations_organizational_unit Read requires."""
+ o = _client_for("999999999999")
+ root_id = o.list_roots()["Roots"][0]["Id"]
+ ou = o.create_organizational_unit(ParentId=root_id, Name="Tagged")["OrganizationalUnit"]
+ try:
+ o.tag_resource(
+ ResourceId=ou["Id"],
+ Tags=[{"Key": "team", "Value": "platform"}, {"Key": "env", "Value": "prod"}],
+ )
+ tags = {t["Key"]: t["Value"] for t in o.list_tags_for_resource(ResourceId=ou["Id"])["Tags"]}
+ assert tags == {"team": "platform", "env": "prod"}
+ o.untag_resource(ResourceId=ou["Id"], TagKeys=["env"])
+ tags = {t["Key"]: t["Value"] for t in o.list_tags_for_resource(ResourceId=ou["Id"])["Tags"]}
+ assert tags == {"team": "platform"}
+ finally:
+ o.delete_organizational_unit(OrganizationalUnitId=ou["Id"])
+
+
+def test_organizations_create_ou_with_inline_tags():
+ """CreateOrganizationalUnit captures inline Tags so the Terraform Read sees them."""
+ o = _client_for("112233445566")
+ root_id = o.list_roots()["Roots"][0]["Id"]
+ ou = o.create_organizational_unit(
+ ParentId=root_id, Name="InlineTagged",
+ Tags=[{"Key": "owner", "Value": "secops"}],
+ )["OrganizationalUnit"]
+ try:
+ tags = {t["Key"]: t["Value"] for t in o.list_tags_for_resource(ResourceId=ou["Id"])["Tags"]}
+ assert tags == {"owner": "secops"}
+ finally:
+ o.delete_organizational_unit(OrganizationalUnitId=ou["Id"])
+
+
+def test_organizations_list_tags_untagged_ou_empty():
+ """An untagged OU returns an empty tag set (not an error) — the provider Read calls
+ ListTagsForResource on every OU whether or not tags are set, so it must not fail."""
+ o = _client_for("223344556677")
+ root_id = o.list_roots()["Roots"][0]["Id"]
+ ou = o.create_organizational_unit(ParentId=root_id, Name="Untagged")["OrganizationalUnit"]
+ try:
+ assert o.list_tags_for_resource(ResourceId=ou["Id"])["Tags"] == []
+ finally:
+ o.delete_organizational_unit(OrganizationalUnitId=ou["Id"])
+
+
+def test_organizations_list_tags_unknown_resource():
+ """ListTagsForResource on a resource that doesn't exist → TargetNotFoundException,
+ matching real AWS (not an empty set)."""
+ o = _client_for("334455667788")
+ o.list_roots() # ensure org
+ with pytest.raises(ClientError) as exc:
+ o.list_tags_for_resource(ResourceId="ou-9999-doesnotexist")
+ assert exc.value.response["Error"]["Code"] == "TargetNotFoundException"
+
+
+def test_organizations_tags_are_account_scoped():
+ """Tags are account-scoped: one tenant's OU + tags are invisible to another
+ (a different account can't even resolve the OU → TargetNotFoundException)."""
+ a = _client_for("445566778899")
+ b = _client_for("556677889900")
+ root_a = a.list_roots()["Roots"][0]["Id"]
+ ou_a = a.create_organizational_unit(ParentId=root_a, Name="ScopedA")["OrganizationalUnit"]
+ try:
+ a.tag_resource(ResourceId=ou_a["Id"], Tags=[{"Key": "owner", "Value": "a"}])
+ with pytest.raises(ClientError) as exc:
+ b.list_tags_for_resource(ResourceId=ou_a["Id"])
+ assert exc.value.response["Error"]["Code"] == "TargetNotFoundException"
+ tags = {t["Key"]: t["Value"] for t in a.list_tags_for_resource(ResourceId=ou_a["Id"])["Tags"]}
+ assert tags == {"owner": "a"}
+ finally:
+ a.delete_organizational_unit(OrganizationalUnitId=ou_a["Id"])