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::ElastiCache subnet groups, parameter groups, clusters and replication groups (#1874) (#1915)
Fábio André Ramos Rodriguesba6a56ba8289
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84c2ad88..d788db94 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,6 +26,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::ElastiCache::SubnetGroup`, `ParameterGroup`, `CacheCluster`, `ReplicationGroup`, `User` and `UserGroup`** — a template declaring an ElastiCache cache failed with `Unrecognized resource types`. The six types now create, update and delete through the ElastiCache API, so a stack's cluster or replication group gets the same container-backed endpoint `CreateCacheCluster` and `CreateReplicationGroup` return, and its `PrimaryEndPoint` / `RedisEndpoint` can be passed to a Lambda function or ECS task. The create-only properties of the published registry schemas replace the resource (refused for a custom-named one, as on AWS); every other property updates in place through the matching `Modify*` call, a replica count change through `IncreaseReplicaCount` / `DecreaseReplicaCount`, and a parameter the template drops goes back to its default. `ConfigurationEndPoint` is only available on a cluster-mode-enabled replication group and `RedisEndpoint` only on a Valkey or Redis OSS cluster, so a `Fn::GetAtt` on the other fails, as the reference says. Cluster and replication group provisioning runs off the event loop, and a stack waits for a cluster whose image is still being pulled to become `available`. Contributed by @fabio-andre-rodrigues.- **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 6a1e8333..8e82aef5 100644--- a/README.md+++ b/README.md@@ -496,6 +496,12 @@ 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::ElastiCache::SubnetGroup` | Subnet group name | — |+| `AWS::ElastiCache::ParameterGroup` | Generated parameter group name | CacheParameterGroupName |+| `AWS::ElastiCache::CacheCluster` | Cluster name | Id, RedisEndpoint.Address, RedisEndpoint.Port (Valkey / Redis OSS), ConfigurationEndpoint.Address, ConfigurationEndpoint.Port (Memcached) |+| `AWS::ElastiCache::ReplicationGroup` | Replication group id | PrimaryEndPoint.Address, PrimaryEndPoint.Port, ReaderEndPoint.Address, ReaderEndPoint.Port, ReadEndPoint.Addresses, ReadEndPoint.Ports, ReadEndPoint.AddressesList, ReadEndPoint.PortsList (cluster mode disabled); ConfigurationEndPoint.Address, ConfigurationEndPoint.Port (cluster mode enabled) |+| `AWS::ElastiCache::User` | User id | Arn, Status |+| `AWS::ElastiCache::UserGroup` | User group id | Arn, Status || `AWS::Glue::Database` | Database name | — || `AWS::Glue::Table` | Table name | — || `AWS::Glue::Partition` | `<catalog id>\|<database>\|<table>\|<values hash>` | IdentifierPartitionInputValues |diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 534d212b..09c896a5 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -36,6 +36,7 @@ import ministack.services.dynamodb as _dynamodbimport ministack.services.ec2 as _ec2import ministack.services.ecr as _ecrimport ministack.services.ecs as _ecs+import ministack.services.elasticache as _ecimport ministack.services.eventbridge as _ebimport ministack.services.firehose as _firehoseimport ministack.services.glue as _glue@@ -719,6 +720,26 @@ _CUSTOM_NAME_REPLACEMENT = {old.get("Scope", "REGIONAL") != new.get("Scope", "REGIONAL")),},+ # createOnlyProperties of the published registry schemas, the name itself+ # aside. "If you specify a name, you can't perform updates that require+ # replacement" (aws-properties-name).+ "AWS::ElastiCache::CacheCluster": {+ "name": "ClusterName",+ "requires_replacement": lambda old, new: any(+ old.get(p) != new.get(p) for p in (+ "Port", "SnapshotArns", "SnapshotName", "CacheSubnetGroupName",+ "Engine", "NetworkType",+ )+ ),+ },+ "AWS::ElastiCache::ReplicationGroup": {+ "name": "ReplicationGroupId",+ "requires_replacement": lambda old, new: _ec_rg_requires_replacement(old, new),+ },+ "AWS::ElastiCache::User": {+ "name": "UserId",+ "requires_replacement": lambda old, new: old.get("UserName") != new.get("UserName"),+ },# Type and WorkflowName are "Update requires: Replacement" in the# aws-resource-glue-trigger reference."AWS::Glue::Trigger": {@@ -3754,7 +3775,7 @@ def _cfn_wait_condition_create(logical_id, props, stack_name):a FAILURE signal arrived, or the timeout passed. With a ``CreationPolicy``the signals come through SignalResource only; otherwise through thehandle's URL (and SignalResource). Runs on a worker thread (see- ``_is_custom_resource`` in stacks.py)."""+ ``_runs_on_worker_thread`` in stacks.py)."""from ministack.services.cloudformation import wait_conditions as _wcstack_id = _cr_stack_id(stack_name)res_def = _cfn_wait_condition_definition(stack_name, logical_id)@@ -10747,6 +10768,57 @@ def _firehose_delivery_stream_delete(physical_id, props):_firehose._delete_delivery_stream({"DeliveryStreamName": physical_id})+# --- ElastiCache subnet groups, parameter groups, clusters, replication+# groups, users and user groups (#1874) ---+# Each type goes through elasticache.py's own query-protocol functions, so a+# stack's cluster or replication group gets the same container-backed endpoint+# CreateCacheCluster / CreateReplicationGroup return. Create-only properties+# follow the published registry schemas; every other property updates in+# place through the matching Modify call, which, like the API, ignores the+# members MiniStack does not model. Ref is the resource name for every type.++# A cluster created while its image is still being pulled reports `creating`+# and publishes its endpoint when the container starts; CloudFormation waits+# for `available` before the resource completes.+_EC_AVAILABLE_TIMEOUT = float(os.environ.get("MINISTACK_ELASTICACHE_CFN_WAIT", "300"))+++def _ec_query(props, renames=None):+ """Flatten template properties into the query parameters elasticache.py+ reads: lists as ``.member.N``, structures as ``.Member``, booleans as+ ``true`` / ``false``."""+ out = {}++ def put(key, value):+ if isinstance(value, dict):+ for k, v in value.items():+ put(f"{key}.{k}", v)+ elif isinstance(value, list):+ for i, v in enumerate(value, 1):+ put(f"{key}.member.{i}", v)+ elif isinstance(value, bool):+ out[key] = str(value).lower()+ elif value is not None:+ out[key] = str(value)++ for key, value in props.items():+ put((renames or {}).get(key, key), value)+ return out+++def _ec_call(fn, params, resource_type, action):+ _ec._seed_default_param_groups()+ status, _headers, body = fn(params)+ if status >= 400:+ text = body.decode("utf-8", errors="replace") if isinstance(body, bytes) else str(body)+ code = re.search(r"<Code>(.*?)</Code>", text)+ message = re.search(r"<Message>(.*?)</Message>", text, re.S)+ raise ValueError(+ f"{resource_type} {action} failed: "+ f"{code.group(1) if code else status}: {message.group(1) if message else text}")+++def _ec_sync_tags(arn, old_props, new_props, resource_type):# --- 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@@ -10772,6 +10844,394 @@ def _glue_sync_tags(arn, old_props, new_props, resource_type):new_tags = _tag_map(new_props.get("Tags"))removed = sorted(old_tags.keys() - new_tags.keys())if removed:+ _ec_call(_ec._remove_tags, {"ResourceName": arn, **_ec_query({"TagKeys": removed})},+ resource_type, "untag")+ changed = {k: v for k, v in new_tags.items() if old_tags.get(k) != v}+ if changed:+ _ec_call(_ec._add_tags, {"ResourceName": arn, **_ec_query({+ "Tags": [{"Key": k, "Value": v} for k, v in changed.items()]})},+ resource_type, "tag")+++def _ec_changed(old_props, new_props, names):+ return {k: new_props[k] for k in names+ if k in new_props and new_props.get(k) != old_props.get(k)}+++# SubnetGroup ---------------------------------------------------------------++def _ec_subnet_group_create(logical_id, props, stack_name):+ name = props.get("CacheSubnetGroupName") or _physical_name(+ stack_name, logical_id, lowercase=True, max_len=255)+ _ec_call(_ec._create_subnet_group, {+ "CacheSubnetGroupName": name,+ **_ec_query({"CacheSubnetGroupDescription": props.get("Description", ""),+ "SubnetIds": props.get("SubnetIds") or []}),+ }, "AWS::ElastiCache::SubnetGroup", "create")+ _ec_sync_tags(_ec._arn_subnet_group(name), {}, props, "AWS::ElastiCache::SubnetGroup")+ return name, {}+++def _ec_subnet_group_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ name = new_props.get("CacheSubnetGroupName") or _physical_name(+ stack_name, logical_id or physical_id, lowercase=True, max_len=255)+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id, name,+ physical_id if physical_id in _ec._subnet_groups else None,+ _ec_subnet_group_create, _ec_subnet_group_delete)+ if replaced:+ return replaced+ _ec_call(_ec._modify_subnet_group, {+ "CacheSubnetGroupName": name,+ **_ec_query({"CacheSubnetGroupDescription": new_props.get("Description", ""),+ "SubnetIds": new_props.get("SubnetIds") or []}),+ }, "AWS::ElastiCache::SubnetGroup", "update")+ _ec_sync_tags(_ec._arn_subnet_group(name), old_props, new_props,+ "AWS::ElastiCache::SubnetGroup")+ return name, {}+++def _ec_subnet_group_delete(physical_id, props):+ _ec._delete_subnet_group({"CacheSubnetGroupName": physical_id})+++# ParameterGroup ------------------------------------------------------------+# CacheParameterGroupName is read-only in the schema: the name is always+# generated.++def _ec_parameter_values(names_values):+ return _ec_query({"ParameterNameValues": [+ {"ParameterName": k, "ParameterValue": v} for k, v in names_values.items()+ ]}) if names_values else {}+++def _ec_parameter_group_query(params):+ # elasticache.py reads ParameterNameValues.ParameterNameValue.N, the+ # member name of the API's ParameterNameValueList.+ return {k.replace("ParameterNameValues.member.", "ParameterNameValues.ParameterNameValue."): v+ for k, v in params.items()}+++def _ec_parameter_group_create(logical_id, props, stack_name):+ name = _physical_name(stack_name, logical_id, lowercase=True, max_len=255)+ _ec_call(_ec._create_param_group, {+ "CacheParameterGroupName": name,+ **_ec_query({"CacheParameterGroupFamily": props.get("CacheParameterGroupFamily", ""),+ "Description": props.get("Description", "")}),+ }, "AWS::ElastiCache::ParameterGroup", "create")+ values = {str(k): str(v) for k, v in (props.get("Properties") or {}).items()}+ if values:+ _ec_call(_ec._modify_cache_parameter_group, {+ "CacheParameterGroupName": name,+ **_ec_parameter_group_query(_ec_parameter_values(values)),+ }, "AWS::ElastiCache::ParameterGroup", "create")+ _ec_sync_tags(_ec._arn_param_group(name), {}, props, "AWS::ElastiCache::ParameterGroup")+ return name, {"CacheParameterGroupName": name}+++def _ec_parameter_group_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ if (physical_id not in _ec._param_groups+ or old_props.get("CacheParameterGroupFamily") != new_props.get("CacheParameterGroupFamily")):+ # CacheParameterGroupFamily is the type's create-only property. The+ # generated name does not change, so the old group goes first.+ if physical_id in _ec._param_groups:+ _ec_parameter_group_delete(physical_id, old_props)+ return _ec_parameter_group_create(logical_id or physical_id, new_props, stack_name)+ old_values = {str(k): str(v) for k, v in (old_props.get("Properties") or {}).items()}+ new_values = {str(k): str(v) for k, v in (new_props.get("Properties") or {}).items()}+ changed = {k: v for k, v in new_values.items() if old_values.get(k) != v}+ if changed:+ _ec_call(_ec._modify_cache_parameter_group, {+ "CacheParameterGroupName": physical_id,+ **_ec_parameter_group_query(_ec_parameter_values(changed)),+ }, "AWS::ElastiCache::ParameterGroup", "update")+ dropped = sorted(old_values.keys() - new_values.keys())+ if dropped:+ # A parameter the template no longer sets goes back to its default.+ _ec_call(_ec._reset_cache_parameter_group, {+ "CacheParameterGroupName": physical_id,+ **_ec_parameter_group_query(_ec_parameter_values({k: "" for k in dropped})),+ }, "AWS::ElastiCache::ParameterGroup", "update")+ if new_props.get("Description") != old_props.get("Description"):+ # ModifyCacheParameterGroup has no description member.+ _ec._param_groups[physical_id]["Description"] = new_props.get("Description", "")+ _ec_sync_tags(_ec._arn_param_group(physical_id), old_props, new_props,+ "AWS::ElastiCache::ParameterGroup")+ return physical_id, {"CacheParameterGroupName": physical_id}+++def _ec_parameter_group_delete(physical_id, props):+ _ec._delete_param_group({"CacheParameterGroupName": physical_id})+++# CacheCluster --------------------------------------------------------------++_EC_CLUSTER_MODIFIABLE = (+ "AZMode", "AutoMinorVersionUpgrade", "CacheNodeType", "CacheParameterGroupName",+ "CacheSecurityGroupNames", "EngineVersion", "IpDiscovery", "LogDeliveryConfigurations",+ "NotificationTopicArn", "NumCacheNodes", "PreferredAvailabilityZones",+ "PreferredMaintenanceWindow", "SnapshotRetentionLimit", "SnapshotWindow",+ "TransitEncryptionEnabled", "VpcSecurityGroupIds",+)+# CacheClusterId is ClusterName in the template; the API's SecurityGroupIds+# is VpcSecurityGroupIds.+_EC_CLUSTER_RENAMES = {"ClusterName": "CacheClusterId", "VpcSecurityGroupIds": "SecurityGroupIds"}+++def _ec_wait_available(records, record_id, status_key, resource_type):+ deadline = time.time() + _EC_AVAILABLE_TIMEOUT+ while True:+ rec = records.get(record_id)+ status = rec.get(status_key) if rec else None+ if status != "creating":+ break+ if time.time() >= deadline:+ raise ValueError(f"{resource_type} {record_id} did not become available "+ f"within {_EC_AVAILABLE_TIMEOUT:.0f}s")+ time.sleep(0.5)+ if rec is None or status == "create-failed":+ raise ValueError(f"{resource_type} {record_id} failed to start")+ return rec+++def _ec_cluster_attrs(cluster_id):+ rec = _ec._clusters.get(cluster_id) or {}+ ep = rec.get("_endpoint") or {}+ address, port = ep.get("Address", ""), str(ep.get("Port", ""))+ attrs = {"Id": cluster_id}+ # RedisEndpoint for Valkey / Redis OSS; ConfigurationEndpoint is the+ # Memcached cluster's. Either one is absent on the other engine, so a+ # GetAtt on it fails, as the reference says.+ if rec.get("Engine") == "memcached":+ attrs["ConfigurationEndpoint.Address"] = address+ attrs["ConfigurationEndpoint.Port"] = port+ else:+ attrs["RedisEndpoint.Address"] = address+ attrs["RedisEndpoint.Port"] = port+ return attrs+++def _ec_cluster_name(logical_id, props, stack_name):+ return props.get("ClusterName") or _physical_name(+ stack_name, logical_id, lowercase=True, max_len=50)+++def _ec_cluster_create(logical_id, props, stack_name):+ name = _ec_cluster_name(logical_id, props, stack_name)+ params = _ec_query({**props, "ClusterName": name}, _EC_CLUSTER_RENAMES)+ _ec_call(_ec._create_cache_cluster, params, "AWS::ElastiCache::CacheCluster", "create")+ _ec_wait_available(_ec._clusters, name, "CacheClusterStatus", "AWS::ElastiCache::CacheCluster")+ return name, _ec_cluster_attrs(name)+++def _ec_cluster_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ name = _ec_cluster_name(logical_id or physical_id, new_props, stack_name)+ current = physical_id if physical_id in _ec._clusters else None+ if current is not None and name == physical_id and _requires_replacement(+ "AWS::ElastiCache::CacheCluster", old_props, new_props):+ # A create-only change under a generated name: the replacement takes+ # the same name back, so the old cluster goes first.+ _ec_cluster_delete(physical_id, old_props)+ return _ec_cluster_create(logical_id or physical_id, new_props, stack_name)+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id, name, current,+ _ec_cluster_create, _ec_cluster_delete)+ if replaced:+ return replaced+ changed = _ec_changed(old_props, new_props, _EC_CLUSTER_MODIFIABLE)+ if changed:+ _ec_call(_ec._modify_cache_cluster, {+ "CacheClusterId": name, **_ec_query(changed, _EC_CLUSTER_RENAMES)},+ "AWS::ElastiCache::CacheCluster", "update")+ _ec_sync_tags(_ec._arn_cluster(name), old_props, new_props, "AWS::ElastiCache::CacheCluster")+ return name, _ec_cluster_attrs(name)+++def _ec_cluster_delete(physical_id, props):+ _ec._delete_cache_cluster({"CacheClusterId": physical_id})+++# ReplicationGroup ----------------------------------------------------------++_EC_RG_MODIFIABLE = (+ "AutoMinorVersionUpgrade", "AutomaticFailoverEnabled", "CacheNodeType",+ "CacheParameterGroupName", "ClusterMode", "Engine", "EngineVersion", "IpDiscovery",+ "LogDeliveryConfigurations", "MultiAZEnabled", "NotificationTopicArn",+ "PreferredMaintenanceWindow", "PrimaryClusterId", "ReplicationGroupDescription",+ "SecurityGroupIds", "SnapshotRetentionLimit", "SnapshotWindow", "SnapshottingClusterId",+ "TransitEncryptionEnabled", "TransitEncryptionMode", "AuthToken",+)+++def _ec_rg_requires_replacement(old, new):+ # The schema's createOnlyProperties, plus its conditional ones: adding an+ # AuthToken and changing NodeGroupConfiguration replace the group. The+ # reference also replaces on a NumNodeGroups change unless the+ # UseOnlineResharding update policy is set, which a handler cannot see.+ fixed = ("AtRestEncryptionEnabled", "CacheSubnetGroupName", "DataTieringEnabled",+ "GlobalReplicationGroupId", "KmsKeyId", "NetworkType", "Port",+ "PreferredCacheClusterAZs", "SnapshotArns", "SnapshotName",+ "NodeGroupConfiguration")+ return (any(old.get(p) != new.get(p) for p in fixed)+ or (not old.get("AuthToken") and bool(new.get("AuthToken")))+ or int(old.get("NumNodeGroups") or 1) != int(new.get("NumNodeGroups") or 1))+++def _ec_rg_attrs(rg_id):+ rg = _ec._replication_groups.get(rg_id) or {}+ attrs = {}+ groups = rg.get("NodeGroups") or []+ if rg.get("ConfigurationEndpoint"):+ # Only a clustered group has a configuration endpoint; GetAtt on it+ # fails otherwise, as the reference says.+ attrs["ConfigurationEndPoint.Address"] = rg["ConfigurationEndpoint"].get("Address", "")+ attrs["ConfigurationEndPoint.Port"] = str(rg["ConfigurationEndpoint"].get("Port", ""))+ elif groups:+ primary = groups[0].get("PrimaryEndpoint") or {}+ reader = groups[0].get("ReaderEndpoint") or primary+ replicas = [m.get("ReadEndpoint") or {} for m in groups[0].get("NodeGroupMembers", [])+ if m.get("CurrentRole") == "replica"]+ addresses = [r.get("Address", "") for r in replicas]+ ports = [str(r.get("Port", "")) for r in replicas]+ attrs.update({+ "PrimaryEndPoint.Address": primary.get("Address", ""),+ "PrimaryEndPoint.Port": str(primary.get("Port", "")),+ "ReaderEndPoint.Address": reader.get("Address", ""),+ "ReaderEndPoint.Port": str(reader.get("Port", "")),+ "ReadEndPoint.Addresses": ",".join(addresses),+ "ReadEndPoint.Ports": ",".join(ports),+ "ReadEndPoint.AddressesList": addresses,+ "ReadEndPoint.PortsList": ports,+ })+ return attrs+++def _ec_rg_id(logical_id, props, stack_name):+ return props.get("ReplicationGroupId") or _physical_name(+ stack_name, logical_id, lowercase=True, max_len=40)+++def _ec_rg_create(logical_id, props, stack_name):+ rg_id = _ec_rg_id(logical_id, props, stack_name)+ _ec_call(_ec._create_replication_group,+ _ec_query({**props, "ReplicationGroupId": rg_id}),+ "AWS::ElastiCache::ReplicationGroup", "create")+ return rg_id, _ec_rg_attrs(rg_id)+++def _ec_rg_replicas(props):+ if props.get("ReplicasPerNodeGroup") is not None:+ return int(props["ReplicasPerNodeGroup"])+ return max(int(props.get("NumCacheClusters") or 1) - 1, 0)+++def _ec_rg_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ rg_id = _ec_rg_id(logical_id or physical_id, new_props, stack_name)+ current = physical_id if physical_id in _ec._replication_groups else None+ if current is not None and rg_id == physical_id and _ec_rg_requires_replacement(+ old_props, new_props):+ # As for the cache cluster: a generated id is taken back by the+ # replacement, so the old group goes first.+ _ec_rg_delete(physical_id, old_props)+ return _ec_rg_create(logical_id or physical_id, new_props, stack_name)+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id, rg_id, current,+ _ec_rg_create, _ec_rg_delete)+ if replaced:+ return replaced+ changed = _ec_changed(old_props, new_props, _EC_RG_MODIFIABLE)+ old_groups = set(old_props.get("UserGroupIds") or [])+ new_groups = set(new_props.get("UserGroupIds") or [])+ params = _ec_query(changed)+ params.update(_ec_query({"UserGroupIdsToAdd": sorted(new_groups - old_groups),+ "UserGroupIdsToRemove": sorted(old_groups - new_groups)}))+ if params:+ _ec_call(_ec._modify_replication_group, {"ReplicationGroupId": rg_id, **params},+ "AWS::ElastiCache::ReplicationGroup", "update")+ old_replicas, new_replicas = _ec_rg_replicas(old_props), _ec_rg_replicas(new_props)+ if new_replicas != old_replicas:+ fn = _ec._increase_replica_count if new_replicas > old_replicas else _ec._decrease_replica_count+ _ec_call(fn, {"ReplicationGroupId": rg_id, "NewReplicaCount": str(new_replicas),+ "ApplyImmediately": "true"},+ "AWS::ElastiCache::ReplicationGroup", "update")+ _ec_sync_tags(_ec._arn_replication_group(rg_id), old_props, new_props,+ "AWS::ElastiCache::ReplicationGroup")+ return rg_id, _ec_rg_attrs(rg_id)+++def _ec_rg_delete(physical_id, props):+ _ec._delete_replication_group({"ReplicationGroupId": physical_id})+++# User and UserGroup --------------------------------------------------------++def _ec_user_attrs(user_id):+ user = _ec._users.get(user_id) or {}+ return {"Arn": user.get("ARN", _ec._arn_user(user_id)), "Status": user.get("Status", "active")}+++def _ec_user_create(logical_id, props, stack_name):+ user_id = props.get("UserId", "")+ _ec_call(_ec._create_user, _ec_query(props), "AWS::ElastiCache::User", "create")+ return user_id, _ec_user_attrs(user_id)+++def _ec_user_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id,+ new_props.get("UserId", ""),+ physical_id if physical_id in _ec._users else None,+ _ec_user_create, _ec_user_delete)+ if replaced:+ return replaced+ changed = _ec_changed(old_props, new_props,+ ("AccessString", "AuthenticationMode", "Engine",+ "NoPasswordRequired", "Passwords"))+ if changed:+ _ec_call(_ec._modify_user, {"UserId": physical_id, **_ec_query(changed)},+ "AWS::ElastiCache::User", "update")+ _ec_sync_tags(_ec._arn_user(physical_id), old_props, new_props, "AWS::ElastiCache::User")+ return physical_id, _ec_user_attrs(physical_id)+++def _ec_user_delete(physical_id, props):+ _ec._delete_user({"UserId": physical_id})+++def _ec_user_group_attrs(group_id):+ group = _ec._user_groups.get(group_id) or {}+ return {"Arn": group.get("ARN", _ec._arn_user_group(group_id)),+ "Status": group.get("Status", "active")}+++def _ec_user_group_create(logical_id, props, stack_name):+ group_id = props.get("UserGroupId", "")+ _ec_call(_ec._create_user_group, _ec_query(props), "AWS::ElastiCache::UserGroup", "create")+ return group_id, _ec_user_group_attrs(group_id)+++def _ec_user_group_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ replaced = _rename_replacement(+ physical_id, old_props, new_props, stack_name, logical_id,+ new_props.get("UserGroupId", ""),+ physical_id if physical_id in _ec._user_groups else None,+ _ec_user_group_create, _ec_user_group_delete)+ if replaced:+ return replaced+ old_users = list(old_props.get("UserIds") or [])+ new_users = list(new_props.get("UserIds") or [])+ params = _ec_query({"UserIdsToAdd": [u for u in new_users if u not in old_users],+ "UserIdsToRemove": [u for u in old_users if u not in new_users]})+ if params:+ _ec_call(_ec._modify_user_group, {"UserGroupId": physical_id, **params},+ "AWS::ElastiCache::UserGroup", "update")+ _ec_sync_tags(_ec._arn_user_group(physical_id), old_props, new_props,+ "AWS::ElastiCache::UserGroup")+ return physical_id, _ec_user_group_attrs(physical_id)+++def _ec_user_group_delete(physical_id, props):+ _ec._delete_user_group({"UserGroupId": physical_id})_glue_call(_glue._untag_resource, {"ResourceArn": arn, "TagsToRemove": removed},resource_type, "untag")if new_tags and new_tags != old_tags:@@ -11933,6 +12393,20 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"LayerName", "Content", "CompatibleRuntimes", "CompatibleArchitectures","Description", "LicenseInfo",),+ # createOnlyProperties of the published registry schemas.+ "AWS::ElastiCache::SubnetGroup": ("CacheSubnetGroupName",),+ "AWS::ElastiCache::ParameterGroup": ("CacheParameterGroupFamily",),+ "AWS::ElastiCache::CacheCluster": (+ "Port", "SnapshotArns", "SnapshotName", "CacheSubnetGroupName", "ClusterName",+ "Engine", "NetworkType",+ ),+ "AWS::ElastiCache::ReplicationGroup": (+ "AtRestEncryptionEnabled", "CacheSubnetGroupName", "DataTieringEnabled",+ "GlobalReplicationGroupId", "KmsKeyId", "NetworkType", "Port",+ "PreferredCacheClusterAZs", "ReplicationGroupId", "SnapshotArns", "SnapshotName",+ ),+ "AWS::ElastiCache::User": ("UserId", "UserName"),+ "AWS::ElastiCache::UserGroup": ("UserGroupId",),# 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@@ -11947,6 +12421,9 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {_CONDITIONALLY_REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {"AWS::DynamoDB::Table": ("KeySchema",),"AWS::Lambda::Function": ("DurableConfig",),+ # conditionalCreateOnlyProperties of the published registry schemas.+ "AWS::ElastiCache::CacheCluster": ("PreferredAvailabilityZones", "IpDiscovery"),+ "AWS::ElastiCache::ReplicationGroup": ("AuthToken", "NodeGroupConfiguration"),}@@ -11976,6 +12453,41 @@ _RESOURCE_HANDLERS = {"update": _s3_bucket_policy_update,"delete": _s3_bucket_policy_delete,},+ "AWS::ElastiCache::SubnetGroup": {+ "create": _ec_subnet_group_create,+ "update": _ec_subnet_group_update,+ "update_with_logical_id": True,+ "delete": _ec_subnet_group_delete,+ },+ "AWS::ElastiCache::ParameterGroup": {+ "create": _ec_parameter_group_create,+ "update": _ec_parameter_group_update,+ "update_with_logical_id": True,+ "delete": _ec_parameter_group_delete,+ },+ "AWS::ElastiCache::CacheCluster": {+ "create": _ec_cluster_create,+ "update": _ec_cluster_update,+ "update_with_logical_id": True,+ "delete": _ec_cluster_delete,+ },+ "AWS::ElastiCache::ReplicationGroup": {+ "create": _ec_rg_create,+ "update": _ec_rg_update,+ "update_with_logical_id": True,+ "delete": _ec_rg_delete,+ },+ "AWS::ElastiCache::User": {+ "create": _ec_user_create,+ "update": _ec_user_update,+ "update_with_logical_id": True,+ "delete": _ec_user_delete,+ },+ "AWS::ElastiCache::UserGroup": {+ "create": _ec_user_group_create,+ "update": _ec_user_group_update,+ "update_with_logical_id": True,+ "delete": _ec_user_group_delete,"AWS::Glue::Database": {"create": _glue_database_create,"update": _glue_database_update,diff --git a/ministack/services/cloudformation/stacks.py b/ministack/services/cloudformation/stacks.pyindex c9cb87de..401513e7 100644--- a/ministack/services/cloudformation/stacks.py+++ b/ministack/services/cloudformation/stacks.py@@ -68,15 +68,19 @@ def _create_stack_task_in_region(coro, stack: dict | None, stack_id: str | Noneasyncio.get_event_loop().create_task(coro)-def _is_custom_resource(resource_type: str) -> bool:- """The types whose provisioning blocks on a callback into this server, so- they run on a worker thread: custom resources wait for the ResponseURL- PUT, a WaitCondition for the signals on its handle, and a nested stack- deploys inline and may contain either."""+def _runs_on_worker_thread(resource_type: str) -> bool:+ """The types whose provisioning blocks, so they run on a worker thread:+ custom resources wait for the ResponseURL PUT, a WaitCondition for the+ signals on its handle, and a nested stack deploys inline and may contain+ either. ElastiCache clusters and replication groups start and stop their+ containers through the Docker daemon, the calls elasticache.py itself+ keeps off the event loop."""return (resource_type.startswith("Custom::")or resource_type in ("AWS::CloudFormation::CustomResource","AWS::CloudFormation::WaitCondition",- "AWS::CloudFormation::Stack"))+ "AWS::CloudFormation::Stack",+ "AWS::ElastiCache::CacheCluster",+ "AWS::ElastiCache::ReplicationGroup"))# ===========================================================================@@ -235,7 +239,7 @@ async def _revert_update(stack_id, stack_name, logical_id, rtype, physical_id,_add_event(stack_id, stack_name, logical_id, rtype, "UPDATE_IN_PROGRESS",physical_id=physical_id)try:- if _is_custom_resource(rtype):+ if _runs_on_worker_thread(rtype):new_pid, new_attrs = await run_reentrant(_update_resource, rtype, physical_id, applied_props,previous_props, stack_name, logical_id, attrs)@@ -290,7 +294,7 @@ async def _continue_update_rollback_async(stack_name: str, stack_id: str,still_failed[logical_id] = rescontinuetry:- if _is_custom_resource(rtype):+ if _runs_on_worker_thread(rtype):await run_reentrant(_delete_resource, rtype, pid,res.get("Properties", {}), stack_name, logical_id)else:@@ -460,7 +464,7 @@ async def _roll_back_operation(stack_name: str, stack_id: str, stack: dict,_add_event(stack_id, stack_name, logical_id, rtype,"DELETE_IN_PROGRESS", physical_id=pid)try:- if _is_custom_resource(rtype):+ if _runs_on_worker_thread(rtype):await run_reentrant(_delete_resource, rtype, pid, res_props,stack_name, logical_id@@ -673,7 +677,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,resource_type, old_tagged, new_tagged):update_attempt = (old_pid, new_tagged, old_tagged, old_attrs)try:- if _is_custom_resource(resource_type):+ if _runs_on_worker_thread(resource_type):physical_id, attrs = await run_reentrant(_update_resource, resource_type, old_pid, old_tagged,new_tagged, stack_name, logical_id, old_attrs@@ -698,7 +702,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,new_tagged = _with_stack_tags(resource_type, resolved_props, stack_tags,stack_name, stack_id, logical_id)- if _is_custom_resource(resource_type):+ if _runs_on_worker_thread(resource_type):physical_id, attrs = await run_reentrant(_provision_resource, resource_type, logical_id, new_tagged, stack_name)@@ -788,7 +792,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,delete_fn(*args, **kwargs)if new_pid == old_pid:continue- if _is_custom_resource(rtype):+ if _runs_on_worker_thread(rtype):await run_reentrant(_delete_resource, rtype, old_pid, old_props,stack_name, logical_id@@ -831,7 +835,7 @@ async def _deploy_stack_async(stack_name: str, stack_id: str, template: dict,try:if policy == "Snapshot":_snapshot_resource(rtype, pid, old_props)- if _is_custom_resource(rtype):+ if _runs_on_worker_thread(rtype):await run_reentrant(_delete_resource, rtype, pid, old_props,stack_name, logical_id@@ -979,7 +983,7 @@ async def _delete_stack_async(stack_name: str, stack_id: str,try:if policy == "Snapshot":_snapshot_resource(rtype, pid, res_props)- if _is_custom_resource(rtype):+ if _runs_on_worker_thread(rtype):await run_reentrant(_delete_resource, rtype, pid, res_props,stack_name, logical_iddiff --git a/tests/test_cfn_elasticache.py b/tests/test_cfn_elasticache.pynew file mode 100644index 00000000..31ee80d3--- /dev/null+++ b/tests/test_cfn_elasticache.py@@ -0,0 +1,409 @@+"""CloudFormation AWS::ElastiCache::* resource types (#1874)."""++import json+import os+import uuid++import pytest+from botocore.exceptions import ClientError, WaiterError++from ministack.services.cloudformation.stacks import _diff_resources++_WAIT = {"Delay": 1, "MaxAttempts": 120}+_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"++requires_docker = pytest.mark.skipif(+ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set - skipping network connectivity test",+)+++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 _reasons(cfn, name, logical_id):+ events = cfn.describe_stack_events(StackName=name)["StackEvents"]+ return [e.get("ResourceStatusReason", "") for e in events+ if e["LogicalResourceId"] == logical_id]+++def _error_code(call):+ with pytest.raises(ClientError) as exc:+ call()+ return exc.value.response["Error"]["Code"]+++def _params(ec, group):+ return {p["ParameterName"]: p["ParameterValue"]+ for p in ec.describe_cache_parameters(CacheParameterGroupName=group)["Parameters"]}+++def _cache_stack(s, *, rg_description="sessions", num_cache_clusters=2,+ params=None, subnet_description="cache subnets",+ access_string="on ~app:* +@all", extra_user=False,+ cluster_nodes=1, rg_tags=None):+ resources = {+ "Subnets": {"Type": "AWS::ElastiCache::SubnetGroup", "Properties": {+ "CacheSubnetGroupName": f"subnets-{s}",+ "Description": subnet_description,+ "SubnetIds": ["subnet-aaa", "subnet-bbb"],+ }},+ "Params": {"Type": "AWS::ElastiCache::ParameterGroup", "Properties": {+ "CacheParameterGroupFamily": "redis7",+ "Description": "app params",+ "Properties": params if params is not None else {+ "maxmemory-policy": "allkeys-lru", "timeout": "300"},+ }},+ "User": {"Type": "AWS::ElastiCache::User", "Properties": {+ "UserId": f"app-{s}", "UserName": f"app-{s}", "Engine": "redis",+ "AccessString": access_string, "Passwords": ["correct-horse-battery"],+ }},+ "Users": {"Type": "AWS::ElastiCache::UserGroup", "Properties": {+ "UserGroupId": f"users-{s}", "Engine": "redis",+ "UserIds": [{"Ref": "User"}] + ([{"Ref": "Other"}] if extra_user else []),+ }},+ "Cache": {"Type": "AWS::ElastiCache::ReplicationGroup", "Properties": {+ "ReplicationGroupId": f"cache-{s}",+ "ReplicationGroupDescription": rg_description,+ "Engine": "redis",+ "CacheNodeType": "cache.t3.micro",+ "NumCacheClusters": num_cache_clusters,+ "CacheSubnetGroupName": {"Ref": "Subnets"},+ "CacheParameterGroupName": {"Ref": "Params"},+ "UserGroupIds": [{"Ref": "Users"}],+ "TransitEncryptionEnabled": True,+ "Tags": rg_tags if rg_tags is not None else [{"Key": "team", "Value": "data"}],+ }},+ "Single": {"Type": "AWS::ElastiCache::CacheCluster", "Properties": {+ "ClusterName": f"single-{s}",+ "Engine": "redis",+ "CacheNodeType": "cache.t3.micro",+ "NumCacheNodes": cluster_nodes,+ "CacheSubnetGroupName": {"Ref": "Subnets"},+ }},+ }+ if extra_user:+ resources["Other"] = {"Type": "AWS::ElastiCache::User", "Properties": {+ "UserId": f"other-{s}", "UserName": f"other-{s}", "Engine": "redis",+ "AccessString": "on ~* +@read", "NoPasswordRequired": True,+ }}+ outputs = {k: {"Value": {"Ref": k}} for k in resources}++ def att(logical_id, attr):+ return {"Value": {"Fn::GetAtt": [logical_id, attr]}}++ outputs.update({+ "ParamsName": att("Params", "CacheParameterGroupName"),+ "UserArn": att("User", "Arn"),+ "UsersArn": att("Users", "Arn"),+ "PrimaryAddress": att("Cache", "PrimaryEndPoint.Address"),+ "PrimaryPort": att("Cache", "PrimaryEndPoint.Port"),+ "ReaderAddress": att("Cache", "ReaderEndPoint.Address"),+ "ReadAddresses": att("Cache", "ReadEndPoint.Addresses"),+ "SingleAddress": att("Single", "RedisEndpoint.Address"),+ "SinglePort": att("Single", "RedisEndpoint.Port"),+ })+ return {"Resources": resources, "Outputs": outputs}+++def test_cfn_elasticache_stack_create_and_delete(cfn, ec):+ s = _suffix()+ stack = f"ec-full-{s}"+ _create(cfn, stack, _cache_stack(s))+ out = _outputs(cfn, stack)+ assert out["Subnets"] == f"subnets-{s}"+ assert out["Cache"] == f"cache-{s}"+ assert out["Single"] == f"single-{s}"+ assert out["User"] == f"app-{s}" and out["Users"] == f"users-{s}"+ # The parameter group's name is read-only in the schema: always generated.+ assert out["Params"] == out["ParamsName"] == out["Params"].lower()+ try:+ groups = ec.describe_cache_subnet_groups(CacheSubnetGroupName=f"subnets-{s}")+ subnets = groups["CacheSubnetGroups"][0]["Subnets"]+ assert [n["SubnetIdentifier"] for n in subnets] == ["subnet-aaa", "subnet-bbb"]+ assert _params(ec, out["Params"])["maxmemory-policy"] == "allkeys-lru"++ user = ec.describe_users(UserId=f"app-{s}")["Users"][0]+ assert user["ARN"] == out["UserArn"]+ assert user["AccessString"] == "on ~app:* +@all"+ group = ec.describe_user_groups(UserGroupId=f"users-{s}")["UserGroups"][0]+ assert group["ARN"] == out["UsersArn"]+ assert group["UserIds"] == [f"app-{s}"]+ assert group["ReplicationGroups"] == [f"cache-{s}"]++ # The stack's endpoints are the ones the API reports for the same group.+ rg = ec.describe_replication_groups(ReplicationGroupId=f"cache-{s}")["ReplicationGroups"][0]+ primary = rg["NodeGroups"][0]["PrimaryEndpoint"]+ assert (out["PrimaryAddress"], out["PrimaryPort"]) == (primary["Address"], str(primary["Port"]))+ assert out["ReaderAddress"] == rg["NodeGroups"][0]["ReaderEndpoint"]["Address"]+ replicas = [m for m in rg["NodeGroups"][0]["NodeGroupMembers"] if m["CurrentRole"] == "replica"]+ assert out["ReadAddresses"] == ",".join(m["ReadEndpoint"]["Address"] for m in replicas)+ assert rg["CacheNodeType"] == "cache.t3.micro"+ assert rg["TransitEncryptionEnabled"] is True+ tags = ec.list_tags_for_resource(ResourceName=rg["ARN"])["TagList"]+ assert {"Key": "team", "Value": "data"} in tags++ cluster = ec.describe_cache_clusters(+ CacheClusterId=f"single-{s}", ShowCacheNodeInfo=True)["CacheClusters"][0]+ node = cluster["CacheNodes"][0]["Endpoint"]+ assert (out["SingleAddress"], out["SinglePort"]) == (node["Address"], str(node["Port"]))+ assert cluster["CacheSubnetGroupName"] == f"subnets-{s}"+ finally:+ _delete(cfn, stack)++ assert _error_code(lambda: ec.describe_replication_groups(+ ReplicationGroupId=f"cache-{s}")) == "ReplicationGroupNotFoundFault"+ assert _error_code(lambda: ec.describe_cache_clusters(+ CacheClusterId=f"single-{s}")) == "CacheClusterNotFound"+ assert _error_code(lambda: ec.describe_cache_subnet_groups(+ CacheSubnetGroupName=f"subnets-{s}")) == "CacheSubnetGroupNotFoundFault"+ assert _error_code(lambda: ec.describe_cache_parameter_groups(+ CacheParameterGroupName=out["Params"])) == "CacheParameterGroupNotFound"+ assert _error_code(lambda: ec.describe_users(UserId=f"app-{s}")) == "UserNotFound"+ assert _error_code(lambda: ec.describe_user_groups(+ UserGroupId=f"users-{s}")) == "UserGroupNotFound"+++def test_cfn_elasticache_update_in_place(cfn, ec):+ s = _suffix()+ stack = f"ec-upd-{s}"+ _create(cfn, stack, _cache_stack(s))+ before = _outputs(cfn, stack)+ try:+ _update(cfn, stack, _cache_stack(+ s, rg_description="sessions v2", num_cache_clusters=3,+ params={"maxmemory-policy": "volatile-ttl"}, subnet_description="new subnets",+ access_string="on ~* +@all", extra_user=True, cluster_nodes=2,+ rg_tags=[{"Key": "team", "Value": "platform"}]))+ after = _outputs(cfn, stack)+ for key in ("Subnets", "Params", "User", "Users", "Cache", "Single"):+ assert after[key] == before[key], key++ rg = ec.describe_replication_groups(ReplicationGroupId=f"cache-{s}")["ReplicationGroups"][0]+ assert rg["Description"] == "sessions v2"+ assert len(rg["NodeGroups"][0]["NodeGroupMembers"]) == 3+ tags = ec.list_tags_for_resource(ResourceName=rg["ARN"])["TagList"]+ assert {"Key": "team", "Value": "platform"} in tags++ params = _params(ec, before["Params"])+ assert params["maxmemory-policy"] == "volatile-ttl"+ # A parameter the template dropped goes back to its default.+ assert params["timeout"] == "0"+ group = ec.describe_cache_subnet_groups(CacheSubnetGroupName=f"subnets-{s}")+ assert group["CacheSubnetGroups"][0]["CacheSubnetGroupDescription"] == "new subnets"+ assert ec.describe_users(UserId=f"app-{s}")["Users"][0]["AccessString"] == "on ~* +@all"+ users = ec.describe_user_groups(UserGroupId=f"users-{s}")["UserGroups"][0]["UserIds"]+ assert sorted(users) == sorted([f"app-{s}", f"other-{s}"])+ cluster = ec.describe_cache_clusters(CacheClusterId=f"single-{s}")["CacheClusters"][0]+ assert cluster["NumCacheNodes"] == 2+ finally:+ _delete(cfn, stack)+++def test_cfn_elasticache_replication_group_rename_replaces(cfn, ec):+ s = _suffix()+ stack = f"ec-ren-{s}"++ def template(rg_id):+ return {"Resources": {"Rg": {"Type": "AWS::ElastiCache::ReplicationGroup", "Properties": {+ "ReplicationGroupId": rg_id, "ReplicationGroupDescription": "rename",+ "Engine": "redis", "CacheNodeType": "cache.t3.micro"}}}}++ _create(cfn, stack, template(f"first-{s}"))+ try:+ _update(cfn, stack, template(f"second-{s}"))+ ec.describe_replication_groups(ReplicationGroupId=f"second-{s}")+ assert _error_code(lambda: ec.describe_replication_groups(+ ReplicationGroupId=f"first-{s}")) == "ReplicationGroupNotFoundFault"+ finally:+ _delete(cfn, stack)+++def test_cfn_elasticache_generated_cluster_replaced_on_create_only_change(cfn, ec):+ s = _suffix()+ stack = f"Ec-Gen-{s}"++ def template(subnet_ref):+ return {+ "Resources": {+ "A": {"Type": "AWS::ElastiCache::SubnetGroup", "Properties": {+ "Description": "a", "SubnetIds": ["subnet-a"]}},+ "B": {"Type": "AWS::ElastiCache::SubnetGroup", "Properties": {+ "Description": "b", "SubnetIds": ["subnet-b"]}},+ "C": {"Type": "AWS::ElastiCache::CacheCluster", "Properties": {+ "Engine": "redis", "CacheNodeType": "cache.t3.micro", "NumCacheNodes": 1,+ "CacheSubnetGroupName": {"Ref": subnet_ref}}},+ },+ "Outputs": {k: {"Value": {"Ref": k}} for k in ("A", "B", "C")},+ }++ _create(cfn, stack, template("A"))+ try:+ out = _outputs(cfn, stack)+ # Generated names are lowercase, as ElastiCache stores them, and a+ # cluster name fits the 50-character limit.+ assert out["A"] == out["A"].lower() and out["A"].startswith(f"ec-gen-{s}-a-")+ assert out["C"] == out["C"].lower() and len(out["C"]) <= 50+ first = ec.describe_cache_clusters(CacheClusterId=out["C"])["CacheClusters"][0]+ # CacheSubnetGroupName is create-only: the cluster is replaced and+ # takes its generated name back.+ _update(cfn, stack, template("B"))+ assert _outputs(cfn, stack)["C"] == out["C"]+ second = ec.describe_cache_clusters(CacheClusterId=out["C"])["CacheClusters"][0]+ assert second["CacheSubnetGroupName"] == out["B"]+ assert second["CacheClusterCreateTime"] >= first["CacheClusterCreateTime"]+ finally:+ _delete(cfn, stack)+++def test_cfn_elasticache_named_cluster_engine_change_is_refused(cfn, ec):+ s = _suffix()+ stack = f"ec-ref-{s}"++ def template(engine):+ return {"Resources": {"C": {"Type": "AWS::ElastiCache::CacheCluster", "Properties": {+ "ClusterName": f"named-{s}", "Engine": engine,+ "CacheNodeType": "cache.t3.micro", "NumCacheNodes": 1}}}}++ _create(cfn, stack, template("redis"))+ try:+ cfn.update_stack(StackName=stack, TemplateBody=json.dumps(template("memcached")))+ with pytest.raises(WaiterError):+ cfn.get_waiter("stack_update_complete").wait(StackName=stack, WaiterConfig=_WAIT)+ assert any("custom-named resource requires replacing" in r+ for r in _reasons(cfn, stack, "C"))+ cluster = ec.describe_cache_clusters(CacheClusterId=f"named-{s}")["CacheClusters"][0]+ assert cluster["Engine"] == "redis"+ finally:+ _delete(cfn, stack)+++def test_cfn_elasticache_configuration_endpoint_needs_cluster_mode(cfn):+ # "Fn::GetAtt returns a value for this attribute only if the replication+ # group is clustered. Otherwise, Fn::GetAtt fails."+ s = _suffix()+ stack = f"ec-cfg-{s}"+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({+ "Resources": {"Rg": {"Type": "AWS::ElastiCache::ReplicationGroup", "Properties": {+ "ReplicationGroupDescription": "no cluster mode", "Engine": "redis",+ "CacheNodeType": "cache.t3.micro"}}},+ "Outputs": {"Cfg": {"Value": {"Fn::GetAtt": ["Rg", "ConfigurationEndPoint.Address"]}}},+ }))+ try:+ with pytest.raises(WaiterError):+ cfn.get_waiter("stack_create_complete").wait(StackName=stack, WaiterConfig=_WAIT)+ status = cfn.describe_stacks(StackName=stack)["Stacks"][0]["StackStatus"]+ assert status == "ROLLBACK_COMPLETE"+ finally:+ _delete(cfn, stack)+++def test_cfn_elasticache_memcached_configuration_endpoint(cfn, ec):+ s = _suffix()+ stack = f"ec-mc-{s}"+ _create(cfn, stack, {+ "Resources": {"Mc": {"Type": "AWS::ElastiCache::CacheCluster", "Properties": {+ "ClusterName": f"mc-{s}", "Engine": "memcached", "EngineVersion": "1.6.17",+ "CacheNodeType": "cache.t3.micro", "NumCacheNodes": 1}}},+ "Outputs": {"Address": {"Value": {"Fn::GetAtt": ["Mc", "ConfigurationEndpoint.Address"]}},+ "Port": {"Value": {"Fn::GetAtt": ["Mc", "ConfigurationEndpoint.Port"]}}},+ })+ try:+ out = _outputs(cfn, stack)+ node = ec.describe_cache_clusters(+ CacheClusterId=f"mc-{s}", ShowCacheNodeInfo=True)["CacheClusters"][0]["CacheNodes"][0]+ assert (out["Address"], out["Port"]) == (node["Endpoint"]["Address"], str(node["Endpoint"]["Port"]))+ finally:+ _delete(cfn, stack)+++# Expected values follow the createOnlyProperties and+# conditionalCreateOnlyProperties of the published registry schemas; they were+# not observed on an AWS change set.[email protected]("rtype,old,new,expected", [+ ("AWS::ElastiCache::CacheCluster", {"Engine": "redis"}, {"Engine": "memcached"}, "Always"),+ ("AWS::ElastiCache::CacheCluster", {"NumCacheNodes": 1}, {"NumCacheNodes": 2}, "Never"),+ ("AWS::ElastiCache::CacheCluster", {"IpDiscovery": "ipv4"}, {"IpDiscovery": "ipv6"}, "Conditionally"),+ ("AWS::ElastiCache::ReplicationGroup", {"Port": 6379}, {"Port": 6380}, "Always"),+ ("AWS::ElastiCache::ReplicationGroup", {"AuthToken": "a" * 16}, {"AuthToken": "b" * 16}, "Conditionally"),+ ("AWS::ElastiCache::ReplicationGroup", {"CacheNodeType": "cache.t3.micro"},+ {"CacheNodeType": "cache.t3.small"}, "Never"),+ ("AWS::ElastiCache::ParameterGroup", {"CacheParameterGroupFamily": "redis6.x"},+ {"CacheParameterGroupFamily": "redis7"}, "Always"),+ ("AWS::ElastiCache::User", {"UserName": "a"}, {"UserName": "b"}, "Always"),+ ("AWS::ElastiCache::UserGroup", {"UserIds": ["a"]}, {"UserIds": ["b"]}, "Never"),+])+def test_cfn_elasticache_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}+++@requires_docker[email protected]_plane+def test_cfn_elasticache_lambda_reaches_replication_group(cfn, lam):+ """The issue's use case: a stack passes PrimaryEndPoint into a function's+ environment, and the function talks to the container behind it."""+ s = _suffix()+ stack = f"ec-lam-{s}"+ code = (+ "import os, socket\n"+ "def handler(event, context):\n"+ " s = socket.create_connection((os.environ['REDIS_HOST'], int(os.environ['REDIS_PORT'])), timeout=5)\n"+ " s.sendall(b'PING\\r\\n')\n"+ " reply = s.recv(64).decode()\n"+ " s.close()\n"+ " return {'reply': reply.strip()}\n"+ )+ _create(cfn, stack, {+ "Resources": {+ "Cache": {"Type": "AWS::ElastiCache::ReplicationGroup", "Properties": {+ "ReplicationGroupDescription": "lambda", "Engine": "redis",+ "CacheNodeType": "cache.t3.micro"}},+ "Fn": {"Type": "AWS::Lambda::Function", "Properties": {+ "FunctionName": f"ec-ping-{s}", "Runtime": "python3.12",+ "Handler": "index.handler", "Role": _LAMBDA_ROLE, "Timeout": 15,+ "Code": {"ZipFile": code},+ "Environment": {"Variables": {+ "REDIS_HOST": {"Fn::GetAtt": ["Cache", "PrimaryEndPoint.Address"]},+ "REDIS_PORT": {"Fn::GetAtt": ["Cache", "PrimaryEndPoint.Port"]},+ }}}},+ },+ })+ try:+ import time+ deadline = time.time() + 60+ while True:+ resp = lam.invoke(FunctionName=f"ec-ping-{s}", Payload=b"{}")+ result = json.loads(resp["Payload"].read())+ if result.get("reply") == "+PONG" or time.time() > deadline:+ break+ time.sleep(1)+ assert result.get("reply") == "+PONG", result+ finally:+ _delete(cfn, stack)