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): AWS::Glue database, table and catalog types (#1875) (#1907)
Fábio André Ramos Rodrigues3704eb4a0c2e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex db02fc13..2866b788 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **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+- **CloudFormation — `AWS::Glue::Database`, `Table`, `Partition`, `Connection`, `Crawler`, `Job` and `Trigger`** — a template declaring a Glue catalog failed with `Unrecognized resource types`. The seven types now create, update and delete through the Glue control plane, so a stack's tables are the ones the Glue API and Athena read. Ref returns the resource name, or for a partition its `CatalogId|DatabaseName|TableName|values-hash` identifier; `Fn::GetAtt` `Name` works on a connection and `IdentifierPartitionInputValues` on a partition. The create-only properties of the published registry schemas replace the resource (a database's `DatabaseName`, a partition's database, table and `Values`, a connection's name, a crawler's, job's or trigger's `Name`, a trigger's `Type` and `WorkflowName`); renaming a table or moving it to another database replaces it too, and a `DatabaseInput` change, its `Name` included, updates the database in place. A named trigger whose `Type` or `WorkflowName` changes is refused, as for other custom-named resources. Tags are accepted as a map or a Tag list. Crawlers and jobs are only recorded: a stack never starts a crawl or a job run. Contributed by @fabio-andre-rodrigues.- **IoT — `DescribeEventConfigurations` and `UpdateEventConfigurations`** — both answered `Unsupported IoT path`; they now store the registry event switches per account and region, every type starting disabled, an update changing only the types it names, and `creationDate` / `lastModifiedDate` set from the first update on, as on AWS. Contributed by @iot-rocket.- **CloudFormation — `AWS::ServiceDiscovery::HttpNamespace`, `PrivateDnsNamespace`, `PublicDnsNamespace`, `Service` and `Instance`** — a template declaring any of them, as the CDK ECS constructs do for Cloud Map, failed validation with `Unrecognized resource types`. They now create, update and delete through the Cloud Map service, so a DNS namespace from a stack gets its Route 53 hosted zone. `Ref` and `Fn::GetAtt` return the values in the CloudFormation reference; Description, the SOA TTL, a service's `DnsConfig`, `HealthCheckConfig` and `ServiceAttributes`, and instance attributes change in place, while the properties the reference marks as replacing (including `HealthCheckCustomConfig`) replace the resource. Two Cloud Map API changes come with this: namespaces store and update `Properties.DnsProperties.SOA.TTL`, and `DeleteNamespace` removes the namespace's hosted zone, as on AWS. Contributed by @fabio-andre-rodrigues.diff --git a/README.md b/README.mdindex f498a0ec..6a1e8333 100644--- a/README.md+++ b/README.md@@ -496,6 +496,13 @@ subnet = ec2.create_subnet(| `AWS::Events::EventBus` | EventBus name | Arn, Name || `AWS::Events::Rule` | Rule name | Arn || `AWS::Kinesis::Stream` | Stream name | Arn, StreamId |+| `AWS::Glue::Database` | Database name | — |+| `AWS::Glue::Table` | Table name | — |+| `AWS::Glue::Partition` | `<catalog id>\|<database>\|<table>\|<values hash>` | IdentifierPartitionInputValues |+| `AWS::Glue::Connection` | Connection name | Name |+| `AWS::Glue::Crawler` | Crawler name | — |+| `AWS::Glue::Job` | Job name | — |+| `AWS::Glue::Trigger` | Trigger name | — || `AWS::Lambda::Permission` | Statement ID | — || `AWS::Lambda::Version` | Version ARN | Version || `AWS::Lambda::Alias` | Alias ARN | — |diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 7cf1a601..fdcb91e9 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -38,6 +38,7 @@ import ministack.services.ecr as _ecrimport ministack.services.ecs as _ecsimport ministack.services.eventbridge as _ebimport ministack.services.firehose as _firehose+import ministack.services.glue as _glueimport ministack.services.iam as _iamimport ministack.services.iot as _iotimport ministack.services.kinesis as _kinesis@@ -718,6 +719,15 @@ _CUSTOM_NAME_REPLACEMENT = {old.get("Scope", "REGIONAL") != new.get("Scope", "REGIONAL")),},+ # Type and WorkflowName are "Update requires: Replacement" in the+ # aws-resource-glue-trigger reference.+ "AWS::Glue::Trigger": {+ "name": "Name",+ "requires_replacement": lambda old, new: (+ old.get("Type") != new.get("Type")+ or old.get("WorkflowName", "") != new.get("WorkflowName", "")+ ),+ },}@@ -807,10 +817,11 @@ def _delete_predecessor(delete_fn, *args, **kwargs):retaining set): the engine then records the DELETE_SKIPPED event and thepredecessor stays, as on AWS. Every update handler that creates thereplacement itself removes the old resource through this, so the policy- cannot be forgotten at one site, with four exceptions. Three have a- deterministic generated name (the DynamoDB table, the Location tracker- and the IoT thing type): the replacement takes the name back, so there is- nothing left to retain. The fourth is the Lambda permission's degenerate ``Id`` branch,+ cannot be forgotten at one site, with five exceptions. Four have a+ deterministic generated name (the DynamoDB table, the Location tracker,+ the IoT thing type and the Glue trigger): the replacement takes the name+ back, so there is nothing left to retain. The fifth is the Lambda+ permission's degenerate ``Id`` branch,which removes and re-puts one statement under a Sid that cannot change:the physical id is kept, nothing is replaced, and the policy does notapply.@@ -10749,6 +10760,383 @@ def _firehose_delivery_stream_delete(physical_id, props):_firehose._delete_delivery_stream({"DeliveryStreamName": physical_id})+# --- Glue Data Catalog, connections, crawlers, jobs and triggers (#1875) ---+# Each type goes through glue.py's own control-plane functions, so a stack's+# databases and tables are the catalog Athena and the Glue API read. Crawlers+# and jobs are records only: a stack never starts a crawl or a job run. Ref+# is the resource name for every type except the partition, whose Ref is its+# compound primary identifier. Create-only properties follow the published+# registry schemas. Deletes ignore EntityNotFound, since deleting a database+# already drops its tables and partitions.+++def _glue_call(fn, data, resource_type, action):+ status, _headers, body = fn(data)+ if status >= 400:+ raise ValueError(f"{resource_type} {action} failed: {body!r}")+ return json.loads(body or b"{}")+++def _glue_sync_tags(arn, old_props, new_props, resource_type):+ """Apply a Tags change through TagResource / UntagResource. The registry+ schemas type Tags as a map, while the template reference pages say Tag+ list; _tag_map reads both."""+ old_tags = _tag_map(old_props.get("Tags"))+ new_tags = _tag_map(new_props.get("Tags"))+ removed = sorted(old_tags.keys() - new_tags.keys())+ if removed:+ _glue_call(_glue._untag_resource, {"ResourceArn": arn, "TagsToRemove": removed},+ resource_type, "untag")+ if new_tags and new_tags != old_tags:+ _glue_call(_glue._tag_resource, {"ResourceArn": arn, "TagsToAdd": new_tags},+ resource_type, "tag")+++def _glue_reset_dropped(old_props, new_props, defaults):+ """The update payload entries for properties the new template dropped.+ glue.py's Update* calls change only the members they are given, so a+ removed property would otherwise keep its old value."""+ return {k: v for k, v in defaults.items() if k in old_props and k not in new_props}+++def _glue_database_name(logical_id, props, stack_name):+ # DatabaseName is the schema's primary identifier, so it wins over+ # DatabaseInput.Name when both are given.+ return (props.get("DatabaseName") or (props.get("DatabaseInput") or {}).get("Name")+ or _physical_name(stack_name, logical_id, lowercase=True, max_len=255))+++def _glue_database_input(name, props):+ return {**(props.get("DatabaseInput") or {}), "Name": name}+++def _glue_database_create(logical_id, props, stack_name):+ name = _glue_database_name(logical_id, props, stack_name)+ _glue_call(_glue._create_database, {"DatabaseInput": _glue_database_input(name, props)},+ "AWS::Glue::Database", "create")+ return name, {}+++def _glue_database_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ # The registry schema's only create-only property is DatabaseName, and its+ # update handler is granted glue:UpdateDatabase but neither CreateDatabase+ # nor DeleteDatabase: a DatabaseInput change, its Name included, updates+ # the database in place under the same Ref.+ declared = new_props.get("DatabaseName")+ if physical_id not in _glue._databases or (declared and declared != physical_id):+ created = _glue_database_create(logical_id or physical_id, new_props, stack_name)+ if physical_id in _glue._databases and created[0] != physical_id:+ _delete_predecessor(_glue_database_delete, physical_id, old_props)+ return created+ name = physical_id+ db_input = _glue_database_input(name, new_props)+ db_input.update(_glue_reset_dropped(+ old_props.get("DatabaseInput") or {}, db_input,+ {"Description": "", "LocationUri": None, "Parameters": {}}))+ _glue_call(_glue._update_database, {"Name": name, "DatabaseInput": db_input},+ "AWS::Glue::Database", "update")+ return name, {}+++def _glue_database_delete(physical_id, props):+ _glue._delete_database({"Name": physical_id})+++def _glue_table_name(logical_id, props, stack_name):+ return ((props.get("TableInput") or {}).get("Name") or props.get("Name")+ or _physical_name(stack_name, logical_id, lowercase=True, max_len=255))+++def _glue_table_request(name, props):+ data = {+ "DatabaseName": props.get("DatabaseName", ""),+ "TableInput": {**(props.get("TableInput") or {}), "Name": name},+ }+ if props.get("OpenTableFormatInput"):+ data["OpenTableFormatInput"] = props["OpenTableFormatInput"]+ return data+++def _glue_table_create(logical_id, props, stack_name):+ name = _glue_table_name(logical_id, props, stack_name)+ _glue_call(_glue._create_table, _glue_table_request(name, props),+ "AWS::Glue::Table", "create")+ return name, {}+++def _glue_table_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ # A table is identified by database and name: changing either replaces it,+ # and moving databases keeps the physical id, so the old table is deleted+ # explicitly.+ name = _glue_table_name(logical_id or physical_id, new_props, stack_name)+ old_key = f"{old_props.get('DatabaseName', '')}/{physical_id}"+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id,+ f"{new_props.get('DatabaseName', '')}/{name}",+ old_key if old_key in _glue._tables else None,+ _glue_table_create, _glue_table_delete, delete_when_id_unchanged=True)+ if replaced:+ return replaced+ data = _glue_table_request(name, new_props)+ data["TableInput"].update(_glue_reset_dropped(+ old_props.get("TableInput") or {}, data["TableInput"],+ {"Description": "", "Owner": "", "StorageDescriptor": {}, "PartitionKeys": [],+ "Parameters": {}, "ViewOriginalText": None, "ViewExpandedText": None}))+ _glue_call(_glue._update_table, data, "AWS::Glue::Table", "update")+ return name, {}+++def _glue_table_delete(physical_id, props):+ _glue._delete_table({"DatabaseName": props.get("DatabaseName", ""), "Name": physical_id})+++def _glue_partition_values(props):+ return (props.get("PartitionInput") or {}).get("Values", [])+++def _glue_partition_exists(props):+ status, _headers, _body = _glue._get_partition({+ "DatabaseName": props.get("DatabaseName", ""),+ "TableName": props.get("TableName", ""),+ "PartitionValues": _glue_partition_values(props),+ })+ return status < 400+++def _glue_partition_values_hash(props):+ # The schema's IdentifierPartitionInputValues is "a hashed string+ # equivalent to the partition values list"; AWS does not document the+ # hash, so this one is the emulator's.+ return hashlib.sha256(json.dumps(_glue_partition_values(props)).encode()).hexdigest()+++def _glue_partition_id(props):+ # The schema's compound primary identifier, joined with "|" as Cloud+ # Control documents for compound identifiers.+ return "|".join((+ str(props.get("CatalogId") or get_account_id()),+ props.get("DatabaseName", ""), props.get("TableName", ""),+ _glue_partition_values_hash(props),+ ))+++def _glue_partition_create(logical_id, props, stack_name):+ _glue_call(_glue._create_partition, {+ "DatabaseName": props.get("DatabaseName", ""),+ "TableName": props.get("TableName", ""),+ "PartitionInput": props.get("PartitionInput") or {},+ }, "AWS::Glue::Partition", "create")+ return _glue_partition_id(props), {+ "IdentifierPartitionInputValues": _glue_partition_values_hash(props)}+++def _glue_partition_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ # CatalogId, DatabaseName, TableName and PartitionInput.Values are+ # create-only and all of them are in the id, so a new id is a replacement.+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id,+ _glue_partition_id(new_props),+ physical_id if _glue_partition_exists(old_props) else None,+ _glue_partition_create, _glue_partition_delete)+ if replaced:+ return replaced+ result = _glue_call(_glue._batch_update_partition, {+ "DatabaseName": new_props.get("DatabaseName", ""),+ "TableName": new_props.get("TableName", ""),+ "Entries": [{+ "PartitionValueList": _glue_partition_values(old_props),+ "PartitionInput": new_props.get("PartitionInput") or {},+ }],+ }, "AWS::Glue::Partition", "update")+ if result.get("Errors"):+ raise ValueError(f"AWS::Glue::Partition update failed: {result['Errors']!r}")+ return physical_id, {+ "IdentifierPartitionInputValues": _glue_partition_values_hash(new_props)}+++def _glue_partition_delete(physical_id, props):+ _glue._delete_partition({+ "DatabaseName": props.get("DatabaseName", ""),+ "TableName": props.get("TableName", ""),+ "PartitionValues": _glue_partition_values(props),+ })+++def _glue_connection_name(logical_id, props, stack_name):+ return ((props.get("ConnectionInput") or {}).get("Name")+ or _physical_name(stack_name, logical_id, max_len=255))+++def _glue_connection_create(logical_id, props, stack_name):+ name = _glue_connection_name(logical_id, props, stack_name)+ conn_input = {**(props.get("ConnectionInput") or {}), "Name": name}+ _glue_call(_glue._create_connection, {"ConnectionInput": conn_input},+ "AWS::Glue::Connection", "create")+ _glue_sync_tags(_glue._arn("connection", name), {}, props, "AWS::Glue::Connection")+ return name, {"Name": name}+++def _glue_connection_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ name = _glue_connection_name(logical_id or physical_id, new_props, stack_name)+ current = _glue._connections.get(physical_id)+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id, name,+ physical_id if current is not None else None,+ _glue_connection_create, _glue_connection_delete)+ if replaced:+ return replaced+ # glue.py has no UpdateConnection: the record is rewritten from the new+ # ConnectionInput, keeping its creation time.+ _glue._connections[name] = {+ **(new_props.get("ConnectionInput") or {}), "Name": name,+ "CreationTime": current.get("CreationTime", int(time.time())),+ "LastUpdatedTime": int(time.time()),+ }+ _glue_sync_tags(_glue._arn("connection", name), old_props, new_props,+ "AWS::Glue::Connection")+ return name, {"Name": name}+++def _glue_connection_delete(physical_id, props):+ _glue._delete_connection({"ConnectionName": physical_id})+ _glue._tags.pop(_glue._arn("connection", physical_id), None)+++_GLUE_CRAWLER_DEFAULTS = {+ "DatabaseName": "", "Description": "", "Schedule": {}, "Classifiers": [],+ "TablePrefix": "", "SchemaChangePolicy": {}, "RecrawlPolicy": {},+ "LineageConfiguration": {}, "Configuration": "", "CrawlerSecurityConfiguration": "",+}+++def _glue_crawler_request(name, props):+ data = {k: props[k] for k in ("Role", "Targets", *_GLUE_CRAWLER_DEFAULTS) if k in props}+ # The template's Schedule is a {ScheduleExpression} object; CreateCrawler+ # takes the expression string.+ schedule = props.get("Schedule")+ if isinstance(schedule, dict):+ data["Schedule"] = schedule.get("ScheduleExpression", "")+ data["Name"] = name+ return data+++def _glue_crawler_create(logical_id, props, stack_name):+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=255)+ _glue_call(_glue._create_crawler, _glue_crawler_request(name, props),+ "AWS::Glue::Crawler", "create")+ _glue_sync_tags(_glue._arn("crawler", name), {}, props, "AWS::Glue::Crawler")+ return name, {}+++def _glue_crawler_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ name = new_props.get("Name") or _physical_name(stack_name, logical_id or physical_id, max_len=255)+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id, name,+ physical_id if physical_id in _glue._crawlers else None,+ _glue_crawler_create, _glue_crawler_delete)+ if replaced:+ return replaced+ data = _glue_crawler_request(name, new_props)+ data.update(_glue_reset_dropped(old_props, new_props, _GLUE_CRAWLER_DEFAULTS))+ _glue_call(_glue._update_crawler, data, "AWS::Glue::Crawler", "update")+ _glue_sync_tags(_glue._arn("crawler", name), old_props, new_props, "AWS::Glue::Crawler")+ return name, {}+++def _glue_crawler_delete(physical_id, props):+ _glue._delete_crawler({"Name": physical_id})+ _glue._tags.pop(_glue._arn("crawler", physical_id), None)+++_GLUE_JOB_DEFAULTS = {+ "Description": "", "DefaultArguments": {}, "NonOverridableArguments": {},+ "Connections": {}, "MaxRetries": 0, "Timeout": 2880, "GlueVersion": "3.0",+ "NumberOfWorkers": 2, "WorkerType": "G.1X", "MaxCapacity": None,+ "SecurityConfiguration": "",+}+++def _glue_job_fields(props):+ return {k: props[k] for k in ("Role", "Command", *_GLUE_JOB_DEFAULTS) if k in props}+++def _glue_job_create(logical_id, props, stack_name):+ name = props.get("Name") or _physical_name(stack_name, logical_id, max_len=255)+ data = {**_glue_job_fields(props), "Name": name}+ if props.get("Tags"):+ data["Tags"] = _tag_map(props["Tags"])+ _glue_call(_glue._create_job, data, "AWS::Glue::Job", "create")+ _glue_sync_tags(_glue._arn("job", name), {}, props, "AWS::Glue::Job")+ return name, {}+++def _glue_job_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ name = new_props.get("Name") or _physical_name(stack_name, logical_id or physical_id, max_len=255)+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id, name,+ physical_id if physical_id in _glue._jobs else None,+ _glue_job_create, _glue_job_delete)+ if replaced:+ return replaced+ job_update = _glue_job_fields(new_props)+ job_update.update(_glue_reset_dropped(old_props, new_props, _GLUE_JOB_DEFAULTS))+ _glue_call(_glue._update_job, {"JobName": name, "JobUpdate": job_update},+ "AWS::Glue::Job", "update")+ _glue_sync_tags(_glue._arn("job", name), old_props, new_props, "AWS::Glue::Job")+ return name, {}+++def _glue_job_delete(physical_id, props):+ _glue._delete_job({"JobName": physical_id})+ _glue._tags.pop(_glue._arn("job", physical_id), None)+++_GLUE_TRIGGER_DEFAULTS = {"Schedule": "", "Predicate": {}, "Description": ""}+++def _glue_trigger_name(logical_id, props, stack_name):+ return props.get("Name") or _physical_name(stack_name, logical_id, max_len=255)+++def _glue_trigger_create(logical_id, props, stack_name):+ name = _glue_trigger_name(logical_id, props, stack_name)+ data = {k: props[k] for k in ("Type", "Actions", "WorkflowName", *_GLUE_TRIGGER_DEFAULTS)+ if k in props}+ data["Name"] = name+ data["StartOnCreation"] = _cfn_bool(props.get("StartOnCreation", False))+ if props.get("Tags"):+ data["Tags"] = _tag_map(props["Tags"])+ _glue_call(_glue._create_trigger, data, "AWS::Glue::Trigger", "create")+ return name, {}+++def _glue_trigger_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ name = _glue_trigger_name(logical_id or physical_id, new_props, stack_name)+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id, name,+ physical_id if physical_id in _glue._triggers else None,+ _glue_trigger_create, _glue_trigger_delete)+ if replaced:+ return replaced+ if _requires_replacement("AWS::Glue::Trigger", old_props, new_props):+ # Type and WorkflowName are create-only. An explicit Name is refused+ # above the handler; a generated one is taken back by the replacement,+ # so the old trigger goes first and there is nothing left to retain.+ _glue_trigger_delete(physical_id, old_props)+ return _glue_trigger_create(logical_id or physical_id, new_props, stack_name)+ trigger_update = {k: new_props[k] for k in ("Actions", *_GLUE_TRIGGER_DEFAULTS)+ if k in new_props}+ trigger_update.update(_glue_reset_dropped(old_props, new_props, _GLUE_TRIGGER_DEFAULTS))+ _glue_call(_glue._update_trigger, {"Name": name, "TriggerUpdate": trigger_update},+ "AWS::Glue::Trigger", "update")+ _glue_sync_tags(_glue._arn("trigger", name), old_props, new_props, "AWS::Glue::Trigger")+ return name, {}+++def _glue_trigger_delete(physical_id, props):+ _glue._delete_trigger({"Name": physical_id})++# --- IoT ThingType / Policy, Cognito IdentityPoolRoleAttachment,# Lambda LayerVersionPermission (#1345, item 5) ---# Each maps onto the service's own control-plane create, so the resource is@@ -11556,6 +11944,14 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"LayerName", "Content", "CompatibleRuntimes", "CompatibleArchitectures","Description", "LicenseInfo",),+ # createOnlyProperties of the published registry schemas. Table,+ # Partition and Connection are left out: the first replaces on a+ # TableInput.Name change the schema does not list, and the other two have+ # nested create-only members (PartitionInput/Values, ConnectionInput/Name).+ "AWS::Glue::Database": ("DatabaseName",),+ "AWS::Glue::Crawler": ("Name",),+ "AWS::Glue::Job": ("Name",),+ "AWS::Glue::Trigger": ("Name", "WorkflowName", "Type"),}@@ -11591,6 +11987,48 @@ _RESOURCE_HANDLERS = {"update": _s3_bucket_policy_update,"delete": _s3_bucket_policy_delete,},+ "AWS::Glue::Database": {+ "create": _glue_database_create,+ "update": _glue_database_update,+ "update_with_logical_id": True,+ "delete": _glue_database_delete,+ },+ "AWS::Glue::Table": {+ "create": _glue_table_create,+ "update": _glue_table_update,+ "update_with_logical_id": True,+ "delete": _glue_table_delete,+ },+ "AWS::Glue::Partition": {+ "create": _glue_partition_create,+ "update": _glue_partition_update,+ "update_with_logical_id": True,+ "delete": _glue_partition_delete,+ },+ "AWS::Glue::Connection": {+ "create": _glue_connection_create,+ "update": _glue_connection_update,+ "update_with_logical_id": True,+ "delete": _glue_connection_delete,+ },+ "AWS::Glue::Crawler": {+ "create": _glue_crawler_create,+ "update": _glue_crawler_update,+ "update_with_logical_id": True,+ "delete": _glue_crawler_delete,+ },+ "AWS::Glue::Job": {+ "create": _glue_job_create,+ "update": _glue_job_update,+ "update_with_logical_id": True,+ "delete": _glue_job_delete,+ },+ "AWS::Glue::Trigger": {+ "create": _glue_trigger_create,+ "update": _glue_trigger_update,+ "update_with_logical_id": True,+ "delete": _glue_trigger_delete,+ },"AWS::S3Tables::TableBucket": {"create": _s3tables_bucket_create,"update": _s3tables_bucket_update,diff --git a/tests/test_cfn_glue.py b/tests/test_cfn_glue.pynew file mode 100644index 00000000..3bd0428e--- /dev/null+++ b/tests/test_cfn_glue.py@@ -0,0 +1,370 @@+"""CloudFormation AWS::Glue::* resource types (#1875)."""++import json+import uuid++import pytest+from botocore.exceptions import ClientError++from ministack.services.cloudformation.stacks import _diff_resources++_ROLE = "arn:aws:iam::000000000000:role/glue-cfn-role"+_WAIT = {"Delay": 1, "MaxAttempts": 30}+++def _suffix():+ return uuid.uuid4().hex[:8]+++def _create(cfn, name, template):+ cfn.create_stack(StackName=name, TemplateBody=json.dumps(template))+ cfn.get_waiter("stack_create_complete").wait(StackName=name, WaiterConfig=_WAIT)+++def _update(cfn, name, template):+ cfn.update_stack(StackName=name, TemplateBody=json.dumps(template))+ cfn.get_waiter("stack_update_complete").wait(StackName=name, WaiterConfig=_WAIT)+++def _delete(cfn, name):+ cfn.delete_stack(StackName=name)+ cfn.get_waiter("stack_delete_complete").wait(StackName=name, WaiterConfig=_WAIT)+++def _outputs(cfn, name):+ stack = cfn.describe_stacks(StackName=name)["Stacks"][0]+ return {o["OutputKey"]: o["OutputValue"] for o in stack.get("Outputs", [])}+++def _not_found(call):+ with pytest.raises(ClientError) as exc:+ call()+ assert exc.value.response["Error"]["Code"] == "EntityNotFoundException"+++def _glue_arn(sts, kind, name):+ account = sts.get_caller_identity()["Account"]+ return f"arn:aws:glue:us-east-1:{account}:{kind}/{name}"+++def _data_lake(s, *, table_description="raw events", crawler_schedule=True,+ job_tags=True, trigger_description="nightly", partition_location="p1"):+ crawler = {+ "Name": f"crawler-{s}",+ "Role": _ROLE,+ "DatabaseName": {"Ref": "Db"},+ "Targets": {"S3Targets": [{"Path": f"s3://lake-{s}/events/"}]},+ "Tags": {"team": "data"},+ }+ if crawler_schedule:+ crawler["Schedule"] = {"ScheduleExpression": "cron(0 2 * * ? *)"}+ job = {+ "Name": f"job-{s}",+ "Role": _ROLE,+ "Command": {"Name": "pythonshell", "ScriptLocation": f"s3://lake-{s}/etl.py"},+ "DefaultArguments": {"--stage": "dev"},+ "MaxRetries": 1,+ }+ if job_tags:+ job["Tags"] = [{"Key": "owner", "Value": "etl"}]+ return {+ "Resources": {+ "Db": {+ "Type": "AWS::Glue::Database",+ "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"},+ "DatabaseInput": {"Name": f"lake_{s}", "Description": "data lake"},+ },+ },+ "Events": {+ "Type": "AWS::Glue::Table",+ "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"},+ "DatabaseName": {"Ref": "Db"},+ "TableInput": {+ "Name": "events",+ "Description": table_description,+ "TableType": "EXTERNAL_TABLE",+ "PartitionKeys": [{"Name": "dt", "Type": "string"}],+ "StorageDescriptor": {+ "Columns": [{"Name": "id", "Type": "string"}],+ "Location": f"s3://lake-{s}/events/",+ },+ },+ },+ },+ "Day": {+ "Type": "AWS::Glue::Partition",+ "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"},+ "DatabaseName": {"Ref": "Db"},+ "TableName": {"Ref": "Events"},+ "PartitionInput": {+ "Values": ["2026-10-01"],+ "StorageDescriptor": {"Location": f"s3://lake-{s}/events/{partition_location}/"},+ },+ },+ },+ "Jdbc": {+ "Type": "AWS::Glue::Connection",+ "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"},+ "ConnectionInput": {+ "Name": f"conn-{s}",+ "ConnectionType": "JDBC",+ "ConnectionProperties": {"JDBC_CONNECTION_URL": "jdbc:postgresql://db:5432/app"},+ },+ },+ },+ "Crawler": {"Type": "AWS::Glue::Crawler", "Properties": crawler},+ "Job": {"Type": "AWS::Glue::Job", "Properties": job},+ "Trigger": {+ "Type": "AWS::Glue::Trigger",+ "Properties": {+ "Name": f"trigger-{s}",+ "Type": "SCHEDULED",+ "Schedule": "cron(0 3 * * ? *)",+ "Description": trigger_description,+ "Actions": [{"JobName": {"Ref": "Job"}}],+ },+ },+ },+ "Outputs": {+ key: {"Value": {"Ref": key}}+ for key in ("Db", "Events", "Day", "Jdbc", "Crawler", "Job", "Trigger")+ } | {+ "JdbcName": {"Value": {"Fn::GetAtt": ["Jdbc", "Name"]}},+ "DayValues": {"Value": {"Fn::GetAtt": ["Day", "IdentifierPartitionInputValues"]}},+ },+ }+++def test_cfn_glue_data_lake_stack_create_and_delete(cfn, glue, sts):+ s = _suffix()+ stack = f"glue-lake-{s}"+ _create(cfn, stack, _data_lake(s))+ db, conn, crawler, job, trigger = f"lake_{s}", f"conn-{s}", f"crawler-{s}", f"job-{s}", f"trigger-{s}"++ out = _outputs(cfn, stack)+ assert out["Db"] == db+ assert out["Events"] == "events"+ assert out["Jdbc"] == out["JdbcName"] == conn+ assert out["Crawler"] == crawler+ assert out["Job"] == job+ assert out["Trigger"] == trigger+ # The partition's Ref is its compound primary identifier joined with "|".+ account = sts.get_caller_identity()["Account"]+ assert out["Day"] == f"{account}|{db}|events|{out['DayValues']}"++ assert glue.get_database(Name=db)["Database"]["Description"] == "data lake"+ table = glue.get_table(DatabaseName=db, Name="events")["Table"]+ assert table["Description"] == "raw events"+ assert table["PartitionKeys"] == [{"Name": "dt", "Type": "string"}]+ partition = glue.get_partition(DatabaseName=db, TableName="events",+ PartitionValues=["2026-10-01"])["Partition"]+ assert partition["StorageDescriptor"]["Location"] == f"s3://lake-{s}/events/p1/"+ assert glue.get_connection(Name=conn)["Connection"]["ConnectionType"] == "JDBC"+ got_crawler = glue.get_crawler(Name=crawler)["Crawler"]+ assert got_crawler["DatabaseName"] == db+ assert got_crawler["Schedule"]["ScheduleExpression"] == "cron(0 2 * * ? *)"+ assert glue.get_job(JobName=job)["Job"]["Command"]["Name"] == "pythonshell"+ assert glue.get_trigger(Name=trigger)["Trigger"]["Actions"] == [{"JobName": job}]+ # Tags given as a map (crawler) and as a Tag list (job) both land.+ assert glue.get_tags(ResourceArn=_glue_arn(sts, "crawler", crawler))["Tags"] == {"team": "data"}+ assert glue.get_tags(ResourceArn=_glue_arn(sts, "job", job))["Tags"] == {"owner": "etl"}++ _delete(cfn, stack)+ _not_found(lambda: glue.get_database(Name=db))+ _not_found(lambda: glue.get_table(DatabaseName=db, Name="events"))+ _not_found(lambda: glue.get_connection(Name=conn))+ _not_found(lambda: glue.get_crawler(Name=crawler))+ _not_found(lambda: glue.get_job(JobName=job))+ _not_found(lambda: glue.get_trigger(Name=trigger))+++def test_cfn_glue_update_in_place(cfn, glue, sts):+ s = _suffix()+ stack = f"glue-upd-{s}"+ _create(cfn, stack, _data_lake(s))+ db, crawler, job, trigger = f"lake_{s}", f"crawler-{s}", f"job-{s}", f"trigger-{s}"+ created = glue.get_table(DatabaseName=db, Name="events")["Table"]["CreateTime"]+ try:+ _update(cfn, stack, _data_lake(+ s, table_description="cleaned events", crawler_schedule=False, job_tags=False,+ trigger_description="hourly", partition_location="p2"))++ table = glue.get_table(DatabaseName=db, Name="events")["Table"]+ assert table["Description"] == "cleaned events"+ assert table["CreateTime"] == created+ assert table["VersionId"] == "2"+ partition = glue.get_partition(DatabaseName=db, TableName="events",+ PartitionValues=["2026-10-01"])["Partition"]+ assert partition["StorageDescriptor"]["Location"] == f"s3://lake-{s}/events/p2/"+ # A property the template dropped is cleared, not left at its old value.+ assert not glue.get_crawler(Name=crawler)["Crawler"].get("Schedule")+ assert glue.get_tags(ResourceArn=_glue_arn(sts, "job", job))["Tags"] == {}+ assert glue.get_trigger(Name=trigger)["Trigger"]["Description"] == "hourly"+ finally:+ _delete(cfn, stack)+++def test_cfn_glue_table_rename_replaces(cfn, glue):+ s = _suffix()+ stack = f"glue-ren-{s}"+ template = _data_lake(s)+ _create(cfn, stack, template)+ db = f"lake_{s}"+ try:+ template["Resources"]["Events"]["Properties"]["TableInput"]["Name"] = "events_v2"+ # The partition follows its table through Ref, which replaces it too.+ _update(cfn, stack, template)+ assert _outputs(cfn, stack)["Events"] == "events_v2"+ assert glue.get_table(DatabaseName=db, Name="events_v2")["Table"]["Name"] == "events_v2"+ _not_found(lambda: glue.get_table(DatabaseName=db, Name="events"))+ glue.get_partition(DatabaseName=db, TableName="events_v2", PartitionValues=["2026-10-01"])+ finally:+ _delete(cfn, stack)+++def test_cfn_glue_partition_values_change_replaces(cfn, glue):+ s = _suffix()+ stack = f"glue-pv-{s}"+ template = _data_lake(s)+ _create(cfn, stack, template)+ db = f"lake_{s}"+ before = _outputs(cfn, stack)["Day"]+ try:+ template["Resources"]["Day"]["Properties"]["PartitionInput"]["Values"] = ["2026-10-02"]+ _update(cfn, stack, template)+ assert _outputs(cfn, stack)["Day"] != before+ glue.get_partition(DatabaseName=db, TableName="events", PartitionValues=["2026-10-02"])+ _not_found(lambda: glue.get_partition(+ DatabaseName=db, TableName="events", PartitionValues=["2026-10-01"]))+ finally:+ _delete(cfn, stack)+++def test_cfn_glue_database_input_name_change_updates_in_place(cfn, glue):+ s = _suffix()+ stack = f"glue-dbn-{s}"++ def template(name, description):+ return {+ "Resources": {"Db": {"Type": "AWS::Glue::Database", "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"},+ "DatabaseInput": {"Name": name, "Description": description}}}},+ "Outputs": {"Db": {"Value": {"Ref": "Db"}}},+ }++ _create(cfn, stack, template(f"first_{s}", "one"))+ try:+ # DatabaseName is the type's only create-only property, so the+ # database is updated, not replaced, and keeps its Ref.+ _update(cfn, stack, template(f"second_{s}", "two"))+ assert _outputs(cfn, stack)["Db"] == f"first_{s}"+ assert glue.get_database(Name=f"first_{s}")["Database"]["Description"] == "two"+ _not_found(lambda: glue.get_database(Name=f"second_{s}"))+ finally:+ _delete(cfn, stack)+++def test_cfn_glue_table_moves_database(cfn, glue):+ s = _suffix()+ stack = f"glue-mv-{s}"++ def template(db_ref):+ return {"Resources": {+ "A": {"Type": "AWS::Glue::Database", "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"}, "DatabaseInput": {"Name": f"a_{s}"}}},+ "B": {"Type": "AWS::Glue::Database", "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"}, "DatabaseInput": {"Name": f"b_{s}"}}},+ "T": {"Type": "AWS::Glue::Table", "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"}, "DatabaseName": {"Ref": db_ref},+ "TableInput": {"Name": "t"}}},+ }}++ _create(cfn, stack, template("A"))+ try:+ _update(cfn, stack, template("B"))+ glue.get_table(DatabaseName=f"b_{s}", Name="t")+ _not_found(lambda: glue.get_table(DatabaseName=f"a_{s}", Name="t"))+ finally:+ _delete(cfn, stack)+++def test_cfn_glue_named_trigger_type_change_is_refused(cfn, glue):+ s = _suffix()+ stack = f"glue-trg-{s}"++ def template(trigger_type):+ props = {"Name": f"trigger-{s}", "Type": trigger_type,+ "Actions": [{"JobName": f"job-{s}"}]}+ if trigger_type == "SCHEDULED":+ props["Schedule"] = "cron(0 3 * * ? *)"+ return {"Resources": {"T": {"Type": "AWS::Glue::Trigger", "Properties": props}}}++ _create(cfn, stack, template("ON_DEMAND"))+ try:+ cfn.update_stack(StackName=stack, TemplateBody=json.dumps(template("SCHEDULED")))+ with pytest.raises(Exception):+ cfn.get_waiter("stack_update_complete").wait(StackName=stack, WaiterConfig=_WAIT)+ events = cfn.describe_stack_events(StackName=stack)["StackEvents"]+ reasons = [e.get("ResourceStatusReason", "") for e in events if e["LogicalResourceId"] == "T"]+ assert any("custom-named resource requires replacing" in r for r in reasons)+ assert glue.get_trigger(Name=f"trigger-{s}")["Trigger"]["Type"] == "ON_DEMAND"+ finally:+ _delete(cfn, stack)+++def test_cfn_glue_generated_names(cfn, glue):+ s = _suffix()+ stack = f"Glue-Gen-{s}"+ template = {+ "Resources": {+ "Db": {"Type": "AWS::Glue::Database", "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"}, "DatabaseInput": {}}},+ "Tbl": {"Type": "AWS::Glue::Table", "Properties": {+ "CatalogId": {"Ref": "AWS::AccountId"}, "DatabaseName": {"Ref": "Db"},+ "TableInput": {"TableType": "EXTERNAL_TABLE"}}},+ "Job": {"Type": "AWS::Glue::Job", "Properties": {+ "Role": _ROLE, "Command": {"Name": "pythonshell", "ScriptLocation": "s3://b/k.py"}}},+ },+ "Outputs": {k: {"Value": {"Ref": k}} for k in ("Db", "Tbl", "Job")},+ }+ _create(cfn, stack, template)+ try:+ out = _outputs(cfn, stack)+ # Glue folds catalog names to lowercase, so generated ones start that way.+ assert out["Db"] == out["Db"].lower() and out["Db"].startswith(f"glue-gen-{s}-db-")+ assert out["Tbl"] == out["Tbl"].lower()+ assert out["Job"].startswith(f"{stack}-Job-")+ glue.get_table(DatabaseName=out["Db"], Name=out["Tbl"])+ glue.get_job(JobName=out["Job"])+ # An update under a generated name keeps the same resource.+ template["Resources"]["Job"]["Properties"]["MaxRetries"] = 2+ _update(cfn, stack, template)+ assert _outputs(cfn, stack)["Job"] == out["Job"]+ assert glue.get_job(JobName=out["Job"])["Job"]["MaxRetries"] == 2+ finally:+ _delete(cfn, stack)+++# Expected values follow the createOnlyProperties of the published registry+# schemas; they were not observed on an AWS change set.[email protected]("rtype,old,new,expected", [+ ("AWS::Glue::Database", {"DatabaseName": "a"}, {"DatabaseName": "b"}, "Always"),+ ("AWS::Glue::Database", {"DatabaseInput": {"Name": "a"}}, {"DatabaseInput": {"Name": "b"}}, "Never"),+ ("AWS::Glue::Job", {"Name": "a"}, {"Name": "b"}, "Always"),+ ("AWS::Glue::Job", {"MaxRetries": 0}, {"MaxRetries": 1}, "Never"),+ ("AWS::Glue::Trigger", {"Type": "ON_DEMAND"}, {"Type": "SCHEDULED"}, "Always"),+ ("AWS::Glue::Crawler", {"Description": "a"}, {"Description": "b"}, "Never"),+ ("AWS::Glue::Partition", {"TableName": "a"}, {"TableName": "b"}, "Conditionally"),+])+def test_cfn_glue_change_set_recreation(rtype, old, new, expected):+ def tmpl(props):+ return {"Resources": {"R": {"Type": rtype, "Properties": props}}}++ change = _diff_resources(tmpl(old), tmpl(new))[0]["ResourceChange"]+ targets = {d["Target"]["Name"]: d["Target"]["RequiresRecreation"]+ for d in change.get("Details", []) if d["Target"].get("Name")}+ assert set(targets.values()) == {expected}