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::ServiceDiscovery namespace, service and instance types (#1876) (#1906)
Fábio André Ramos Rodrigues898f290514b5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 45778b42..db02fc13 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).### Added- **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.### Fixeddiff --git a/README.md b/README.mdindex b56f5145..f498a0ec 100644--- a/README.md+++ b/README.md@@ -551,6 +551,11 @@ subnet = ec2.create_subnet(| `AWS::StepFunctions::StateMachine` | State machine ARN | Arn, Name || `AWS::Route53::HostedZone` | Zone ID | Id, NameServers || `AWS::Route53::RecordSet` | Record FQDN (trailing dot) | Name |+| `AWS::ServiceDiscovery::HttpNamespace` | Namespace ID | Arn, Id |+| `AWS::ServiceDiscovery::PrivateDnsNamespace` | Namespace ID | Arn, HostedZoneId, Id |+| `AWS::ServiceDiscovery::PublicDnsNamespace` | Namespace ID | Arn, HostedZoneId, Id |+| `AWS::ServiceDiscovery::Service` | Service ID | Arn, Id, Name |+| `AWS::ServiceDiscovery::Instance` | Instance ID | — || `AWS::ApiGatewayV2::Api` | API ID | ApiId, ApiEndpoint || `AWS::ApiGatewayV2::Stage` | Stage ID | StageName || `AWS::ApiGatewayV2::Integration` | Integration ID | IntegrationId |diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 162aaffa..7cf1a601 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -50,6 +50,7 @@ import ministack.services.route53 as _r53import ministack.services.s3 as _s3import ministack.services.s3tables as _s3tablesimport ministack.services.secretsmanager as _sm+import ministack.services.servicediscovery as _sdimport ministack.services.ses as _sesimport ministack.services.ses_v2 as _ses_v2import ministack.services.sns as _sns@@ -993,6 +994,10 @@ _STACK_TAG_PROPERTY: dict[str, tuple[str, str]] = {"AWS::SSM::Parameter": ("Tags", "map"),"AWS::Scheduler::ScheduleGroup": ("Tags", "list"),"AWS::SecretsManager::Secret": ("Tags", "list"),+ "AWS::ServiceDiscovery::HttpNamespace": ("Tags", "list"),+ "AWS::ServiceDiscovery::PrivateDnsNamespace": ("Tags", "list"),+ "AWS::ServiceDiscovery::PublicDnsNamespace": ("Tags", "list"),+ "AWS::ServiceDiscovery::Service": ("Tags", "list"),"AWS::StepFunctions::StateMachine": ("Tags", "list"),}@@ -8705,6 +8710,231 @@ def _elbv2_listener_rule_update(physical_id, old_props, new_props, stack_name,return physical_id, {"RuleArn": physical_id}+# ---------------------------------------------------------------------------+# Cloud Map (AWS::ServiceDiscovery::*)+#+# Every handler goes through the servicediscovery module's own functions, so a+# stack-created namespace gets its Route 53 hosted zone and a service or+# instance the same record the API writes. Ref, Fn::GetAtt and the+# replacement properties follow the CloudFormation Template Reference pages for+# the five types. Tags are "Updates are not supported" on every taggable type,+# so an update leaves them as created.+# ---------------------------------------------------------------------------++_SD_NAMESPACE_TYPES = {+ "HTTP": "AWS::ServiceDiscovery::HttpNamespace",+ "DNS_PRIVATE": "AWS::ServiceDiscovery::PrivateDnsNamespace",+ "DNS_PUBLIC": "AWS::ServiceDiscovery::PublicDnsNamespace",+}+++def _sd_result(response, what, missing_ok=False):+ """The parsed body of a servicediscovery call, or ValueError naming+ ``what``. With ``missing_ok`` a 404 (resource already gone) returns None."""+ status, _, body = response+ if status == 404 and missing_ok:+ return None+ if status >= 400:+ raise ValueError(f"{what} failed: {body!r}")+ return json.loads(body) if body else {}+++def _sd_soa_ttl(props):+ return ((((props.get("Properties") or {}).get("DnsProperties") or {})+ .get("SOA") or {}).get("TTL"))+++def _sd_namespace_attrs(namespace):+ attrs = {"Id": namespace["Id"], "Arn": namespace["Arn"]}+ zone_id = (namespace.get("Properties") or {}).get("DnsProperties", {}).get("HostedZoneId")+ if zone_id:+ attrs["HostedZoneId"] = zone_id+ return attrs+++def _sd_namespace_create_for(ns_type):+ """The create handler for one of the three namespace types."""+ resource_type = _SD_NAMESPACE_TYPES[ns_type]++ def create(logical_id, props, stack_name):+ name = props.get("Name")+ if not name:+ raise ValueError(f"{resource_type} requires Name")+ namespace, err = _sd._create_namespace_record(+ name, ns_type, props.get("Description"), props.get("Tags"),+ _sd_soa_ttl(props) if ns_type != "HTTP" else None,+ )+ if err:+ raise ValueError(f"{resource_type} create failed: {err[2]!r}")+ return namespace["Id"], _sd_namespace_attrs(namespace)++ return create+++def _sd_namespace_update_for(ns_type):+ """The update handler for one of the three namespace types. Name, and Vpc+ on a private namespace, require replacement; the namespace id is+ generated, so the new namespace is created before the old one is+ removed. Description and the SOA TTL change in place."""+ resource_type = _SD_NAMESPACE_TYPES[ns_type]+ create = _sd_namespace_create_for(ns_type)++ def update(physical_id, old_props, new_props, stack_name, logical_id=None):+ namespace = _sd._namespaces.get(physical_id)+ if (namespace is None or new_props.get("Name") != namespace["Name"]+ or new_props.get("Vpc") != old_props.get("Vpc")):+ created = create(logical_id or physical_id, new_props, stack_name)+ if namespace is not None:+ _delete_predecessor(_sd_namespace_delete, physical_id, old_props)+ return created+ change = {}+ if "Description" in new_props or "Description" in old_props:+ change["Description"] = new_props.get("Description")+ ttl = _sd_soa_ttl(new_props)+ if ttl is not None and ns_type != "HTTP":+ change["Properties"] = {"DnsProperties": {"SOA": {"TTL": ttl}}}+ if change:+ _sd_result(_sd._update_namespace({"Id": physical_id, "Namespace": change}),+ f"{resource_type} update")+ return physical_id, _sd_namespace_attrs(namespace)++ return update+++def _sd_namespace_delete(physical_id, props):+ _sd_result(_sd._delete_namespace({"Id": physical_id}),+ "AWS::ServiceDiscovery namespace delete", missing_ok=True)+++# UpdateService's members, each reverting to None when the template drops it.+_SD_SERVICE_UPDATABLE = {"Description": None, "DnsConfig": None, "HealthCheckConfig": None}+++def _sd_string_map(values):+ """A Cloud Map attribute map: string keys and string values."""+ return {str(k): str(v) for k, v in (values or {}).items()}+++def _sd_service_name(props, stack_name, logical_id):+ # Inference: AWS documents no format for a generated service name; a+ # Cloud Map DNS label is at most 63 characters.+ return props.get("Name") or _physical_name(stack_name, logical_id, max_len=63)+++def _sd_service_namespace_id(props):+ return props.get("NamespaceId") or (props.get("DnsConfig") or {}).get("NamespaceId")+++def _sd_service_attrs(service):+ return {"Id": service["Id"], "Arn": service["Arn"], "Name": service["Name"]}+++def _sd_service_create(logical_id, props, stack_name):+ payload = {+ key: props[key]+ for key in ("Description", "DnsConfig", "HealthCheckConfig", "HealthCheckCustomConfig", "Tags")+ if key in props+ }+ payload["Name"] = _sd_service_name(props, stack_name, logical_id)+ payload["NamespaceId"] = _sd_service_namespace_id(props)+ service = _sd_result(_sd._create_service(payload),+ "AWS::ServiceDiscovery::Service create")["Service"]+ if props.get("ServiceAttributes"):+ _sd_result(_sd._update_service_attributes({+ "ServiceId": service["Id"],+ "Attributes": _sd_string_map(props["ServiceAttributes"]),+ }), "AWS::ServiceDiscovery::Service ServiceAttributes")+ return service["Id"], _sd_service_attrs(service)+++def _sd_service_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """Name, NamespaceId, Type and HealthCheckCustomConfig require+ replacement; the service id is generated, so the new service is created+ before the old one is removed. Description, DnsConfig, HealthCheckConfig+ and ServiceAttributes change in place."""+ logical_id = logical_id or physical_id+ service = _sd._services.get(physical_id)+ if (service is None+ or _sd_service_name(new_props, stack_name, logical_id) != service["Name"]+ or _sd_service_namespace_id(new_props) != service["NamespaceId"]+ or new_props.get("Type") != old_props.get("Type")+ or new_props.get("HealthCheckCustomConfig") != old_props.get("HealthCheckCustomConfig")):+ created = _sd_service_create(logical_id, new_props, stack_name)+ if service is not None:+ _delete_predecessor(_sd_service_delete, physical_id, old_props)+ return created+ change = _declared_or_default(old_props, new_props, _SD_SERVICE_UPDATABLE)+ if change:+ _sd_result(_sd._update_service({"Id": physical_id, "Service": change}),+ "AWS::ServiceDiscovery::Service update")+ old_attrs = _sd_string_map(old_props.get("ServiceAttributes"))+ new_attrs = _sd_string_map(new_props.get("ServiceAttributes"))+ dropped = sorted(old_attrs.keys() - new_attrs.keys())+ if dropped:+ _sd_result(_sd._delete_service_attributes({"ServiceId": physical_id, "Attributes": dropped}),+ "AWS::ServiceDiscovery::Service ServiceAttributes")+ if new_attrs and new_attrs != old_attrs:+ _sd_result(_sd._update_service_attributes({"ServiceId": physical_id, "Attributes": new_attrs}),+ "AWS::ServiceDiscovery::Service ServiceAttributes")+ return physical_id, _sd_service_attrs(service)+++def _sd_service_delete(physical_id, props):+ _sd_result(_sd._delete_service({"Id": physical_id}),+ "AWS::ServiceDiscovery::Service delete", missing_ok=True)+++def _sd_instance_id(props, stack_name, logical_id):+ # Inference: AWS documents no format for a generated instance id.+ return props.get("InstanceId") or _physical_name(stack_name, logical_id, max_len=64)+++def _sd_register_instance(instance_id, props):+ _sd_result(_sd._register_instance({+ "ServiceId": props.get("ServiceId", ""),+ "InstanceId": instance_id,+ "Attributes": _sd_string_map(props.get("InstanceAttributes")),+ }), "AWS::ServiceDiscovery::Instance register")+++def _sd_instance_create(logical_id, props, stack_name):+ """Register the instance. An id already registered in the service is+ refused, so a template cannot take over an instance registered outside+ the stack (inference: RegisterInstance upserts, and AWS documents no+ CloudFormation behaviour for an existing id)."""+ instance_id = _sd_instance_id(props, stack_name, logical_id)+ service_id = props.get("ServiceId", "")+ if instance_id in _sd._instances.get(service_id, {}):+ raise ValueError(+ f"AWS::ServiceDiscovery::Instance {instance_id} is already registered "+ f"in service {service_id}"+ )+ _sd_register_instance(instance_id, props)+ return instance_id, {}+++def _sd_instance_update(physical_id, old_props, new_props, stack_name, logical_id=None):+ """InstanceId and ServiceId require replacement. A ServiceId change keeps+ a user-chosen InstanceId, so the predecessor delete is queued even when+ the physical id is unchanged; the engine treats that as a replacement.+ InstanceAttributes re-register the instance in place."""+ logical_id = logical_id or physical_id+ instance_id = _sd_instance_id(new_props, stack_name, logical_id)+ if instance_id != physical_id or new_props.get("ServiceId") != old_props.get("ServiceId"):+ created = _sd_instance_create(logical_id, new_props, stack_name)+ _delete_predecessor(_sd_instance_delete, physical_id, old_props)+ return created+ _sd_register_instance(physical_id, new_props)+ return physical_id, {}+++def _sd_instance_delete(physical_id, props):+ _sd_result(_sd._deregister_instance({+ "ServiceId": props.get("ServiceId", ""),+ "InstanceId": physical_id,+ }), "AWS::ServiceDiscovery::Instance deregister", missing_ok=True)++# ---------------------------------------------------------------------------# Route53 HostedZone# ---------------------------------------------------------------------------@@ -11815,6 +12045,36 @@ _RESOURCE_HANDLERS = {"delete": _r53_hosted_zone_delete,},"AWS::Route53::RecordSet": {"create": _r53_record_set_create, "update": _r53_record_set_update, "delete": _r53_record_set_delete},+ "AWS::ServiceDiscovery::HttpNamespace": {+ "create": _sd_namespace_create_for("HTTP"),+ "update": _sd_namespace_update_for("HTTP"),+ "update_with_logical_id": True,+ "delete": _sd_namespace_delete,+ },+ "AWS::ServiceDiscovery::PrivateDnsNamespace": {+ "create": _sd_namespace_create_for("DNS_PRIVATE"),+ "update": _sd_namespace_update_for("DNS_PRIVATE"),+ "update_with_logical_id": True,+ "delete": _sd_namespace_delete,+ },+ "AWS::ServiceDiscovery::PublicDnsNamespace": {+ "create": _sd_namespace_create_for("DNS_PUBLIC"),+ "update": _sd_namespace_update_for("DNS_PUBLIC"),+ "update_with_logical_id": True,+ "delete": _sd_namespace_delete,+ },+ "AWS::ServiceDiscovery::Service": {+ "create": _sd_service_create,+ "update": _sd_service_update,+ "update_with_logical_id": True,+ "delete": _sd_service_delete,+ },+ "AWS::ServiceDiscovery::Instance": {+ "create": _sd_instance_create,+ "update": _sd_instance_update,+ "update_with_logical_id": True,+ "delete": _sd_instance_delete,+ },"AWS::ApiGatewayV2::Api": {"create": _apigw_v2_api_create,"update": _apigw_v2_api_update,diff --git a/ministack/services/servicediscovery.py b/ministack/services/servicediscovery.pyindex 62dc2b8e..13e01702 100644--- a/ministack/services/servicediscovery.py+++ b/ministack/services/servicediscovery.py@@ -253,11 +253,7 @@ async def _create_namespace(data):ns_name = data.get("Name")if not ns_name:return error_response_json("InvalidInput", "Name is required", 400)- for existing in _namespaces.values():- if existing["Name"] == ns_name:- return error_response_json("NamespaceAlreadyExists", f"Namespace {ns_name} already exists", 409)- ns_id = f"ns-{new_uuid()[:8]}"action = data.get("_action", "")# Infer namespace type from action; fallback uses request fields.@@ -284,61 +280,71 @@ async def _create_namespace(data):elif is_http:ns_type = "HTTP"+ soa = ((data.get("Properties") or {}).get("DnsProperties") or {}).get("SOA") or {}+ namespace, err = _create_namespace_record(+ ns_name, ns_type, data.get("Description"), data.get("Tags", []), soa.get("TTL")+ )+ if err:+ return err++ op_id = _create_operation("CREATE_NAMESPACE", {"NAMESPACE": namespace["Id"]})+ return json_response({"OperationId": op_id})+++def _create_namespace_record(name, ns_type, description=None, tags=None, soa_ttl=None):+ """Create a namespace and, for a DNS type, its hosted zone. Returns+ (namespace, None), or (None, error response) for the caller to return.+ Synchronous so the CloudFormation provisioners can call it."""+ for existing in _namespaces.values():+ if existing["Name"] == name:+ return None, error_response_json("NamespaceAlreadyExists", f"Namespace {name} already exists", 409)++ ns_id = f"ns-{new_uuid()[:8]}"namespace = {"Id": ns_id,"Arn": _namespace_arn(ns_id),- "Name": ns_name,+ "Name": name,"Type": ns_type,- "Description": data.get("Description"),+ "Description": description,"CreateDate": int(time.time()),}if ns_type != "HTTP":- zone_name = ns_name if ns_name.endswith(".") else ns_name + "."+ zone_name = name if name.endswith(".") else name + "."xml_body = f"""<CreateHostedZoneRequest xmlns=\"https://route53.amazonaws.com/doc/2013-04-01/\"><Name>{zone_name}</Name><CallerReference>{new_uuid()}</CallerReference><HostedZoneConfig><Comment>Created by Cloud Map</Comment>- <PrivateZone>{"true" if is_private else "false"}</PrivateZone>+ <PrivateZone>{"true" if ns_type == "DNS_PRIVATE" else "false"}</PrivateZone></HostedZoneConfig></CreateHostedZoneRequest>"""- status, _, body = await route53.handle_request(- "POST",- "/2013-04-01/hostedzone",- {},- xml_body.encode("utf-8"),- {},- )+ status, _, body = route53._create_hosted_zone(xml_body.encode("utf-8"), {})if status >= 300:- return error_response_json("InternalFailure", "Failed to create Route53 hosted zone", 500)+ return None, error_response_json("InternalFailure", "Failed to create Route53 hosted zone", 500)root = ET.fromstring(body)zone_id_el = root.find(".//{https://route53.amazonaws.com/doc/2013-04-01/}Id")if zone_id_el is None or not zone_id_el.text:- return error_response_json("InternalFailure", "Hosted zone ID missing in Route53 response", 500)+ return None, error_response_json("InternalFailure", "Hosted zone ID missing in Route53 response", 500)zone_id = zone_id_el.text.split("/")[-1]- namespace["Properties"] = {- "DnsProperties": {- "HostedZoneId": zone_id,- }- }+ dns_properties = {"HostedZoneId": zone_id}+ if soa_ttl is not None:+ dns_properties["SOA"] = {"TTL": int(soa_ttl)}+ namespace["Properties"] = {"DnsProperties": dns_properties}else:namespace["Properties"] = {"HttpProperties": {- "HttpName": ns_name,+ "HttpName": name,}}_namespaces[ns_id] = namespace- tags = data.get("Tags", [])if tags:_resource_tags[namespace["Arn"]] = tags-- op_id = _create_operation("CREATE_NAMESPACE", {"NAMESPACE": ns_id})- return json_response({"OperationId": op_id})+ return namespace, Nonedef _delete_namespace(data):@@ -351,6 +357,15 @@ def _delete_namespace(data):namespace = _namespaces.pop(ns_id)_resource_tags.pop(namespace.get("Arn", ""), None)+ # AWS removes the hosted zone with the namespace. A zone that is already+ # gone is fine; one holding records outside Cloud Map stays, and the+ # namespace delete still succeeds.+ zone_id = ((namespace.get("Properties") or {}).get("DnsProperties") or {}).get("HostedZoneId")+ if zone_id:+ status, _, body = route53._delete_hosted_zone(zone_id)+ if status >= 300 and status != 404:+ logger.warning("Hosted zone %s of namespace %s not deleted: %s", zone_id, ns_id, body)+op_id = _create_operation("DELETE_NAMESPACE", {"NAMESPACE": ns_id})return json_response({"OperationId": op_id})@@ -667,6 +682,10 @@ def _update_namespace(data):namespace_update = data.get("Namespace", {})if "Description" in namespace_update:ns["Description"] = namespace_update.get("Description")+ soa = ((namespace_update.get("Properties") or {}).get("DnsProperties") or {}).get("SOA")+ dns_properties = (ns.get("Properties") or {}).get("DnsProperties")+ if soa and "TTL" in soa and dns_properties is not None:+ dns_properties["SOA"] = {"TTL": int(soa["TTL"])}op_id = _create_operation("UPDATE_NAMESPACE", {"NAMESPACE": ns_id})return json_response({"OperationId": op_id})diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex a5eb0e38..ad8e546f 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -6285,6 +6285,315 @@ def test_cfn_route53_hosted_zone_and_record_set(cfn, r53):assert exc.value.response["Error"]["Code"] == "NoSuchHostedZone"+# ---------------------------------------------------------------------------+# AWS::ServiceDiscovery::* (#1876). Ref, Fn::GetAtt and replacement properties+# follow the CloudFormation Template Reference pages for the five types.+# ---------------------------------------------------------------------------+++def _sd_physical_ids(cfn, stack_name):+ resources = cfn.describe_stack_resources(StackName=stack_name)["StackResources"]+ return {r["LogicalResourceId"]: r["PhysicalResourceId"] for r in resources}+++def _sd_stack_template(uid, ns_name=None, ns_description="ns", soa_ttl=100,+ svc_description="svc", dns_ttl=60, svc_attributes=None,+ health_threshold=1, instance_id=None, instance_ip="10.0.0.1"):+ """A private namespace, a service in it and one instance in the service."""+ return {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Ns": {+ "Type": "AWS::ServiceDiscovery::PrivateDnsNamespace",+ "Properties": {+ "Name": ns_name or f"sd{uid}.local",+ "Vpc": "vpc-12345",+ "Description": ns_description,+ "Properties": {"DnsProperties": {"SOA": {"TTL": soa_ttl}}},+ },+ },+ "Svc": {+ "Type": "AWS::ServiceDiscovery::Service",+ "Properties": {+ "Name": "api",+ "Description": svc_description,+ "DnsConfig": {+ "NamespaceId": {"Fn::GetAtt": ["Ns", "Id"]},+ "DnsRecords": [{"Type": "A", "TTL": dns_ttl}],+ "RoutingPolicy": "MULTIVALUE",+ },+ "HealthCheckCustomConfig": {"FailureThreshold": health_threshold},+ "ServiceAttributes": svc_attributes or {"team": "a"},+ },+ },+ "Inst": {+ "Type": "AWS::ServiceDiscovery::Instance",+ "Properties": {+ "ServiceId": {"Ref": "Svc"},+ "InstanceId": instance_id or "inst-1",+ "InstanceAttributes": {"AWS_INSTANCE_IPV4": instance_ip, "port": 8080},+ },+ },+ },+ }+++def test_cfn_servicediscovery_validate_template(cfn):+ template = _sd_stack_template(_uuid_mod.uuid4().hex[:8])+ template["Resources"]["Http"] = {+ "Type": "AWS::ServiceDiscovery::HttpNamespace",+ "Properties": {"Name": "http-ns"},+ }+ template["Resources"]["Pub"] = {+ "Type": "AWS::ServiceDiscovery::PublicDnsNamespace",+ "Properties": {"Name": "pub.example.com"},+ }+ cfn.validate_template(TemplateBody=json.dumps(template))+++def test_cfn_servicediscovery_namespaces_create(cfn, sd, r53):+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-sd-ns-{uid}"+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Http": {+ "Type": "AWS::ServiceDiscovery::HttpNamespace",+ "Properties": {"Name": f"http-{uid}", "Description": "http"},+ },+ "Priv": {+ "Type": "AWS::ServiceDiscovery::PrivateDnsNamespace",+ "Properties": {"Name": f"priv{uid}.local", "Vpc": "vpc-12345"},+ },+ "Pub": {+ "Type": "AWS::ServiceDiscovery::PublicDnsNamespace",+ "Properties": {"Name": f"pub{uid}.example.com"},+ },+ },+ "Outputs": {+ "HttpRef": {"Value": {"Ref": "Http"}},+ "HttpArn": {"Value": {"Fn::GetAtt": ["Http", "Arn"]}},+ "PrivId": {"Value": {"Fn::GetAtt": ["Priv", "Id"]}},+ "PrivZone": {"Value": {"Fn::GetAtt": ["Priv", "HostedZoneId"]}},+ "PubRef": {"Value": {"Ref": "Pub"}},+ "PubZone": {"Value": {"Fn::GetAtt": ["Pub", "HostedZoneId"]}},+ },+ }+ cfn.create_stack(+ StackName=stack_name, TemplateBody=json.dumps(template),+ Tags=[{"Key": "env", "Value": "test"}],+ )+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}++ http = sd.get_namespace(Id=outputs["HttpRef"])["Namespace"]+ assert http["Type"] == "HTTP"+ assert http["Arn"] == outputs["HttpArn"]+ assert http["Description"] == "http"+ assert "DnsProperties" not in http["Properties"]++ priv = sd.get_namespace(Id=outputs["PrivId"])["Namespace"]+ assert priv["Type"] == "DNS_PRIVATE"+ assert priv["Properties"]["DnsProperties"]["HostedZoneId"] == outputs["PrivZone"]+ assert r53.get_hosted_zone(Id=outputs["PrivZone"])["HostedZone"]["Config"]["PrivateZone"] is True++ pub = sd.get_namespace(Id=outputs["PubRef"])["Namespace"]+ assert pub["Type"] == "DNS_PUBLIC"+ assert r53.get_hosted_zone(Id=outputs["PubZone"])["HostedZone"]["Config"]["PrivateZone"] is False++ tags = sd.list_tags_for_resource(ResourceARN=http["Arn"])["Tags"]+ assert {"Key": "env", "Value": "test"} in tags++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_servicediscovery_service_and_instance(cfn, sd):+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-sd-svc-{uid}"+ template = _sd_stack_template(uid)+ template["Outputs"] = {+ "SvcRef": {"Value": {"Ref": "Svc"}},+ "SvcArn": {"Value": {"Fn::GetAtt": ["Svc", "Arn"]}},+ "SvcName": {"Value": {"Fn::GetAtt": ["Svc", "Name"]}},+ "InstRef": {"Value": {"Ref": "Inst"}},+ }+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}++ svc = sd.get_service(Id=outputs["SvcRef"])["Service"]+ assert svc["Arn"] == outputs["SvcArn"]+ assert svc["Name"] == outputs["SvcName"] == "api"+ assert svc["NamespaceId"] == _sd_physical_ids(cfn, stack_name)["Ns"]+ attrs = sd.get_service_attributes(ServiceId=svc["Id"])["ServiceAttributes"]["Attributes"]+ assert attrs == {"team": "a"}++ assert outputs["InstRef"] == "inst-1"+ found = sd.discover_instances(NamespaceName=f"sd{uid}.local", ServiceName="api")["Instances"]+ assert [i["InstanceId"] for i in found] == ["inst-1"]+ assert found[0]["Attributes"] == {"AWS_INSTANCE_IPV4": "10.0.0.1", "port": "8080"}++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_servicediscovery_update_in_place(cfn, sd):+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-sd-upd-{uid}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_sd_stack_template(uid)))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ before = _sd_physical_ids(cfn, stack_name)++ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(_sd_stack_template(+ uid, ns_description="ns2", soa_ttl=60, svc_description="svc2", dns_ttl=30,+ svc_attributes={"owner": "b"}, instance_ip="10.0.0.2",+ )))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"+ assert _sd_physical_ids(cfn, stack_name) == before++ ns = sd.get_namespace(Id=before["Ns"])["Namespace"]+ assert ns["Description"] == "ns2"+ assert ns["Properties"]["DnsProperties"]["SOA"]["TTL"] == 60++ svc = sd.get_service(Id=before["Svc"])["Service"]+ assert svc["Description"] == "svc2"+ assert svc["DnsConfig"]["DnsRecords"] == [{"Type": "A", "TTL": 30}]+ attrs = sd.get_service_attributes(ServiceId=before["Svc"])["ServiceAttributes"]["Attributes"]+ assert attrs == {"owner": "b"}++ inst = sd.get_instance(ServiceId=before["Svc"], InstanceId="inst-1")["Instance"]+ assert inst["Attributes"]["AWS_INSTANCE_IPV4"] == "10.0.0.2"++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_servicediscovery_update_replacement(cfn, sd, r53):+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-sd-repl-{uid}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_sd_stack_template(uid)))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ first = _sd_physical_ids(cfn, stack_name)++ # HealthCheckCustomConfig and InstanceId both require replacement.+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(_sd_stack_template(+ uid, health_threshold=2, instance_id="inst-2",+ )))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"+ second = _sd_physical_ids(cfn, stack_name)+ assert second["Ns"] == first["Ns"]+ assert second["Svc"] != first["Svc"]+ assert second["Inst"] == "inst-2"+ with pytest.raises(ClientError) as exc:+ sd.get_service(Id=first["Svc"])+ assert exc.value.response["Error"]["Code"] == "ServiceNotFound"+ svc = sd.get_service(Id=second["Svc"])["Service"]+ assert svc["HealthCheckCustomConfig"] == {"FailureThreshold": 2}+ instances = sd.list_instances(ServiceId=second["Svc"])["Instances"]+ assert [i["Id"] for i in instances] == ["inst-2"]++ # A new namespace Name replaces the namespace, and through Ref the+ # service and the instance (same InstanceId, new ServiceId).+ old_zone = sd.get_namespace(Id=first["Ns"])["Namespace"]["Properties"]["DnsProperties"]["HostedZoneId"]+ cfn.update_stack(StackName=stack_name, TemplateBody=json.dumps(_sd_stack_template(+ uid, ns_name=f"sd{uid}-b.local", health_threshold=2, instance_id="inst-2",+ )))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "UPDATE_COMPLETE"+ third = _sd_physical_ids(cfn, stack_name)+ assert third["Ns"] != first["Ns"]+ assert third["Svc"] != second["Svc"]+ assert third["Inst"] == "inst-2"+ with pytest.raises(ClientError) as exc:+ sd.get_namespace(Id=first["Ns"])+ assert exc.value.response["Error"]["Code"] == "NamespaceNotFound"+ with pytest.raises(ClientError) as exc:+ r53.get_hosted_zone(Id=old_zone)+ assert exc.value.response["Error"]["Code"] == "NoSuchHostedZone"+ assert sd.get_service(Id=third["Svc"])["Service"]["NamespaceId"] == third["Ns"]+ found = sd.discover_instances(NamespaceName=f"sd{uid}-b.local", ServiceName="api")["Instances"]+ assert [i["InstanceId"] for i in found] == ["inst-2"]++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)+++def test_cfn_servicediscovery_delete_stack(cfn, sd, r53):+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-sd-del-{uid}"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(_sd_stack_template(uid)))+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "CREATE_COMPLETE"+ ids = _sd_physical_ids(cfn, stack_name)+ zone_id = sd.get_namespace(Id=ids["Ns"])["Namespace"]["Properties"]["DnsProperties"]["HostedZoneId"]++ cfn.delete_stack(StackName=stack_name)+ assert _wait_stack(cfn, stack_name)["StackStatus"] == "DELETE_COMPLETE"++ with pytest.raises(ClientError) as exc:+ sd.get_instance(ServiceId=ids["Svc"], InstanceId=ids["Inst"])+ assert exc.value.response["Error"]["Code"] == "InstanceNotFound"+ with pytest.raises(ClientError) as exc:+ sd.get_service(Id=ids["Svc"])+ assert exc.value.response["Error"]["Code"] == "ServiceNotFound"+ with pytest.raises(ClientError) as exc:+ sd.get_namespace(Id=ids["Ns"])+ assert exc.value.response["Error"]["Code"] == "NamespaceNotFound"+ with pytest.raises(ClientError) as exc:+ r53.get_hosted_zone(Id=zone_id)+ assert exc.value.response["Error"]["Code"] == "NoSuchHostedZone"+++def test_cfn_servicediscovery_cdk_ecs_shape(cfn, sd):+ """The shape the CDK ECS constructs emit for a Cloud Map namespace and a+ service with cloudMapOptions (taken from the construct library, not a+ synthesized app): the namespace's Vpc comes from a VPC in the stack and+ the service has no Name."""+ uid = _uuid_mod.uuid4().hex[:8]+ stack_name = f"cfn-sd-cdk-{uid}"+ template = {+ "AWSTemplateFormatVersion": "2010-09-09",+ "Resources": {+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.0.0.0/16"}},+ "ClusterDefaultServiceDiscoveryNamespace": {+ "Type": "AWS::ServiceDiscovery::PrivateDnsNamespace",+ "Properties": {"Name": f"cdk{uid}.local", "Vpc": {"Ref": "Vpc"}},+ },+ "ServiceCloudmapService": {+ "Type": "AWS::ServiceDiscovery::Service",+ "Properties": {+ "DnsConfig": {+ "DnsRecords": [{"TTL": 60, "Type": "A"}],+ "NamespaceId": {"Fn::GetAtt": ["ClusterDefaultServiceDiscoveryNamespace", "Id"]},+ "RoutingPolicy": "MULTIVALUE",+ },+ "HealthCheckCustomConfig": {"FailureThreshold": 1},+ "NamespaceId": {"Fn::GetAtt": ["ClusterDefaultServiceDiscoveryNamespace", "Id"]},+ },+ },+ },+ "Outputs": {+ "SvcName": {"Value": {"Fn::GetAtt": ["ServiceCloudmapService", "Name"]}},+ "SvcArn": {"Value": {"Fn::GetAtt": ["ServiceCloudmapService", "Arn"]}},+ },+ }+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps(template))+ stack = _wait_stack(cfn, stack_name)+ assert stack["StackStatus"] == "CREATE_COMPLETE"+ outputs = {o["OutputKey"]: o["OutputValue"] for o in stack["Outputs"]}+ ids = _sd_physical_ids(cfn, stack_name)++ svc = sd.get_service(Id=ids["ServiceCloudmapService"])["Service"]+ assert svc["Name"] == outputs["SvcName"]+ assert svc["Arn"] == outputs["SvcArn"]+ assert svc["NamespaceId"] == ids["ClusterDefaultServiceDiscoveryNamespace"]+ assert svc["HealthCheckCustomConfig"] == {"FailureThreshold": 1}++ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)++# ---------------------------------------------------------------------------# Update handlers, batch 5: the twelve types of #1601 C1 whose stack update# fell through to the create handler and lost what the resource was holding.diff --git a/tests/test_servicediscovery.py b/tests/test_servicediscovery.pyindex 62b7c5e6..14d394e9 100644--- a/tests/test_servicediscovery.py+++ b/tests/test_servicediscovery.py@@ -340,6 +340,41 @@ def test_servicediscovery_update_public_dns_namespace(sd):sd.delete_namespace(Id=ns_id)+def test_servicediscovery_soa_ttl_create_and_update(sd):+ ns_op = sd.create_private_dns_namespace(+ Name="soa-ttl.example.local",+ Vpc="vpc-12345",+ Properties={"DnsProperties": {"SOA": {"TTL": 100}}},+ )+ ns_id = sd.get_operation(OperationId=ns_op["OperationId"])["Operation"]["Targets"]["NAMESPACE"]+ dns = sd.get_namespace(Id=ns_id)["Namespace"]["Properties"]["DnsProperties"]+ assert dns["SOA"]["TTL"] == 100+ zone_id = dns["HostedZoneId"]++ sd.update_private_dns_namespace(+ Id=ns_id,+ UpdaterRequestId="soa-ttl-1",+ Namespace={"Properties": {"DnsProperties": {"SOA": {"TTL": 60}}}},+ )+ dns = sd.get_namespace(Id=ns_id)["Namespace"]["Properties"]["DnsProperties"]+ assert dns["SOA"]["TTL"] == 60+ assert dns["HostedZoneId"] == zone_id++ sd.delete_namespace(Id=ns_id)+++def test_servicediscovery_delete_namespace_removes_hosted_zone(sd, r53):+ ns_op = sd.create_public_dns_namespace(Name="hz-cleanup.example.com")+ ns_id = sd.get_operation(OperationId=ns_op["OperationId"])["Operation"]["Targets"]["NAMESPACE"]+ zone_id = sd.get_namespace(Id=ns_id)["Namespace"]["Properties"]["DnsProperties"]["HostedZoneId"]+ r53.get_hosted_zone(Id=zone_id)++ sd.delete_namespace(Id=ns_id)++ with pytest.raises(r53.exceptions.NoSuchHostedZone):+ r53.get_hosted_zone(Id=zone_id)++# ---------------------------------------------------------------------------# ARN adoption / tag-API in-process unit tests. Folded from# test_servicediscovery_arn_adoption.py (drive the module directly).