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
feat(cloudformation): provision AWS::IoT::ThingGroup (#1638)
iot-rocket1adc05863673
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 44a3c1ec..75eb5a6d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **CloudFormation — `UpdateStack` without changes is refused** — an identical `TemplateBody`, or `UsePreviousTemplate` with unchanged parameters, ran an empty update (`UPDATE_IN_PROGRESS` / `UPDATE_COMPLETE` events) where CloudFormation answers `ValidationError: No updates are to be performed.`, so a "deploy until nothing changes" loop never ended. The request is refused when the template, every resolved parameter and the tags (when sent) equal what the stack runs; a changed parameter value or tag set is still an update. Contributed by @iot-rocket.- **CloudFormation — unrecognized resource types are rejected up front, `Fn::GetAtt` to a missing attribute fails the stack** — a template with a resource type the emulator does not know provisioned every resource ahead of it, failed on that one and rolled the stack back; `CreateStack`, `UpdateStack`, `CreateChangeSet` and `ValidateTemplate` now refuse it synchronously with CloudFormation's own `Template format error: Unrecognized resource types: [...]` and leave no stack (or `REVIEW_IN_PROGRESS` placeholder) behind. Dynamic references (`{{resolve:ssm:...}}`, `{{resolve:secretsmanager:...}}`), which the emulator does not resolve, are refused the same way instead of reaching the service as literal strings. `Fn::GetAtt` to an attribute a resource does not expose answered with the physical id, a silently wrong value; it now fails the operation with `Requested attribute X does not exist in schema for T` and the stack rolls back, matching what a real account does. Outputs are resolved before the success path commits, so a failing output rolls back too and registers no export. Contributed by @iot-rocket.### Added+- **CloudFormation — `AWS::IoT::ThingGroup` provisions** — a stack with a thing group rolled back with `Unsupported resource type` while the thing-group API worked, so a fleet modelled for jobs could not deploy. The type now provisions through `CreateThingGroup` (name generated when `ThingGroupName` is omitted, `ThingGroupProperties` and `ParentGroupName` applied, the parent reported under `thingGroupMetadata` by `DescribeThingGroup`), `Ref` returns the thing group id and `Fn::GetAtt` serves `Arn` and `Id`, as the resource reference documents. `ThingGroupProperties` updates in place through `UpdateThingGroup` (a dropped description or attribute set is cleared); `ThingGroupName` and `ParentGroupName` require replacement — the new group is created before the old one is removed, and a parent change under an unchanged custom name gets CloudFormation's own refusal. `QueryString` (dynamic groups) and `Tags` are accepted without effect: the service has neither. Contributed by @iot-rocket.- **CloudFront — the policy, OAC and function types provision from CloudFormation** — `AWS::CloudFront::CachePolicy`, `OriginRequestPolicy`, `ResponseHeadersPolicy`, `OriginAccessControl` and `Function` had complete APIs and no CloudFormation provisioner, so a CDK app declaring any of them rolled the stack back with `Unsupported resource type` while the same objects were creatable over the API. Each type now provisions by converting its CFN properties to the element the service's own config parser accepts, so validation, defaults and the stored record are identical to the API path, and `Ref`/`Fn::GetAtt` return the documented values (policy `Id`, OAC `Id`, function `FunctionARN`). Deletes are wired; an update replaces rather than mutating in place. Contributed by @mm-salesqueze.- **S3 — Multi-Region Access Points deploy and serve** — `AWS::S3::MultiRegionAccessPoint` rolled the stack back with `Unsupported resource type` and the MRAP hostname resolved nowhere, so a CDK app fronting regional buckets with one could not deploy. The type now provisions (minting the `.mrap`-suffixed alias, the shape S3 uses, and remembering its member buckets) and `<alias>.accesspoint.s3-global.amazonaws.com` resolves onto the existing virtual-hosted S3 path, so path-style rewriting, IAM enforcement and the handler apply unchanged. The member whose bucket region matches the request region is served, else the first. State is account-scoped, cleared by `/_ministack/reset` and persisted. SigV4A, which S3 requires for an MRAP, is not verified — consistent with the documented no-SigV4 stance: such a request has its presign parameters dropped and is served rather than refused for a signature that could never have matched, and because a SigV4A credential scope carries no region it falls back to the first member. The s3control control plane (`CreateMultiRegionAccessPoint` and the async request token, Get/List/Delete, policies) is not included. Contributed by @mm-salesqueze.- **CloudFormation — the Cognito resources update in place** — a stack update that changed an `AWS::Cognito::UserPool`, `UserPoolClient`, `IdentityPool` or `UserPoolGroup` fell through to the type's create handler, and for the three with a generated id that meant a second resource under a new id: `Ref` flipped to the new one, the old one was orphaned together with its data (the users in a pool, the role mapping of an identity pool) and nothing in the stack events said so. The four now update the existing record through the service's own path (`UpdateUserPool`, `UpdateUserPoolClient`, `UpdateIdentityPool`, `AddCustomAttributes` for a grown `Schema`; a group's `Description`, `Precedence` and `RoleArn` directly, since the service has no `UpdateGroup`), keeping the physical id and everything stored behind it, and a property the new template drops reverts to the default `CreateUserPool` / `CreateUserPoolClient` fills in, as the resource reference says Cognito does. The pool and the app client are also created through those two calls now, so the record carries every property the update can change (`DeletionProtection`, `EmailConfiguration`, `AccountRecoverySetting`, token validity, `PreventUserExistenceErrors`, …) instead of the handful the create handler copied, and a replaced client carries its whole template over. The properties the resource references mark *Replacement* replace: a `UserPoolClient` whose `UserPoolId` or `GenerateSecret` changed, and a renamed or moved group, are created before the old one is removed and `Ref` follows the new id, while a move to another pool under an unchanged `GroupName` gets CloudFormation's own refusal for a custom-named resource. `AliasAttributes`, `UsernameAttributes` and `UsernameConfiguration` are marked *No interruption* on the reference, but the first two are fixed at `CreateUserPool` and the reference itself calls the third immutable once set, so a change fails the update with a message naming the property rather than altering the record. A group declared without `Precedence` gets none, the null the reference documents as the default, instead of 0; `Fn::GetAtt` gains `UserPoolId` on the pool, `ClientId` on the client and `Name` on the identity pool. Contributed by @iot-rocket.diff --git a/README.md b/README.mdindex aec77991..fd13809e 100644--- a/README.md+++ b/README.md@@ -511,6 +511,7 @@ subnet = ec2.create_subnet(| `AWS::Cognito::IdentityPoolPrincipalTag` | `<pool ID>\|<provider name>` | — || `AWS::Cognito::UserPoolDomain` | Domain | — || `AWS::IoT::CACertificate` | Certificate id | Arn, Id |+| `AWS::IoT::ThingGroup` | Thing group id | Arn, Id || `AWS::ECR::Repository` | Repo name | Arn, RepositoryUri || `AWS::IAM::ManagedPolicy` | Policy ARN | — || `AWS::KMS::Key` | Key ID | Arn, KeyId |diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 09f10e95..a9f8bda5 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -421,6 +421,10 @@ _CUSTOM_NAME_REPLACEMENT = {"name": "GroupName","requires_replacement": _requires_replacement_cognito_user_pool_group,},+ "AWS::IoT::ThingGroup": {+ "name": "ThingGroupName",+ "requires_replacement": lambda old, new: old.get("ParentGroupName") != new.get("ParentGroupName"),+ },}@@ -7742,6 +7746,72 @@ def _iot_thing_type_delete(physical_id, props):_iot._thing_types.pop(physical_id, None)+# --- IoT ThingGroup ---+# Ref is the thing group id (the resource reference), so the physical id is+# the id and the handlers find the record by it.++def _iot_thing_group_record(physical_id):+ return next((g for g in _iot._thing_groups.values()+ if g.get("thingGroupId") == physical_id), None)+++def _iot_thing_group_properties(props):+ """The ThingGroupProperties payload, with a dropped property at the+ value the service stores for an omitted one (no description, no+ attributes), so an update that removes a property clears it."""+ declared = _pascal_to_camel(props.get("ThingGroupProperties") or {})+ attributes = (declared.get("attributePayload") or {}).get("attributes") or {}+ return {+ "thingGroupDescription": declared.get("thingGroupDescription"),+ "attributePayload": {"attributes": dict(attributes)},+ }+++def _iot_thing_group_create(logical_id, props, stack_name):+ name = props.get("ThingGroupName") or _physical_name(stack_name, logical_id)+ payload = {"thingGroupProperties": _iot_thing_group_properties(props)}+ if props.get("ParentGroupName"):+ payload["parentGroupName"] = props["ParentGroupName"]+ resp = _iot._create_thing_group(name, payload)+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::ThingGroup create failed: {resp[2]!r}")+ rec = _iot._thing_groups.get(name) or {}+ return rec.get("thingGroupId", name), {+ "Arn": rec.get("thingGroupArn", _iot._thing_group_arn(name)),+ "Id": rec.get("thingGroupId", ""),+ }+++def _iot_thing_group_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """Update a thing group in place through UpdateThingGroup: ThingGroupProperties+ is the one property the reference marks No interruption that the service+ stores. ThingGroupName and ParentGroupName require replacement+ (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thinggroup.html):+ the new group is created before the old one is removed, as CloudFormation+ orders a replacement, and Ref follows the new id. QueryString and Tags are+ accepted without effect — the service has no dynamic groups and no tag+ store for thing groups."""+ rec = _iot_thing_group_record(physical_id)+ replacement = rec is None or any(+ new_props.get(key) != old_props.get(key)+ for key in ("ThingGroupName", "ParentGroupName")+ )+ if replacement:+ return _iot_thing_group_create(logical_id or physical_id, new_props, stack_name)+ name = rec["thingGroupName"]+ resp = _iot._update_thing_group(+ name, {"thingGroupProperties": _iot_thing_group_properties(new_props)})+ if resp[0] >= 400:+ raise ValueError(f"AWS::IoT::ThingGroup update failed: {resp[2]!r}")+ return physical_id, {"Arn": rec["thingGroupArn"], "Id": physical_id}+++def _iot_thing_group_delete(physical_id, props):+ rec = _iot_thing_group_record(physical_id)+ if rec is not None:+ _iot._delete_thing_group(rec["thingGroupName"])++def _iot_policy_document(props):doc = props.get("PolicyDocument")return json.dumps(doc) if isinstance(doc, (dict, list)) else doc@@ -8561,6 +8631,12 @@ _RESOURCE_HANDLERS = {"delete": _iot_topic_rule_delete,},"AWS::IoT::ThingType": {"create": _iot_thing_type_create, "delete": _iot_thing_type_delete},+ "AWS::IoT::ThingGroup": {+ "create": _iot_thing_group_create,+ "update": _iot_thing_group_update,+ "update_with_logical_id": True,+ "delete": _iot_thing_group_delete,+ },"AWS::IoT::Policy": {"create": _iot_policy_create,"update": _iot_policy_update,diff --git a/ministack/services/iot.py b/ministack/services/iot.pyindex 8b5bf06c..19e6ff87 100644--- a/ministack/services/iot.py+++ b/ministack/services/iot.py@@ -987,6 +987,9 @@ def _create_thing_group(name: str, payload: dict) -> tuple:)props = payload.get("thingGroupProperties") or {}attr_payload = props.get("attributePayload") or {}+ parent = payload.get("parentGroupName")+ if parent and parent not in _thing_groups:+ return _error_not_found("ThingGroup", parent)record = {"thingGroupName": name,"thingGroupId": new_uuid(),@@ -999,6 +1002,13 @@ def _create_thing_group(name: str, payload: dict) -> tuple:"things": [],"creationDate": _now_epoch(),}+ if parent:+ # DescribeThingGroup reports the parent under thingGroupMetadata, as+ # the API reference documents it.+ record["thingGroupMetadata"] = {+ "parentGroupName": parent,+ "creationDate": record["creationDate"],+ }_thing_groups[name] = recordreturn json_response({"thingGroupName": name,diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 12109bb5..04562853 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -14366,6 +14366,135 @@ def test_cfn_delete_change_set_missing_is_idempotent(cfn):assert exc.value.response["Error"]["Code"] == "ValidationError"+def test_cfn_iot_thing_group_lifecycle(cfn, iot_client):+ """AWS::IoT::ThingGroup provisions with its properties and parent, Ref is+ the group id and Fn::GetAtt serves Arn and Id; a ThingGroupProperties+ change updates the group in place under the same id, a dropped+ description or attribute set is cleared, and deleting the stack removes+ the group."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-thing-group-{uid}"+ parent_name = f"cfn-tg-parent-{uid}"+ group_name = f"cfn-tg-child-{uid}"++ def template(description, attributes):+ # ParentGroupName takes the parent's NAME; Ref would give its id.+ properties = {"ThingGroupName": group_name, "ParentGroupName": parent_name}+ if description is not None or attributes is not None:+ properties["ThingGroupProperties"] = {}+ if description is not None:+ properties["ThingGroupProperties"]["ThingGroupDescription"] = description+ if attributes is not None:+ properties["ThingGroupProperties"]["AttributePayload"] = {"Attributes": attributes}+ return json.dumps({+ "Resources": {+ "Parent": {"Type": "AWS::IoT::ThingGroup", "Properties": {+ "ThingGroupName": parent_name}},+ "Group": {"Type": "AWS::IoT::ThingGroup", "DependsOn": "Parent",+ "Properties": properties},+ },+ "Outputs": {+ "Id": {"Value": {"Ref": "Group"}},+ "Arn": {"Value": {"Fn::GetAtt": ["Group", "Arn"]}},+ "AttId": {"Value": {"Fn::GetAtt": ["Group", "Id"]}},+ "ParentRef": {"Value": {"Ref": "Parent"}},+ },+ })++ cfn.create_stack(StackName=stack_name, TemplateBody=template("fleet", {"site": "a"}))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ group = iot_client.describe_thing_group(thingGroupName=group_name)+ assert _output(stack, "Id") == group["thingGroupId"] == _output(stack, "AttId")+ assert _output(stack, "Arn") == group["thingGroupArn"]+ assert group["thingGroupProperties"]["thingGroupDescription"] == "fleet"+ assert group["thingGroupProperties"]["attributePayload"]["attributes"] == {"site": "a"}+ assert group["thingGroupMetadata"]["parentGroupName"] == parent_name+ parent = iot_client.describe_thing_group(thingGroupName=parent_name)+ assert _output(stack, "ParentRef") == parent["thingGroupId"]+ # The Ref is the id, not the name, as the resource reference documents.+ assert _output(stack, "Id") != group_name+ group_id = group["thingGroupId"]++ cfn.update_stack(StackName=stack_name, TemplateBody=template("fleet-b", {"site": "b", "tier": "1"}))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ group = iot_client.describe_thing_group(thingGroupName=group_name)+ assert group["thingGroupId"] == group_id == _output(stack, "Id")+ assert group["thingGroupProperties"]["thingGroupDescription"] == "fleet-b"+ assert group["thingGroupProperties"]["attributePayload"]["attributes"] == {"site": "b", "tier": "1"}+ assert group["version"] == 2++ cfn.update_stack(StackName=stack_name, TemplateBody=template(None, None))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ group = iot_client.describe_thing_group(thingGroupName=group_name)+ assert group["thingGroupId"] == group_id+ assert not group["thingGroupProperties"].get("thingGroupDescription")+ assert group["thingGroupProperties"]["attributePayload"]["attributes"] == {}+ finally:+ _delete_cfn_test_stack(cfn, stack_name)+ for name in (group_name, parent_name):+ with pytest.raises(ClientError) as exc:+ iot_client.describe_thing_group(thingGroupName=name)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_cfn_iot_thing_group_rename_replaces_and_parent_change_is_refused(cfn, iot_client):+ """ThingGroupName and ParentGroupName require replacement: a renamed group+ is created before the old one is removed and Ref follows the new id, while+ a parent change under an unchanged custom name gets CloudFormation's own+ refusal; a group without ThingGroupName gets a generated name and can be+ re-parented, since the replacement runs under a fresh identity."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-thing-group-repl-{uid}"+ parents = (f"cfn-tg-p1-{uid}", f"cfn-tg-p2-{uid}")++ def template(name, parent):+ return json.dumps({+ "Resources": {+ "P1": {"Type": "AWS::IoT::ThingGroup", "Properties": {"ThingGroupName": parents[0]}},+ "P2": {"Type": "AWS::IoT::ThingGroup", "Properties": {"ThingGroupName": parents[1]}},+ "Group": {"Type": "AWS::IoT::ThingGroup", "DependsOn": ["P1", "P2"], "Properties": {+ "ThingGroupName": name, "ParentGroupName": parent}},+ "Unnamed": {"Type": "AWS::IoT::ThingGroup", "DependsOn": ["P1", "P2"], "Properties": {+ "ParentGroupName": parent}},+ },+ "Outputs": {"Id": {"Value": {"Ref": "Group"}},+ "UnnamedId": {"Value": {"Ref": "Unnamed"}}},+ })++ cfn.create_stack(StackName=stack_name, TemplateBody=template(f"cfn-tg-a-{uid}", parents[0]))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ first_id = _output(stack, "Id")+ unnamed_id = _output(stack, "UnnamedId")+ unnamed_name = next(+ g["groupName"] for g in iot_client.list_thing_groups()["thingGroups"]+ if g["groupName"].startswith(f"{stack_name}-Unnamed-"))++ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-tg-b-{uid}", parents[0]))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")+ renamed = iot_client.describe_thing_group(thingGroupName=f"cfn-tg-b-{uid}")+ assert _output(stack, "Id") == renamed["thingGroupId"] != first_id+ with pytest.raises(ClientError):+ iot_client.describe_thing_group(thingGroupName=f"cfn-tg-a-{uid}")+ assert _output(stack, "UnnamedId") == unnamed_id++ cfn.update_stack(StackName=stack_name, TemplateBody=template(f"cfn-tg-b-{uid}", parents[1]))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ reasons = _stack_event_reasons(cfn, stack_name)+ assert "custom-named resource requires replacing" in reasons, reasons+ assert iot_client.describe_thing_group(thingGroupName=f"cfn-tg-b-{uid}")[+ "thingGroupMetadata"]["parentGroupName"] == parents[0]+ # The generated-name group was re-parented before the failure and+ # rolled back with the stack: it still reports the first parent.+ unnamed = iot_client.describe_thing_group(thingGroupName=unnamed_name)+ assert unnamed["thingGroupMetadata"]["parentGroupName"] in parentsdef test_cfn_apigateway_authorizer_update_in_place_and_replacement(cfn, apigw_v1):"""An authorizer property change updates the authorizer under the same id(Ref and AuthorizerId keep their value), a property the template drops@@ -14509,6 +14638,40 @@ def test_cfn_apigateway_deployment_update_in_place_and_replacement(cfn, apigw_v1_delete_cfn_test_stack(cfn, stack_name)+def test_cfn_iot_thing_group_missing_parent_fails_and_unmodelled_properties_are_accepted(cfn, iot_client):+ """A parent that does not exist fails the stack with the service's own+ ResourceNotFoundException; QueryString (dynamic groups) and Tags, which+ the service does not model, are accepted without effect."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-thing-group-edge-{uid}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps({+ "Resources": {"Group": {"Type": "AWS::IoT::ThingGroup", "Properties": {+ "ThingGroupName": f"cfn-tg-orphan-{uid}", "ParentGroupName": f"cfn-tg-nowhere-{uid}"}}},+ }))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE", stack.get("StackStatusReason")+ assert "ResourceNotFoundException" in _stack_event_reasons(cfn, stack_name)+ with pytest.raises(ClientError):+ iot_client.describe_thing_group(thingGroupName=f"cfn-tg-orphan-{uid}")+ finally:+ _delete_cfn_test_stack(cfn, stack_name)++ stack_name = f"cfn-thing-group-dyn-{uid}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps({+ "Resources": {"Group": {"Type": "AWS::IoT::ThingGroup", "Properties": {+ "ThingGroupName": f"cfn-tg-dyn-{uid}",+ "QueryString": "attributes.site:a",+ "Tags": [{"Key": "owner", "Value": "fleet"}],+ "ThingGroupProperties": {"ThingGroupDescription": "dynamic on AWS, static here"}}}},+ "Outputs": {"Id": {"Value": {"Ref": "Group"}}},+ }))+ try:+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ group = iot_client.describe_thing_group(thingGroupName=f"cfn-tg-dyn-{uid}")+ assert group["thingGroupId"] == _output(stack, "Id")+ assert group["thingGroupProperties"]["thingGroupDescription"] == "dynamic on AWS, static here"def test_cfn_kms_alias_target_change_in_place_and_rename_replaces(cfn, kms_client):"""A TargetKeyId change re-points the alias under its name (Ref keeps itsvalue), an AliasName change replaces the alias — the new name exists, the