Skip to content

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

feat(cloudformation): execute IMPORT change sets (#1946)

iot-rocket9ac846e88b7b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 060cd41f..1202869a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Added
+- **CloudFormation — `IMPORT` change sets execute** — existing SQS queues, SSM parameters, S3 buckets, DynamoDB tables, IAM roles, log groups, Lambda functions, IoT policies, IoT CA certificates and Cognito user pools are adopted into a new or existing stack without being changed (`IMPORT_IN_PROGRESS` to `IMPORT_COMPLETE`, or a rollback when a resource is gone), and an import that changes `Outputs` or stack tags is refused, as on AWS.
- **CloudFormation — `Capabilities` check without `AUTH`** — `CFN_ENFORCE_CAPABILITIES=1` refuses a template whose IAM resources or macros the request does not acknowledge also without `AUTH=true`, as AWS always does.
### Fixed
diff --git a/ministack/services/cloudformation/changesets.py b/ministack/services/cloudformation/changesets.py
index e061940b..407a5446 100644
--- a/ministack/services/cloudformation/changesets.py
+++ b/ministack/services/cloudformation/changesets.py
@@ -4,10 +4,17 @@
CloudFormation change set handlers — Create, Describe, Execute, Delete, List change sets.
"""
+import asyncio
import copy
+import json
import logging
+import ministack.services.cloudwatch_logs as _cw_logs
+import ministack.services.cognito as _cognito
import ministack.services.dynamodb as _dynamodb
+import ministack.services.iam as _iam
+import ministack.services.iot as _iot
+import ministack.services.lambda_svc as _lambda_svc
import ministack.services.s3 as _s3
import ministack.services.sns as _sns
import ministack.services.sqs as _sqs
@@ -15,11 +22,13 @@ import ministack.services.ssm as _ssm
from ministack.core.responses import get_account_id, get_region, new_uuid, now_iso
from .engine import (
+ _NO_VALUE,
_apply_transforms,
_evaluate_conditions,
_parse_template,
_resolve_parameters,
_resolve_refs,
+ _topological_sort,
validate_template_support,
)
from .helpers import (
@@ -37,6 +46,7 @@ from .helpers import (
stack_name_problems,
validation_error_message,
)
+from .provisioners import _RESOURCE_HANDLERS, _import_resource
from .stacks import (
_add_event,
_create_stack_task_in_region,
@@ -144,18 +154,62 @@ def _parameter_import_problem(name):
return None
+def _role_import_problem(name):
+ if name not in _iam._roles:
+ return _sdk_error(f"The role with name {name} cannot be found.", "Iam", 404)
+ return None
+
+
+def _log_group_import_problem(name):
+ if name not in _cw_logs._log_groups:
+ key = json.dumps({"/properties/LogGroupName": name}, separators=(",", ":"))
+ return _IMPORT_NOT_FOUND.format(type="AWS::Logs::LogGroup", value=key)
+ return None
+
+
+def _function_import_problem(name):
+ if name not in _lambda_svc._functions:
+ arn = f"arn:aws:lambda:{get_region()}:{get_account_id()}:function:{name}"
+ return _sdk_error(f"Function not found: {arn}", "Lambda", 404)
+ return None
+
+
+def _iot_policy_import_problem(name):
+ if name not in _iot._policies:
+ return _IMPORT_NOT_FOUND.format(type="AWS::IoT::Policy", value=name)
+ return None
+
+
+def _ca_certificate_import_problem(ca_id):
+ if ca_id not in _iot._ca_certificates:
+ return _IMPORT_NOT_FOUND.format(type="AWS::IoT::CACertificate", value=ca_id)
+ return None
+
+
+def _user_pool_import_problem(pool_id):
+ if pool_id not in _cognito._user_pools:
+ return _sdk_error(f"User pool {pool_id} does not exist.", "CognitoIdentityProvider", 400)
+ return None
+
+
# The resource types an IMPORT change set looks up before it describes the
# import: the one ResourceIdentifier key AWS expects, and a lookup in this
# emulator's own store that returns the StatusReason of the FAILED change set
-# AWS leaves behind when the identifier is invalid or names nothing (each
-# measured for an existing, a missing, a blank and an empty value). Types not
-# listed are accepted without a lookup.
+# AWS leaves behind when the identifier is invalid or names nothing (measured
+# for a missing value, and for the first five also a blank and an empty one).
+# Types not listed are accepted without a lookup.
_IMPORT_LOOKUPS = {
"AWS::SQS::Queue": ("QueueUrl", _queue_import_problem),
"AWS::SNS::Topic": ("TopicArn", _topic_import_problem),
"AWS::S3::Bucket": ("BucketName", _bucket_import_problem),
"AWS::DynamoDB::Table": ("TableName", _table_import_problem),
"AWS::SSM::Parameter": ("Name", _parameter_import_problem),
+ "AWS::IAM::Role": ("RoleName", _role_import_problem),
+ "AWS::Logs::LogGroup": ("LogGroupName", _log_group_import_problem),
+ "AWS::Lambda::Function": ("FunctionName", _function_import_problem),
+ "AWS::IoT::Policy": ("Id", _iot_policy_import_problem),
+ "AWS::IoT::CACertificate": ("Id", _ca_certificate_import_problem),
+ "AWS::Cognito::UserPool": ("UserPoolId", _user_pool_import_problem),
}
@@ -163,6 +217,15 @@ def _listed(ids):
return "[" + ", ".join(ids) + "]"
+def _tag_dict(tags):
+ return {t.get("Key"): t.get("Value") for t in tags or []}
+
+
+# The StatusReason AWS gives an executable IMPORT change set.
+_IMPORT_REVIEW = ("Verify that resources and their properties defined in the template match "
+ "the intended configuration of the resource import to avoid unexpected changes.")
+
+
def _import_changes(resources_to_import, template, diff):
"""The Import changes of an IMPORT change set.
@@ -518,6 +581,13 @@ def _create_change_set(params):
template, changed_params, retag)
import_failure = None
if cs_type == "IMPORT":
+ previous_tags = {} if new_stack_import else _tag_dict(stack.get("Tags"))
+ frozen = next((name for name, changed in (
+ ("Outputs", template.get("Outputs", {}) != old_template.get("Outputs", {})),
+ ("Tags", tags_given and _tag_dict(tags) != previous_tags),
+ ) if changed), None)
+ if frozen:
+ return _rejected(f"As part of the import operation, you cannot modify or add [{frozen}]")
# An import describes the resources being adopted, not the template
# diff, which would call each of them `Add`; the diff only decides
# what else the template may not do during an import.
@@ -543,8 +613,14 @@ def _create_change_set(params):
# the change set, with no changes, once it looks the resource up.
_cs_status, _cs_exec, _cs_reason = "FAILED", "UNAVAILABLE", import_failure
elif cs_type == "IMPORT":
- _cs_status, _cs_exec = "CREATE_COMPLETE", "UNAVAILABLE"
- _cs_reason = "Resource import is not supported by this emulator"
+ unsupported = sorted({e["ResourceType"] for e in resources_to_import
+ if "import" not in _RESOURCE_HANDLERS.get(e["ResourceType"], {})})
+ if unsupported:
+ _cs_status, _cs_exec = "CREATE_COMPLETE", "UNAVAILABLE"
+ _cs_reason = ("Resource import is not supported by this emulator for "
+ + ", ".join(unsupported))
+ else:
+ _cs_status, _cs_exec, _cs_reason = "CREATE_COMPLETE", "AVAILABLE", _IMPORT_REVIEW
elif changes:
_cs_status, _cs_exec, _cs_reason = "CREATE_COMPLETE", "AVAILABLE", ""
else:
@@ -578,6 +654,7 @@ def _create_change_set(params):
"_template": template,
"_template_body": template_body,
"_resolved_params": param_values,
+ "_resources_to_import": resources_to_import,
}
_change_sets[cs_id] = change_set
@@ -730,15 +807,6 @@ def _execute_change_set(params):
return _error("ChangeSetNotFound",
f"ChangeSet [{cs_name}] does not exist", 404)
- if cs.get("ChangeSetType") == "IMPORT":
- # The ordinary create path would recreate the imported resource and
- # could delete the stack's existing resources when that create fails.
- return _error(
- "InvalidChangeSetStatus",
- f"ChangeSet [{cs_name}] cannot be executed: resource import is not "
- "supported by this emulator.",
- )
-
if cs["ExecutionStatus"] != "AVAILABLE":
return _error("InvalidChangeSetStatus",
f"ChangeSet [{cs_name}] is in {cs['ExecutionStatus']} status")
@@ -772,6 +840,11 @@ def _execute_change_set(params):
tags = cs.get("Tags", [])
cs_type = cs.get("ChangeSetType", "UPDATE")
is_update = cs_type == "UPDATE"
+ if cs_type == "IMPORT":
+ _start_import(cs, stack)
+ _drop_other_change_sets(stack_id, _executed_cs_id)
+ return _xml(200, "ExecuteChangeSetResponse",
+ "<ExecuteChangeSetResult></ExecuteChangeSetResult>")
if is_update:
previous_stack = {
@@ -823,12 +896,7 @@ def _execute_change_set(params):
stack_id,
)
- # Real AWS deletes the stack's other change sets on execute — they are no
- # longer valid for the updated stack. #1418
- from ministack.services.cloudformation import _change_sets as _cs_store
- for _cid in [c for c, v in _cs_store.items()
- if v.get("StackId") == stack_id and c != _executed_cs_id]:
- _cs_store.pop(_cid, None)
+ _drop_other_change_sets(stack_id, _executed_cs_id)
# ExecutionStatus stays EXECUTE_IN_PROGRESS until the deploy finishes, when
# _track_change_set_execution sets EXECUTE_COMPLETE or EXECUTE_FAILED. Status
@@ -839,6 +907,114 @@ def _execute_change_set(params):
"<ExecuteChangeSetResult></ExecuteChangeSetResult>")
+def _drop_other_change_sets(stack_id, executed_cs_id):
+ """Delete the stack's other change sets, as AWS does on execute."""
+ from ministack.services.cloudformation import _change_sets
+ for cid in [c for c, v in _change_sets.items()
+ if v.get("StackId") == stack_id and c != executed_cs_id]:
+ _change_sets.pop(cid, None)
+
+
+def _start_import(cs, stack):
+ """Put the stack into IMPORT_IN_PROGRESS and adopt the change set's resources."""
+ stack_id, stack_name = stack["StackId"], stack["StackName"]
+ new_stack = stack["StackStatus"] == "REVIEW_IN_PROGRESS"
+ stack["StackStatus"] = "IMPORT_IN_PROGRESS"
+ stack["StackStatusReason"] = "User Initiated"
+ stack["LastUpdatedTime"] = now_iso()
+ with _stack_region_context(stack, stack_id):
+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",
+ "IMPORT_IN_PROGRESS", "User Initiated", stack_id)
+ _create_stack_task_in_region(
+ _track_change_set_execution(cs, stack, _import_resources_async(cs, stack, new_stack)),
+ stack, stack_id)
+
+
+async def _import_resources_async(cs, stack, new_stack):
+ """Adopt an IMPORT change set's resources unchanged; one that cannot be read rolls it back."""
+ stack_id, stack_name = stack["StackId"], stack["StackName"]
+ template, param_values = cs["_template"], cs["_resolved_params"]
+ conditions = _evaluate_conditions(template, param_values)
+ definitions = template.get("Resources", {})
+ entries = {e["LogicalResourceId"]: e for e in cs["_resources_to_import"]}
+ order = [lid for lid in _topological_sort(definitions, conditions) if lid in entries]
+ resources = stack.setdefault("_resources", {})
+
+ def event(logical_id, status, reason="", physical_id=""):
+ _add_event(stack_id, stack_name, logical_id, entries[logical_id]["ResourceType"],
+ status, reason, physical_id)
+
+ started, failure = [], None
+ for logical_id in order:
+ entry = entries[logical_id]
+ rtype = entry["ResourceType"]
+ started.append(logical_id)
+ event(logical_id, "IMPORT_IN_PROGRESS", "Resource import started.")
+ failure = _import_not_found([entry])
+ if failure is None:
+ try:
+ physical_id, attrs = _import_resource(rtype, entry["ResourceIdentifier"])
+ props = _resolve_refs(
+ copy.deepcopy(definitions[logical_id].get("Properties", {})), resources,
+ param_values, conditions, template.get("Mappings", {}), stack_name, stack_id)
+ except Exception as exc:
+ logger.error("Failed to import %s (%s): %s", logical_id, rtype, exc)
+ failure = str(exc)
+ if failure is not None:
+ event(logical_id, "IMPORT_FAILED", failure)
+ break
+ event(logical_id, "IMPORT_IN_PROGRESS", physical_id=physical_id)
+ event(logical_id, "IMPORT_COMPLETE", "Resource import completed.", physical_id)
+ resources[logical_id] = {
+ "PhysicalResourceId": physical_id,
+ "ResourceType": rtype,
+ "ResourceStatus": "IMPORT_COMPLETE",
+ "LogicalResourceId": logical_id,
+ "Properties": {k: v for k, v in props.items() if v is not _NO_VALUE},
+ "Attributes": attrs,
+ "Timestamp": now_iso(),
+ }
+ await asyncio.sleep(0)
+
+ if failure is not None:
+ stack["StackStatus"] = "IMPORT_ROLLBACK_IN_PROGRESS"
+ stack["StackStatusReason"] = failure
+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",
+ "IMPORT_ROLLBACK_IN_PROGRESS", failure, stack_id)
+ for logical_id in reversed(started):
+ record = resources.pop(logical_id, None) or {}
+ event(logical_id, "IMPORT_ROLLBACK_IN_PROGRESS",
+ physical_id=record.get("PhysicalResourceId", ""))
+ event(logical_id, "IMPORT_ROLLBACK_COMPLETE",
+ physical_id=record.get("PhysicalResourceId", ""))
+ stack["StackStatus"] = "ROLLBACK_COMPLETE" if new_stack else "IMPORT_ROLLBACK_COMPLETE"
+ stack["StackStatusReason"] = ""
+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",
+ stack["StackStatus"], physical_id=stack_id)
+ return
+
+ for logical_id in order:
+ record = resources[logical_id]
+ event(logical_id, "UPDATE_IN_PROGRESS",
+ "Apply stack-level tags to imported resource if applicable.",
+ record["PhysicalResourceId"])
+ record["ResourceStatus"] = "UPDATE_COMPLETE"
+ event(logical_id, "UPDATE_COMPLETE", physical_id=record["PhysicalResourceId"])
+ stack["_template"] = template
+ stack["_template_body"] = cs["_template_body"]
+ stack["_resolved_params"] = param_values
+ stack["_conditions"] = conditions
+ stack["Capabilities"] = list(cs.get("Capabilities", []))
+ stack["Parameters"] = [
+ {"ParameterKey": k, "ParameterValue": v["Value"], "NoEcho": v["NoEcho"]}
+ for k, v in param_values.items()
+ ]
+ stack["StackStatus"] = "IMPORT_COMPLETE"
+ stack["StackStatusReason"] = ""
+ _add_event(stack_id, stack_name, stack_name, "AWS::CloudFormation::Stack",
+ "IMPORT_COMPLETE", physical_id=stack_id)
+
+
# --- DeleteChangeSet ---
def _delete_change_set(params):
diff --git a/ministack/services/cloudformation/handlers.py b/ministack/services/cloudformation/handlers.py
index beda45bb..e305b3ea 100644
--- a/ministack/services/cloudformation/handlers.py
+++ b/ministack/services/cloudformation/handlers.py
@@ -978,7 +978,8 @@ def _update_stack(params):
current_status = stack.get("StackStatus", "")
if current_status not in ("CREATE_COMPLETE", "UPDATE_COMPLETE",
- "UPDATE_ROLLBACK_COMPLETE"):
+ "UPDATE_ROLLBACK_COMPLETE", "IMPORT_COMPLETE",
+ "IMPORT_ROLLBACK_COMPLETE"):
return _error("ValidationError",
f"Stack [{stack_name}] is in {current_status} state "
f"and cannot be updated")
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 9e3c1829..db5f8387 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -539,6 +539,11 @@ def _provision_resource(resource_type: str, logical_id: str, props: dict,
raise ValueError(f"Unsupported resource type: {resource_type}")
+def _import_resource(resource_type: str, identifier: dict) -> tuple:
+ """Adopt an existing resource by its ResourceIdentifier. Returns (physical_id, attributes)."""
+ return _RESOURCE_HANDLERS[resource_type]["import"](identifier)
+
+
def _snapshot_id(physical_id: str) -> str:
"""Name for a `DeletionPolicy: Snapshot` snapshot. AWS generates one too;
its format is not documented, so this is the emulator's."""
@@ -1365,6 +1370,15 @@ def _s3_mrap_delete(physical_id, props):
_s3._mraps.pop(alias, None)
+def _s3_attrs(name):
+ return {
+ "Arn": f"arn:aws:s3:::{name}",
+ "DomainName": f"{name}.s3.amazonaws.com",
+ "RegionalDomainName": f"{name}.s3.{get_region()}.amazonaws.com",
+ "WebsiteURL": f"http://{name}.s3-website-{get_region()}.amazonaws.com",
+ }
+
+
def _s3_create(logical_id, props, stack_name):
name = props.get("BucketName") or _physical_name(stack_name, logical_id, lowercase=True, max_len=63)
_s3._buckets.setdefault(name, {
@@ -1377,13 +1391,7 @@ def _s3_create(logical_id, props, stack_name):
_s3._bucket_versioning[name] = "Enabled"
if "NotificationConfiguration" in props:
_s3_apply_notification(name, props["NotificationConfiguration"])
- attrs = {
- "Arn": f"arn:aws:s3:::{name}",
- "DomainName": f"{name}.s3.amazonaws.com",
- "RegionalDomainName": f"{name}.s3.{get_region()}.amazonaws.com",
- "WebsiteURL": f"http://{name}.s3-website-{get_region()}.amazonaws.com",
- }
- return name, attrs
+ return name, _s3_attrs(name)
def _s3_update(physical_id, old_props, new_props, stack_name):
@@ -1408,13 +1416,7 @@ def _s3_update(physical_id, old_props, new_props, stack_name):
_s3._bucket_notifications.pop(name, None)
else:
return _s3_create(name, new_props, stack_name)
- attrs = {
- "Arn": f"arn:aws:s3:::{name}",
- "DomainName": f"{name}.s3.amazonaws.com",
- "RegionalDomainName": f"{name}.s3.{get_region()}.amazonaws.com",
- "WebsiteURL": f"http://{name}.s3-website-{get_region()}.amazonaws.com",
- }
- return name, attrs
+ return name, _s3_attrs(name)
def _s3_bucket_policy_create(logical_id, props, stack_name):
@@ -1439,6 +1441,10 @@ def _s3_bucket_policy_delete(physical_id, props):
_s3._bucket_policies.pop(bucket, None)
+def _s3_import(identifier):
+ return identifier["BucketName"], _s3_attrs(identifier["BucketName"])
+
+
def _s3_delete(physical_id, props):
_s3._buckets.pop(physical_id, None)
_s3._bucket_versioning.pop(physical_id, None)
@@ -1523,7 +1529,12 @@ def _sqs_create(logical_id, props, stack_name):
}
_sqs._queues[url] = queue
_sqs._queue_name_to_url[name] = url
- return url, {"Arn": arn, "QueueName": name, "QueueUrl": url}
+ return url, _sqs_attrs(queue)
+
+
+def _sqs_attrs(queue):
+ return {"Arn": queue["attributes"]["QueueArn"], "QueueName": queue["name"],
+ "QueueUrl": queue["url"]}
def _sqs_update(physical_id, old_props, new_props, stack_name, logical_id=None):
@@ -1550,8 +1561,12 @@ def _sqs_update(physical_id, old_props, new_props, stack_name, logical_id=None):
attributes.update(fields)
_reconcile_tag_map(queue.setdefault("tags", {}), old_props, new_props)
attributes["LastModifiedTimestamp"] = str(int(time.time()))
- arn = attributes["QueueArn"]
- return physical_id, {"Arn": arn, "QueueName": name, "QueueUrl": physical_id}
+ return physical_id, _sqs_attrs(queue)
+
+
+def _sqs_import(identifier):
+ queue = _sqs._get_q(identifier["QueueUrl"])
+ return queue["url"], _sqs_attrs(queue)
def _sqs_delete(physical_id, props):
@@ -1963,10 +1978,19 @@ def _ddb_update(physical_id, old_props, new_props, stack_name, logical_id=None):
"GlobalSecondaryIndexUpdates": [{"Create": new_gsis[idx_name]}],
})
+ return name, _ddb_attrs(table)
+
+
+def _ddb_attrs(table):
attrs = {"Arn": table["TableArn"]}
if table.get("LatestStreamArn") and (table.get("StreamSpecification") or {}).get("StreamEnabled"):
attrs["StreamArn"] = table["LatestStreamArn"]
- return name, attrs
+ return attrs
+
+
+def _ddb_import(identifier):
+ name = identifier["TableName"]
+ return name, _ddb_attrs(_dynamodb._tables[name])
def _ddb_global_table_create(logical_id, props, stack_name):
@@ -2225,6 +2249,11 @@ def _lambda_update(physical_id, old_props, new_props, stack_name, logical_id=Non
return name, {"Arn": func["config"]["FunctionArn"]}
+def _lambda_import(identifier):
+ name = identifier["FunctionName"]
+ return name, {"Arn": _lambda_svc._functions[name]["config"]["FunctionArn"]}
+
+
def _lambda_delete(physical_id, props):
_lambda_svc._functions.pop(physical_id, None)
# The function may have held the last reference to a deleted layer version.
@@ -2409,6 +2438,12 @@ def _iam_role_update(physical_id, old_props, new_props, stack_name, logical_id=N
return name, {"Arn": role["Arn"], "RoleId": role["RoleId"]}
+def _iam_role_import(identifier):
+ name = identifier["RoleName"]
+ role = _iam._roles[name]
+ return name, {"Arn": role["Arn"], "RoleId": role["RoleId"]}
+
+
def _iam_role_delete(physical_id, props):
role = _iam._roles.pop(physical_id, None)
if role:
@@ -2785,6 +2820,11 @@ def _ssm_update(physical_id, old_props, new_props, stack_name):
return physical_id, _ssm_attrs(physical_id, data)
+def _ssm_import(identifier):
+ name = identifier["Name"]
+ return name, _ssm_attrs(name, _ssm._lookup_parameter(name)[1])
+
+
def _ssm_delete(physical_id, props):
# Delete through the SSM path (not a bare store pop) so history and tags are
# cleaned too; a missing parameter is a no-op, so repeated/post-reset deletes
@@ -3181,6 +3221,11 @@ def _cwlogs_update(physical_id, old_props, new_props, stack_name, logical_id=Non
return name, {"Arn": group["arn"]}
+def _cwlogs_import(identifier):
+ name = identifier["LogGroupName"]
+ return name, {"Arn": _cw_logs._log_groups[name]["arn"]}
+
+
def _cwlogs_delete(physical_id, props):
_cw_logs._log_groups.pop(physical_id, None)
@@ -6493,6 +6538,11 @@ def _cognito_user_pool_update(physical_id, old_props, new_props, stack_name,
return physical_id, _cognito_user_pool_attributes(physical_id)
+def _cognito_user_pool_import(identifier):
+ pool_id = identifier["UserPoolId"]
+ return pool_id, _cognito_user_pool_attributes(pool_id)
+
+
def _cognito_user_pool_delete(physical_id, props):
pool = _cognito._user_pools.pop(physical_id, None)
if pool and pool.get("Domain"):
@@ -12220,6 +12270,11 @@ def _iot_policy_update(physical_id, old_props, new_props, stack_name, logical_id
return name, {"Arn": _iot._policy_arn(name), "Id": name}
+def _iot_policy_import(identifier):
+ name = identifier["Id"]
+ return name, {"Arn": _iot._policy_arn(name), "Id": name}
+
+
def _iot_policy_delete(physical_id, props):
_iot._policies.pop(physical_id, None)
@@ -12443,6 +12498,11 @@ def _iot_ca_certificate_update(physical_id, old_props, new_props, stack_name):
return _iot_ca_certificate_apply(physical_id, new_props)
+def _iot_ca_certificate_import(identifier):
+ ca_id = identifier["Id"]
+ return ca_id, {"Arn": _iot._ca_cert_arn(ca_id), "Id": ca_id}
+
+
def _iot_ca_certificate_delete(physical_id, props):
if physical_id not in _iot._ca_certificates:
return
@@ -12885,7 +12945,9 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _opensearch_domain_delete,
},
- "AWS::S3::Bucket": {"create": _s3_create, "update": _s3_update, "delete": _s3_delete},
+ "AWS::S3::Bucket": {
+ "create": _s3_create, "update": _s3_update, "delete": _s3_delete, "import": _s3_import,
+ },
"AWS::S3::MultiRegionAccessPoint": {
"create": _s3_mrap_create,
"update": _replacing_update(_s3_mrap_create, _s3_mrap_delete),
@@ -12992,6 +13054,7 @@ _RESOURCE_HANDLERS = {
"update": _sqs_update,
"update_with_logical_id": True,
"delete": _sqs_delete,
+ "import": _sqs_import,
},
"AWS::SNS::Topic": {
"create": _sns_create,
@@ -13010,6 +13073,7 @@ _RESOURCE_HANDLERS = {
"update": _ddb_update,
"update_with_logical_id": True,
"delete": _ddb_delete,
+ "import": _ddb_import,
},
# CDK TableV2 emits AWS::DynamoDB::GlobalTable, even for single-region
# tables. The schema differs from Table (no ProvisionedThroughput; capacity
@@ -13022,6 +13086,7 @@ _RESOURCE_HANDLERS = {
"update": _lambda_update,
"update_with_logical_id": True,
"delete": _lambda_delete,
+ "import": _lambda_import,
},
"AWS::Lambda::Url": {
"create": _lambda_url_create,
@@ -13033,6 +13098,7 @@ _RESOURCE_HANDLERS = {
"update": _iam_role_update,
"update_with_logical_id": True,
"delete": _iam_role_delete,
+ "import": _iam_role_import,
},
"AWS::IAM::Policy": {
"create": _iam_policy_create,
@@ -13046,7 +13112,9 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _iam_ip_delete,
},
- "AWS::SSM::Parameter": {"create": _ssm_create, "update": _ssm_update, "delete": _ssm_delete},
+ "AWS::SSM::Parameter": {
+ "create": _ssm_create, "update": _ssm_update, "delete": _ssm_delete, "import": _ssm_import,
+ },
"AWS::AppConfig::Application": {
"create": _appconfig_application_create,
"update": _appconfig_application_update,
@@ -13085,6 +13153,7 @@ _RESOURCE_HANDLERS = {
"update": _cwlogs_update,
"update_with_logical_id": True,
"delete": _cwlogs_delete,
+ "import": _cwlogs_import,
},
"AWS::Logs::ResourcePolicy": {
"create": _cwlogs_resource_policy_create,
@@ -13281,6 +13350,7 @@ _RESOURCE_HANDLERS = {
"update": _cognito_user_pool_update,
"update_with_logical_id": True,
"delete": _cognito_user_pool_delete,
+ "import": _cognito_user_pool_import,
},
"AWS::Cognito::UserPoolClient": {
"create": _cognito_user_pool_client_create,
@@ -13586,6 +13656,7 @@ _RESOURCE_HANDLERS = {
"update": _iot_policy_update,
"update_with_logical_id": True,
"delete": _iot_policy_delete,
+ "import": _iot_policy_import,
},
"AWS::IoT::ProvisioningTemplate": {
"create": _iot_provisioning_template_create,
@@ -13597,6 +13668,7 @@ _RESOURCE_HANDLERS = {
"create": _iot_ca_certificate_create,
"update": _iot_ca_certificate_update,
"delete": _iot_ca_certificate_delete,
+ "import": _iot_ca_certificate_import,
},
"AWS::Cognito::IdentityPoolRoleAttachment": {
"create": _cognito_identity_pool_role_attachment_create,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 5dba7d90..7987e6c6 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -30034,6 +30034,343 @@ def test_cfn_update_rollback_does_not_resend_a_refused_resource_update(cfn):
_delete_cfn_test_stack(cfn, stack_name)
+# --- resource import (ChangeSetType=IMPORT) ---
+
+_IMPORT_REVIEW = ("Verify that resources and their properties defined in the template match "
+ "the intended configuration of the resource import to avoid unexpected changes.")
+_TAG_PHASE = "Apply stack-level tags to imported resource if applicable."
+
+
+def _cfn_import(cfn, stack, resources, to_import, template=None, **extra):
+ """Create an IMPORT change set and return its description."""
+ cs_id = cfn.create_change_set(
+ StackName=stack, ChangeSetName="imp", ChangeSetType="IMPORT",
+ TemplateBody=json.dumps({**(template or {}), "Resources": resources}), ResourcesToImport=to_import,
+ Capabilities=["CAPABILITY_NAMED_IAM"], **extra)["Id"]
+ return cfn.describe_change_set(ChangeSetName=cs_id)
+
+
+def _cfn_execute_import(cfn, stack):
+ """Execute the IMPORT change set; return the final stack and the events it added."""
+ before = len(cfn.describe_stack_events(StackName=stack)["StackEvents"])
+ cfn.execute_change_set(StackName=stack, ChangeSetName="imp")
+ final = _wait_stack(cfn, stack)
+ events = cfn.describe_stack_events(StackName=stack)["StackEvents"]
+ return final, [(e["LogicalResourceId"], e["ResourceStatus"], e.get("ResourceStatusReason", ""))
+ for e in reversed(events[:len(events) - before])]
+
+
+def _cfn_queue_import(qname, url):
+ return ({"Type": "AWS::SQS::Queue", "DeletionPolicy": "Retain", "Properties": {"QueueName": qname}},
+ [{"ResourceType": "AWS::SQS::Queue", "LogicalResourceId": "Q",
+ "ResourceIdentifier": {"QueueUrl": url}}])
+
+
+def test_cfn_import_adopts_a_queue_into_a_new_stack(cfn, sqs):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, qname = f"cfn-imp-new-{uid}", f"cfn-imp-new-{uid}"
+ url = sqs.create_queue(QueueName=qname, Attributes={"VisibilityTimeout": "17"})["QueueUrl"]
+ sqs.send_message(QueueUrl=url, MessageBody="kept")
+ declared, to_import = _cfn_queue_import(qname, url)
+ try:
+ cs = _cfn_import(cfn, stack, {"Q": declared}, to_import)
+ assert (cs["Status"], cs["ExecutionStatus"], cs["StatusReason"]) == (
+ "CREATE_COMPLETE", "AVAILABLE", _IMPORT_REVIEW)
+ final, events = _cfn_execute_import(cfn, stack)
+ assert final["StackStatus"] == "IMPORT_COMPLETE"
+ assert events == [
+ (stack, "IMPORT_IN_PROGRESS", "User Initiated"),
+ ("Q", "IMPORT_IN_PROGRESS", "Resource import started."),
+ ("Q", "IMPORT_IN_PROGRESS", ""),
+ ("Q", "IMPORT_COMPLETE", "Resource import completed."),
+ ("Q", "UPDATE_IN_PROGRESS", _TAG_PHASE),
+ ("Q", "UPDATE_COMPLETE", ""),
+ (stack, "IMPORT_COMPLETE", ""),
+ ]
+ resource = cfn.describe_stack_resource(StackName=stack, LogicalResourceId="Q")
+ assert resource["StackResourceDetail"]["ResourceStatus"] == "UPDATE_COMPLETE"
+ assert resource["StackResourceDetail"]["PhysicalResourceId"] == url
+ assert list(cfn.get_template(StackName=stack)["TemplateBody"]["Resources"]) == ["Q"]
+ attrs = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["VisibilityTimeout"])["Attributes"]
+ assert attrs["VisibilityTimeout"] == "17"
+ # Outputs cannot come with the import; a later update reads them off the live queue.
+ cfn.update_stack(StackName=stack, TemplateBody=json.dumps({
+ "Resources": {"Q": declared},
+ "Outputs": {"Ref": {"Value": {"Ref": "Q"}},
+ "Arn": {"Value": {"Fn::GetAtt": ["Q", "Arn"]}}}}))
+ final = _wait_stack(cfn, stack)
+ assert final["StackStatus"] == "UPDATE_COMPLETE", final.get("StackStatusReason")
+ outputs = {o["OutputKey"]: o["OutputValue"] for o in final["Outputs"]}
+ arn = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ assert outputs == {"Ref": url, "Arn": arn}
+ _delete_cfn_test_stack(cfn, stack)
+ assert sqs.receive_message(QueueUrl=url)["Messages"][0]["Body"] == "kept"
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ sqs.delete_queue(QueueUrl=url)
+
+
+def test_cfn_import_into_an_existing_stack_leaves_its_resources_alone(cfn, sqs, ssm):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, qname, pname = f"cfn-imp-old-{uid}", f"cfn-imp-old-{uid}", f"/cfn-imp-old/{uid}"
+ url = sqs.create_queue(QueueName=qname)["QueueUrl"]
+ x = {"Type": "AWS::SSM::Parameter", "Properties": {"Name": pname, "Type": "String", "Value": "v"}}
+ try:
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({"Resources": {"X": x}}))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"
+ declared, to_import = _cfn_queue_import(qname, url)
+ _cfn_import(cfn, stack, {"X": x, "Q": declared}, to_import)
+ assert cfn.describe_stacks(StackName=stack)["Stacks"][0]["StackStatus"] == "CREATE_COMPLETE"
+ final, events = _cfn_execute_import(cfn, stack)
+ assert final["StackStatus"] == "IMPORT_COMPLETE"
+ assert [e for e in events if e[0] == "X"] == []
+ assert ssm.get_parameter(Name=pname)["Parameter"]["Version"] == 1
+ statuses = {r["LogicalResourceId"]: r["ResourceStatus"]
+ for r in cfn.describe_stack_resources(StackName=stack)["StackResources"]}
+ assert statuses == {"X": "CREATE_COMPLETE", "Q": "UPDATE_COMPLETE"}
+ # The imported queue is an ordinary stack resource from here on.
+ declared["Properties"]["VisibilityTimeout"] = 45
+ cfn.update_stack(StackName=stack, TemplateBody=json.dumps({"Resources": {"X": x, "Q": declared}}))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "UPDATE_COMPLETE"
+ attrs = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["VisibilityTimeout"])["Attributes"]
+ assert attrs["VisibilityTimeout"] == "45"
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ sqs.delete_queue(QueueUrl=url)
+
+
[email protected]("new_stack", [False, True])
+def test_cfn_import_rolls_back_when_the_resource_is_gone(cfn, sqs, new_stack):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, qname = f"cfn-imp-gone-{uid}", f"cfn-imp-gone-{uid}"
+ url = sqs.create_queue(QueueName=qname)["QueueUrl"]
+ x = {"Type": "AWS::SQS::Queue"}
+ params = {"Parameters": {"V": {"Type": "String", "Default": "a"}}}
+ try:
+ resources, extra = {}, {}
+ if not new_stack:
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps({**params, "Resources": {"X": x}}))
+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"
+ resources["X"] = x
+ extra = {"template": params, "Parameters": [{"ParameterKey": "V", "ParameterValue": "b"}]}
+ declared, to_import = _cfn_queue_import(qname, url)
+ _cfn_import(cfn, stack, {**resources, "Q": declared}, to_import, **extra)
+ sqs.delete_queue(QueueUrl=url)
+ final, events = _cfn_execute_import(cfn, stack)
+ reason = f"Resource of type 'AWS::SQS::Queue' with identifier '{url}' was not found."
+ status = "ROLLBACK_COMPLETE" if new_stack else "IMPORT_ROLLBACK_COMPLETE"
+ assert final["StackStatus"] == status
+ assert events == [
+ (stack, "IMPORT_IN_PROGRESS", "User Initiated"),
+ ("Q", "IMPORT_IN_PROGRESS", "Resource import started."),
+ ("Q", "IMPORT_FAILED", reason),
+ (stack, "IMPORT_ROLLBACK_IN_PROGRESS", reason),
+ ("Q", "IMPORT_ROLLBACK_IN_PROGRESS", ""),
+ ("Q", "IMPORT_ROLLBACK_COMPLETE", ""),
+ (stack, status, ""),
+ ]
+ assert [r["LogicalResourceId"] for r in cfn.describe_stack_resources(
+ StackName=stack)["StackResources"]] == list(resources)
+ if not new_stack:
+ assert final["Parameters"] == [{"ParameterKey": "V", "ParameterValue": "a"}]
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+
+
[email protected]("change", ["new-outputs", "new-tags", "dropped-output", "changed-tags"])
+def test_cfn_import_refuses_outputs_and_tags_changes(cfn, sqs, change):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, qname = f"cfn-imp-frozen-{uid}", f"cfn-imp-frozen-{uid}"
+ url = sqs.create_queue(QueueName=qname)["QueueUrl"]
+ declared, to_import = _cfn_queue_import(qname, url)
+ output = {"O": {"Value": "x"}}
+ tags = [{"Key": "team", "Value": "a"}]
+ try:
+ if change.startswith("new"):
+ body = {"Resources": {"Q": declared}}
+ else:
+ base = {"Resources": {"X": {"Type": "AWS::SQS::Queue"}}, "Outputs": output}
+ cfn.create_stack(StackName=stack, TemplateBody=json.dumps(base), Tags=tags)
+ assert _wait_stack(cfn, stack)["StackStatus"] == "CREATE_COMPLETE"
+ body = {**base, "Resources": {**base["Resources"], "Q": declared}}
+ extra = {}
+ if change == "new-outputs":
+ body["Outputs"] = output
+ elif change == "new-tags":
+ extra["Tags"] = tags
+ elif change == "dropped-output":
+ del body["Outputs"]
+ else:
+ # The stack's own tags are accepted again, a different set is not.
+ cfn.create_change_set(
+ StackName=stack, ChangeSetName="same", ChangeSetType="IMPORT", Tags=tags,
+ TemplateBody=json.dumps(body), ResourcesToImport=to_import)
+ extra["Tags"] = [{"Key": "team", "Value": "b"}]
+ with pytest.raises(ClientError) as exc:
+ cfn.create_change_set(StackName=stack, ChangeSetName="imp", ChangeSetType="IMPORT",
+ TemplateBody=json.dumps(body), ResourcesToImport=to_import, **extra)
+ section = "Tags" if change.endswith("tags") else "Outputs"
+ assert exc.value.response["Error"]["Message"] == (
+ f"As part of the import operation, you cannot modify or add [{section}]")
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ sqs.delete_queue(QueueUrl=url)
+
+
+def test_cfn_import_adopts_each_supported_type(cfn, sqs, ssm, s3, ddb, iam, logs, lam, iot_client,
+ cognito_idp):
+ pytest.importorskip("cryptography")
+ from ministack.core.x509_utils import generate_ca
+
+ uid = _uuid_mod.uuid4().hex[:8]
+ name, stack = f"cfn-imp-all-{uid}", f"cfn-imp-all-{uid}"
+ trust = {"Version": "2012-10-17", "Statement": [{
+ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}
+ document = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "iot:Connect",
+ "Resource": "*"}]}
+ ca_pem, _key = generate_ca(common_name=name)
+ url = sqs.create_queue(QueueName=name)["QueueUrl"]
+ ssm.put_parameter(Name=name, Value="v1", Type="String")
+ s3.create_bucket(Bucket=name)
+ ddb.create_table(TableName=name, BillingMode="PAY_PER_REQUEST",
+ KeySchema=[{"AttributeName": "k", "KeyType": "HASH"}],
+ AttributeDefinitions=[{"AttributeName": "k", "AttributeType": "S"}])
+ role = iam.create_role(RoleName=name, AssumeRolePolicyDocument=json.dumps(trust))["Role"]
+ logs.create_log_group(logGroupName=name)
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("index.py", "def handler(e, c):\n return e\n")
+ fn_arn = lam.create_function(FunctionName=name, Runtime="python3.12", Role=role["Arn"],
+ Handler="index.handler", Code={"ZipFile": buf.getvalue()})["FunctionArn"]
+ policy_arn = iot_client.create_policy(policyName=name, policyDocument=json.dumps(document))["policyArn"]
+ ca = iot_client.register_ca_certificate(caCertificate=ca_pem, certificateMode="SNI_ONLY",
+ setAsActive=True)
+ pool = cognito_idp.create_user_pool(PoolName=name)["UserPool"]
+ table_arn = ddb.describe_table(TableName=name)["Table"]["TableArn"]
+ queue_arn = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
+ log_arn = logs.describe_log_groups(logGroupNamePrefix=name)["logGroups"][0]["arn"]
+ # (type, identifier, properties, {attribute: live value}); Ref is the identifier.
+ cases = {
+ "Q": ("AWS::SQS::Queue", {"QueueUrl": url}, {"QueueName": name}, {"Arn": queue_arn, "QueueName": name}),
+ "P": ("AWS::SSM::Parameter", {"Name": name}, {"Name": name, "Type": "String", "Value": "v1"},
+ {"Type": "String", "Value": "v1"}),
+ "B": ("AWS::S3::Bucket", {"BucketName": name}, {"BucketName": name}, {"Arn": f"arn:aws:s3:::{name}"}),
+ "T": ("AWS::DynamoDB::Table", {"TableName": name}, {
+ "TableName": name, "BillingMode": "PAY_PER_REQUEST",
+ "KeySchema": [{"AttributeName": "k", "KeyType": "HASH"}],
+ "AttributeDefinitions": [{"AttributeName": "k", "AttributeType": "S"}]}, {"Arn": table_arn}),
+ "R": ("AWS::IAM::Role", {"RoleName": name}, {"RoleName": name, "AssumeRolePolicyDocument": trust},
+ {"Arn": role["Arn"], "RoleId": role["RoleId"]}),
+ "L": ("AWS::Logs::LogGroup", {"LogGroupName": name}, {"LogGroupName": name}, {"Arn": log_arn}),
+ "F": ("AWS::Lambda::Function", {"FunctionName": name}, {
+ "FunctionName": name, "Runtime": "python3.12", "Handler": "index.handler", "Role": role["Arn"],
+ "Code": {"ZipFile": "def handler(e, c):\n return e\n"}}, {"Arn": fn_arn}),
+ "IP": ("AWS::IoT::Policy", {"Id": name}, {"PolicyName": name, "PolicyDocument": document},
+ {"Arn": policy_arn, "Id": name}),
+ "CA": ("AWS::IoT::CACertificate", {"Id": ca["certificateId"]}, {
+ "CACertificatePem": ca_pem, "Status": "ACTIVE", "CertificateMode": "SNI_ONLY"},
+ {"Arn": ca["certificateArn"], "Id": ca["certificateId"]}),
+ "UP": ("AWS::Cognito::UserPool", {"UserPoolId": pool["Id"]}, {"UserPoolName": name},
+ {"Arn": pool["Arn"], "UserPoolId": pool["Id"]}),
+ }
+ resources = {lid: {"Type": t, "DeletionPolicy": "Retain", "Properties": props}
+ for lid, (t, _ident, props, _attrs) in cases.items()}
+ to_import = [{"ResourceType": t, "LogicalResourceId": lid, "ResourceIdentifier": ident}
+ for lid, (t, ident, _props, _attrs) in cases.items()]
+ try:
+ cs = _cfn_import(cfn, stack, resources, to_import)
+ assert cs["ExecutionStatus"] == "AVAILABLE", cs["StatusReason"]
+ assert [c["ResourceChange"]["Action"] for c in cs["Changes"]] == ["Import"] * len(cases)
+ final, _events = _cfn_execute_import(cfn, stack)
+ assert final["StackStatus"] == "IMPORT_COMPLETE", final.get("StackStatusReason")
+ physical = {r["LogicalResourceId"]: r["PhysicalResourceId"]
+ for r in cfn.describe_stack_resources(StackName=stack)["StackResources"]}
+ assert physical == {lid: next(iter(ident.values())) for lid, (_t, ident, _p, _a) in cases.items()}
+ outputs = {f"{lid}Ref": {"Value": {"Ref": lid}} for lid in cases}
+ outputs.update({f"{lid}{attr}": {"Value": {"Fn::GetAtt": [lid, attr]}}
+ for lid, (_t, _i, _p, attrs) in cases.items() for attr in attrs})
+ cfn.update_stack(StackName=stack, TemplateBody=json.dumps({"Resources": resources, "Outputs": outputs}),
+ Capabilities=["CAPABILITY_NAMED_IAM"])
+ final = _wait_stack(cfn, stack)
+ assert final["StackStatus"] == "UPDATE_COMPLETE", final.get("StackStatusReason")
+ expected = {f"{lid}Ref": v for lid, v in physical.items()}
+ expected.update({f"{lid}{attr}": value
+ for lid, (_t, _i, _p, attrs) in cases.items() for attr, value in attrs.items()})
+ assert {o["OutputKey"]: o["OutputValue"] for o in final["Outputs"]} == expected
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ sqs.delete_queue(QueueUrl=url)
+ ssm.delete_parameter(Name=name)
+ s3.delete_bucket(Bucket=name)
+ ddb.delete_table(TableName=name)
+ lam.delete_function(FunctionName=name)
+ iam.delete_role(RoleName=name)
+ logs.delete_log_group(logGroupName=name)
+ iot_client.delete_policy(policyName=name)
+ iot_client.update_ca_certificate(certificateId=ca["certificateId"], newStatus="INACTIVE")
+ iot_client.delete_ca_certificate(certificateId=ca["certificateId"])
+ cognito_idp.delete_user_pool(UserPoolId=pool["Id"])
+
+
+# AWS's StatusReason for an identifier that names nothing, per type.
+_CFN_IMPORT_MISSING = {
+ "AWS::IAM::Role": (
+ "RoleName",
+ r"The role with name {v} cannot be found\. \(Service: Iam, Status Code: 404, "
+ r"Request ID: [0-9a-f-]+\) \(SDK Attempt Count: 1\)"),
+ "AWS::Logs::LogGroup": (
+ "LogGroupName",
+ r"Resource of type 'AWS::Logs::LogGroup' with identifier "
+ r"'\{{\"/properties/LogGroupName\":\"{v}\"\}}' was not found\."),
+ "AWS::Lambda::Function": (
+ "FunctionName",
+ r"Function not found: arn:aws:lambda:[a-z0-9-]+:\d{{12}}:function:{v} \(Service: Lambda, "
+ r"Status Code: 404, Request ID: [0-9a-f-]+\) \(SDK Attempt Count: 1\)"),
+ "AWS::IoT::Policy": (
+ "Id", r"Resource of type 'AWS::IoT::Policy' with identifier '{v}' was not found\."),
+ "AWS::IoT::CACertificate": (
+ "Id", r"Resource of type 'AWS::IoT::CACertificate' with identifier '{v}' was not found\."),
+ "AWS::Cognito::UserPool": (
+ "UserPoolId",
+ r"User pool {v} does not exist\. \(Service: CognitoIdentityProvider, Status Code: 400, "
+ r"Request ID: [0-9a-f-]+\) \(SDK Attempt Count: 1\)"),
+}
+
+
[email protected]("rtype", list(_CFN_IMPORT_MISSING))
+def test_cfn_import_of_a_missing_resource_fails_the_change_set(cfn, rtype):
+ key, missing = _CFN_IMPORT_MISSING[rtype]
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, value = f"cfn-imp-missing-{uid}", f"cfn-imp-missing-{uid}"
+ try:
+ cs = _cfn_import(cfn, stack, {"R": {"Type": rtype, "DeletionPolicy": "Retain"}},
+ [{"ResourceType": rtype, "LogicalResourceId": "R", "ResourceIdentifier": {key: value}}])
+ assert (cs["Status"], cs["ExecutionStatus"], cs["Changes"]) == ("FAILED", "UNAVAILABLE", [])
+ assert re.fullmatch(missing.format(v=re.escape(value)), cs["StatusReason"]), cs["StatusReason"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+
+
+def test_cfn_import_of_a_type_without_an_adopter_is_not_executable(cfn, eb):
+ uid = _uuid_mod.uuid4().hex[:8]
+ stack, bus = f"cfn-imp-bus-{uid}", f"cfn-imp-bus-{uid}"
+ eb.create_event_bus(Name=bus)
+ try:
+ cs = _cfn_import(cfn, stack, {"B": {"Type": "AWS::Events::EventBus", "DeletionPolicy": "Retain",
+ "Properties": {"Name": bus}}},
+ [{"ResourceType": "AWS::Events::EventBus", "LogicalResourceId": "B",
+ "ResourceIdentifier": {"Name": bus}}])
+ assert (cs["Status"], cs["ExecutionStatus"], cs["StatusReason"]) == (
+ "CREATE_COMPLETE", "UNAVAILABLE",
+ "Resource import is not supported by this emulator for AWS::Events::EventBus")
+ with pytest.raises(ClientError) as exc:
+ cfn.execute_change_set(StackName=stack, ChangeSetName="imp")
+ assert exc.value.response["Error"]["Code"] == "InvalidChangeSetStatus"
+ finally:
+ _delete_cfn_test_stack(cfn, stack)
+ eb.delete_event_bus(Name=bus)
+
+
# ---------------------------------------------------------------------------
# OnFailure, OnStackFailure, DeletionMode, TemplateStage, ClientRequestToken
# ---------------------------------------------------------------------------
diff --git a/tests/test_cfn_import_change_set.py b/tests/test_cfn_import_change_set.py
index 846780ef..053fd573 100644
--- a/tests/test_cfn_import_change_set.py
+++ b/tests/test_cfn_import_change_set.py
@@ -1,6 +1,5 @@
"""IMPORT change sets: what CreateChangeSet refuses or fails, the shape of an
-Import change, and that the unsupported execution leaves stack and service
-state intact.
+Import change, and that executing one leaves stack and service state intact.
Every expected message is the one AWS answers for the same request.
"""
@@ -167,12 +166,10 @@ def _import_of(kind, value):
# --- accepted imports ---
-def test_import_change_set_describes_only_imports_and_is_unavailable(cfn, adopted):
+def test_import_change_set_describes_only_imports_and_is_available(cfn, adopted):
cs = _create(cfn, adopted)
- assert cs["Status"] == "CREATE_COMPLETE"
- # AWS answers AVAILABLE and executes the import; the emulator refuses it by design.
- assert cs["ExecutionStatus"] == "UNAVAILABLE"
- assert "import" in cs["StatusReason"].lower()
+ assert (cs["Status"], cs["ExecutionStatus"]) == ("CREATE_COMPLETE", "AVAILABLE")
+ assert cs["StatusReason"].startswith("Verify that resources and their properties")
assert [(r["Type"], r["ResourceChange"]["LogicalResourceId"], r["ResourceChange"]["Action"],
r["ResourceChange"]["ResourceType"]) for r in cs["Changes"]] == [
("Resource", "Q", "Import", "AWS::SQS::Queue")]
@@ -563,8 +560,7 @@ def test_import_into_a_new_stack_creates_it_for_review(cfn, fresh):
cs_id = cfn.create_change_set(StackName=stack, ChangeSetName="imp", ChangeSetType="IMPORT",
ResourcesToImport=to_import, TemplateBody=body)["Id"]
cs = cfn.describe_change_set(ChangeSetName=cs_id)
- # AWS answers AVAILABLE and executes the import; the emulator refuses it by design.
- assert (cs["Status"], cs["ExecutionStatus"]) == ("CREATE_COMPLETE", "UNAVAILABLE")
+ assert (cs["Status"], cs["ExecutionStatus"]) == ("CREATE_COMPLETE", "AVAILABLE")
assert cs["Changes"] == [{"Type": "Resource", "ResourceChange": {
"Action": "Import", "LogicalResourceId": "Q", "PhysicalResourceId": url,
"ResourceType": "AWS::SQS::Queue", "Scope": [], "Details": []}}]
@@ -574,10 +570,6 @@ def test_import_into_a_new_stack_creates_it_for_review(cfn, fresh):
assert [(e["ResourceType"], e["ResourceStatus"], e.get("ResourceStatusReason")) for e in events] == [
("AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS", "User Initiated")]
assert [s["ChangeSetName"] for s in cfn.list_change_sets(StackName=stack)["Summaries"]] == ["imp"]
- with pytest.raises(ClientError) as exc:
- cfn.execute_change_set(ChangeSetName=cs_id)
- # AWS executes the import; the emulator refuses it by design.
- assert exc.value.response["Error"]["Code"] == "InvalidChangeSetStatus"
# A second import set against the stack under review is accepted too, and
# deleting the change sets leaves the stack for DeleteStack to remove.
again = cfn.create_change_set(StackName=stack, ChangeSetName="again", ChangeSetType="IMPORT",
@@ -628,28 +620,24 @@ def test_failed_import_into_a_new_stack_leaves_the_stack_for_review(cfn, fresh):
assert _stack_row(cfn, stack) == ("REVIEW_IN_PROGRESS", "User Initiated", None)
-# --- execution stays refused and harmless ---
+# --- execution adopts the queue and changes nothing else ---
@pytest.mark.parametrize("by_arn", [False, True])
-def test_repeated_execution_preserves_stack_and_service_resources(cfn, sqs, ssm, adopted, by_arn):
+def test_executed_import_preserves_stack_and_service_resources(cfn, sqs, ssm, adopted, by_arn):
stack, url, pname, _template, _to_import = adopted
cs = _create(cfn, adopted)
- before = cfn.describe_stacks(StackName=stack)["Stacks"]
resources = cfn.describe_stack_resources(StackName=stack)["StackResources"]
- events = cfn.describe_stack_events(StackName=stack)["StackEvents"]
parameter = ssm.get_parameter(Name=pname)["Parameter"]
- template = cfn.get_template(StackName=stack)["TemplateBody"]
target = {"ChangeSetName": cs["ChangeSetId"]} if by_arn else {"StackName": stack, "ChangeSetName": "imp"}
- for _ in range(2):
- with pytest.raises(ClientError) as exc:
- cfn.execute_change_set(**target)
- # AWS executes the import; the emulator refuses it by design.
- assert exc.value.response["Error"]["Code"] == "InvalidChangeSetStatus"
- assert "import" in exc.value.response["Error"]["Message"].lower()
- assert cfn.describe_stacks(StackName=stack)["Stacks"] == before
- assert cfn.describe_stack_resources(StackName=stack)["StackResources"] == resources
- assert cfn.describe_stack_events(StackName=stack)["StackEvents"] == events
- assert cfn.get_template(StackName=stack)["TemplateBody"] == template
+ cfn.execute_change_set(**target)
+ cfn.get_waiter("stack_import_complete").wait(
+ StackName=stack, WaiterConfig={"Delay": 1, "MaxAttempts": 30})
+ with pytest.raises(ClientError) as exc:
+ cfn.execute_change_set(ChangeSetName=cs["ChangeSetId"])
+ assert exc.value.response["Error"]["Code"] == "InvalidChangeSetStatus"
+ after = {r["LogicalResourceId"]: r for r in cfn.describe_stack_resources(StackName=stack)["StackResources"]}
+ assert after.pop("X") == resources[0]
+ assert (after["Q"]["PhysicalResourceId"], after["Q"]["ResourceStatus"]) == (url, "UPDATE_COMPLETE")
assert ssm.get_parameter(Name=pname)["Parameter"] == parameter
attrs = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["VisibilityTimeout"])["Attributes"]
assert attrs["VisibilityTimeout"] == "17"