Skip to content

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

fix(cloudformation): update AutoScaling lifecycle hooks in place (#2180)

iot-rocket0ffd23ee22ba
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb1235e8..8ebb39eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **CloudFormation — `AWS::AutoScaling::LifecycleHook` updates** — a stack update ran the create again, so a member dropped from the template went back to its default and a hook with a generated name moved to another group stayed on the old group too; the hook now updates in place and keeps a dropped member, and an `AutoScalingGroupName` or `LifecycleHookName` change replaces it. `NotificationMetadata` is stored and returned by `DescribeLifecycleHooks`, and a group deleted by its stack takes its lifecycle hooks along. Contributed by @iot-rocket.
- **IoT — mTLS refusals close without a CONNACK under `AUTH=true`** — with `AUTH=true` the mTLS listener closes the connection of an unknown, inactive, revoked or doubly-registered client certificate after its CONNECT without sending a CONNACK, as AWS does on MQTT 3.1.1 and 5; without `AUTH` it still answers a "not authorized" CONNACK, and the log names the reason either way. Contributed by @iot-rocket.
- **IoT — `AttachPolicy` to a target that does not exist** — `AttachPolicy` and `AttachPrincipalPolicy` accepted any target string; they now answer `ResourceNotFoundException` for an unknown certificate or thing group, `InvalidRequestException` for anything else that is not a certificate, a thing group (`AttachPolicy` only) or a Cognito identity id, and `AccessDeniedException` for another account's certificate, which also fails an `AWS::IoT::PolicyPrincipalAttachment` naming such a principal. Contributed by @iot-rocket.
- **Cognito — confirmation codes are checked under `AUTH=true`** — `ConfirmSignUp` and `ConfirmForgotPassword` accepted any code, and `ConfirmForgotPassword` changed the password even when no reset was requested; with `AUTH=true` they take only the issued code (`123456` for sign-up and `654321` for a password reset, as before), answer a wrong one with `CodeMismatchException` and a code that was never issued with `ExpiredCodeException`, and `ConfirmSignUp` refuses a user who is not `UNCONFIRMED` with `NotAuthorizedException`, as AWS does. Contributed by @iot-rocket.
diff --git a/ministack/services/autoscaling.py b/ministack/services/autoscaling.py
index 85781a63..2f65045b 100644
--- a/ministack/services/autoscaling.py
+++ b/ministack/services/autoscaling.py
@@ -363,10 +363,7 @@ def _delete_asg(p):
name = _p(p, "AutoScalingGroupName")
_asgs.pop(name, None)
_tags.pop(name, None)
- # Remove associated hooks
- keys_to_del = [k for k in _hooks if k.startswith(f"{name}/")]
- for k in keys_to_del:
- del _hooks[k]
+ _delete_group_hooks(name)
_delete_group_policies(name)
return _xml(200, "DeleteAutoScalingGroupResponse", "<DeleteAutoScalingGroupResult/>")
@@ -703,6 +700,13 @@ def _delete_group_policies(asg_name):
_delete_policy_alarms(_policies.pop(k, None))
+def _delete_group_hooks(asg_name):
+ """Delete the lifecycle hooks of a group."""
+ for k, hook in list(_hooks.items()):
+ if hook.get("AutoScalingGroupName") == asg_name:
+ _hooks.pop(k, None)
+
+
def _member_xml(value):
"""A stored member as query-protocol XML."""
if isinstance(value, dict):
@@ -743,19 +747,28 @@ def _delete_policy(p):
# Lifecycle Hook
# ---------------------------------------------------------------------------
+def _hook_record(asg_name, hook_name, fields):
+ """A lifecycle hook record, from API members or template properties."""
+ return {
+ "LifecycleHookName": hook_name,
+ "AutoScalingGroupName": asg_name,
+ "LifecycleTransition": fields.get("LifecycleTransition") or "autoscaling:EC2_INSTANCE_LAUNCHING",
+ "HeartbeatTimeout": int(fields.get("HeartbeatTimeout") or 3600),
+ "DefaultResult": fields.get("DefaultResult") or "ABANDON",
+ "NotificationTargetARN": fields.get("NotificationTargetARN") or "",
+ "RoleARN": fields.get("RoleARN") or "",
+ "NotificationMetadata": fields.get("NotificationMetadata") or "",
+ }
+
+
def _put_lifecycle_hook(p):
asg_name = _p(p, "AutoScalingGroupName")
hook_name = _p(p, "LifecycleHookName")
key = f"{asg_name}/{hook_name}"
- _hooks[key] = {
- "LifecycleHookName": hook_name,
- "AutoScalingGroupName": asg_name,
- "LifecycleTransition": _p(p, "LifecycleTransition") or "autoscaling:EC2_INSTANCE_LAUNCHING",
- "HeartbeatTimeout": int(_p(p, "HeartbeatTimeout") or 3600),
- "DefaultResult": _p(p, "DefaultResult") or "ABANDON",
- "NotificationTargetARN": _p(p, "NotificationTargetARN") or "",
- "RoleARN": _p(p, "RoleARN") or "",
- }
+ _hooks[key] = _hook_record(asg_name, hook_name, {
+ member: _p(p, member) for member in (
+ "LifecycleTransition", "HeartbeatTimeout", "DefaultResult",
+ "NotificationTargetARN", "RoleARN", "NotificationMetadata")})
return _xml(200, "PutLifecycleHookResponse", "<PutLifecycleHookResult/>")
@@ -765,10 +778,13 @@ def _describe_lifecycle_hooks(p):
for key, hook in _hooks.items():
if hook["AutoScalingGroupName"] != asg_name:
continue
+ metadata = hook.get("NotificationMetadata")
+ metadata_xml = f"<NotificationMetadata>{escape(metadata)}</NotificationMetadata>" if metadata else ""
members += (f"<member>"
f"<LifecycleHookName>{hook['LifecycleHookName']}</LifecycleHookName>"
f"<AutoScalingGroupName>{hook['AutoScalingGroupName']}</AutoScalingGroupName>"
f"<LifecycleTransition>{hook['LifecycleTransition']}</LifecycleTransition>"
+ f"{metadata_xml}"
f"<HeartbeatTimeout>{hook['HeartbeatTimeout']}</HeartbeatTimeout>"
f"<DefaultResult>{hook['DefaultResult']}</DefaultResult>"
f"</member>")
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 55b957b6..6afae716 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -11846,6 +11846,7 @@ def _asg_update(physical_id, old_props, new_props, stack_name, logical_id=None):
def _asg_delete(physical_id, props):
_asg._asgs.pop(physical_id, None)
_asg._tags.pop(physical_id, None)
+ _asg._delete_group_hooks(physical_id)
_asg._delete_group_policies(physical_id)
@@ -11913,19 +11914,19 @@ def _asg_policy_delete(physical_id, props):
def _asg_hook_create(logical_id, props, stack_name):
asg_name = props.get("AutoScalingGroupName", "")
hook_name = props.get("LifecycleHookName") or _physical_name(stack_name, logical_id, max_len=255)
- key = f"{asg_name}/{hook_name}"
- _asg._hooks[key] = {
- "LifecycleHookName": hook_name,
- "AutoScalingGroupName": asg_name,
- "LifecycleTransition": props.get("LifecycleTransition", "autoscaling:EC2_INSTANCE_LAUNCHING"),
- "HeartbeatTimeout": int(props.get("HeartbeatTimeout", 3600)),
- "DefaultResult": props.get("DefaultResult", "ABANDON"),
- "NotificationTargetARN": props.get("NotificationTargetARN", ""),
- "RoleARN": props.get("RoleARN", ""),
- }
+ _asg._hooks[f"{asg_name}/{hook_name}"] = _asg._hook_record(asg_name, hook_name, props)
return hook_name, {"LifecycleHookName": hook_name}
+def _asg_hook_update(physical_id, old_props, new_props, stack_name):
+ """AutoScalingGroupName and LifecycleHookName replace; the rest is in place and a dropped member stays."""
+ asg_name = new_props.get("AutoScalingGroupName", "")
+ key = f"{asg_name}/{physical_id}"
+ current = _asg._hooks.get(key, {})
+ _asg._hooks[key] = _asg._hook_record(asg_name, physical_id, {**current, **new_props})
+ return physical_id, {"LifecycleHookName": physical_id}
+
+
def _asg_hook_delete(physical_id, props):
asg_name = props.get("AutoScalingGroupName", "")
_asg._hooks.pop(f"{asg_name}/{physical_id}", None)
@@ -14214,6 +14215,7 @@ _REPLACING_PROPERTIES: dict[str, tuple[str, ...]] = {
"LaunchConfigurationName", "MetadataOptions", "PlacementTenancy", "RamDiskId",
"SecurityGroups", "SpotPrice", "UserData",
),
+ "AWS::AutoScaling::LifecycleHook": ("AutoScalingGroupName", "LifecycleHookName"),
"AWS::IAM::InstanceProfile": ("InstanceProfileName", "Path"),
"AWS::IAM::Role": ("RoleName", "Path"),
"AWS::IAM::User": ("UserName",),
@@ -15257,7 +15259,11 @@ _RESOURCE_HANDLERS = {
"update_with_logical_id": True,
"delete": _asg_policy_delete,
},
- "AWS::AutoScaling::LifecycleHook": {"create": _asg_hook_create, "delete": _asg_hook_delete},
+ "AWS::AutoScaling::LifecycleHook": {
+ "create": _asg_hook_create,
+ "update": _asg_hook_update,
+ "delete": _asg_hook_delete,
+ },
"AWS::AutoScaling::ScheduledAction": {
"create": _asg_scheduled_create,
"update": _asg_scheduled_update,
diff --git a/tests/test_autoscaling.py b/tests/test_autoscaling.py
index 9d9046b6..dcf34340 100644
--- a/tests/test_autoscaling.py
+++ b/tests/test_autoscaling.py
@@ -745,6 +745,29 @@ def test_put_and_describe_lifecycle_hook(autoscaling):
autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+def test_put_lifecycle_hook_notification_metadata_reads_back(autoscaling):
+ asg = _uid("asg-hmeta")
+ hook = _uid("hmeta")
+ autoscaling.create_auto_scaling_group(
+ AutoScalingGroupName=asg,
+ MinSize=0,
+ MaxSize=1,
+ AvailabilityZones=["us-east-1a"],
+ LaunchConfigurationName="dummy-lc",
+ )
+ try:
+ autoscaling.put_lifecycle_hook(
+ AutoScalingGroupName=asg,
+ LifecycleHookName=hook,
+ LifecycleTransition="autoscaling:EC2_INSTANCE_TERMINATING",
+ NotificationMetadata='{"drain": "<all> & wait"}',
+ )
+ [found] = autoscaling.describe_lifecycle_hooks(AutoScalingGroupName=asg)["LifecycleHooks"]
+ assert found["NotificationMetadata"] == '{"drain": "<all> & wait"}'
+ finally:
+ autoscaling.delete_auto_scaling_group(AutoScalingGroupName=asg)
+
+
def test_describe_lifecycle_hooks_empty(autoscaling):
asg = _uid("asg-nohook")
autoscaling.create_auto_scaling_group(
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index 6f65881c..d802e151 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -30565,6 +30565,23 @@ def test_cfn_asg_delete_removes_target_tracking_alarms(cfn, autoscaling, cw):
assert autoscaling.describe_policies(AutoScalingGroupName=group)["ScalingPolicies"] == []
+def test_cfn_asg_delete_removes_lifecycle_hooks_put_on_it(cfn, autoscaling):
+ """Deleting a template group deletes the lifecycle hooks put on it through the API."""
+ suffix = _uuid_mod.uuid4().hex[:8]
+ stack_name = f"cfn-asg-hookdel-{suffix}"
+ group = f"cfn-asg-hookdel-{suffix}"
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_asg_policy_template(group, {}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ autoscaling.put_lifecycle_hook(
+ AutoScalingGroupName=group, LifecycleHookName="drain",
+ LifecycleTransition="autoscaling:EC2_INSTANCE_TERMINATING")
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+ assert autoscaling.describe_lifecycle_hooks(AutoScalingGroupName=group)["LifecycleHooks"] == []
+
+
def test_cfn_asg_target_tracking_policy_creates_its_alarms(cfn, autoscaling, cw):
"""A template target tracking policy creates its alarms, replaces them on update and deletes them with the stack."""
suffix = _uuid_mod.uuid4().hex[:8]
@@ -31011,6 +31028,134 @@ def test_cfn_asg_scheduled_action_recurrence_change_is_rolled_back(cfn, autoscal
_delete_cfn_test_stack(cfn, stack_name)
+def _cfn_asg_hook_template(hook):
+ group = {"LaunchConfigurationName": {"Ref": "LC"}, "MinSize": "0", "MaxSize": "1",
+ "DesiredCapacity": "0", "AvailabilityZones": ["us-east-1a"]}
+ return json.dumps({
+ "Resources": {
+ "LC": {"Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"}},
+ "GroupA": {"Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": group},
+ "GroupB": {"Type": "AWS::AutoScaling::AutoScalingGroup", "Properties": group},
+ "Hook": {"Type": "AWS::AutoScaling::LifecycleHook", "Properties": hook},
+ },
+ "Outputs": {key: {"Value": {"Ref": key}} for key in ("Hook", "GroupA", "GroupB")},
+ })
+
+
+def _cfn_asg_hooks(autoscaling, group):
+ return [(h["LifecycleHookName"], h["LifecycleTransition"], h["HeartbeatTimeout"],
+ h["DefaultResult"], h.get("NotificationMetadata"))
+ for h in autoscaling.describe_lifecycle_hooks(
+ AutoScalingGroupName=group)["LifecycleHooks"]]
+
+
+def test_cfn_asg_lifecycle_hook_update_in_place_keeps_dropped_members(cfn, autoscaling):
+ """A hook update keeps the name; a member the template drops keeps its value."""
+ stack_name = f"cfn-asg-hook-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(**members):
+ return _cfn_asg_hook_template({"AutoScalingGroupName": {"Ref": "GroupA"}, **members})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(
+ LifecycleTransition="autoscaling:EC2_INSTANCE_LAUNCHING", HeartbeatTimeout=300,
+ DefaultResult="ABANDON"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ name, group = _output(stack, "Hook"), _output(stack, "GroupA")
+
+ changed = (name, "autoscaling:EC2_INSTANCE_TERMINATING", 600, "CONTINUE", None)
+ for members in ({"HeartbeatTimeout": 600, "DefaultResult": "CONTINUE"}, {}):
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(
+ LifecycleTransition="autoscaling:EC2_INSTANCE_TERMINATING", **members))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Hook") == name
+ assert _cfn_asg_hooks(autoscaling, group) == [changed]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_lifecycle_hook_notification_metadata_reads_back_and_updates(cfn, autoscaling):
+ """NotificationMetadata reads back, a change applies and a dropped one stays."""
+ stack_name = f"cfn-asg-hookmd-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(**members):
+ return _cfn_asg_hook_template({
+ "AutoScalingGroupName": {"Ref": "GroupA"},
+ "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING", **members})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template(NotificationMetadata="v1"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ group = _output(stack, "GroupA")
+ assert [h[4] for h in _cfn_asg_hooks(autoscaling, group)] == ["v1"]
+ for members in ({"NotificationMetadata": "v2"}, {}):
+ cfn.update_stack(StackName=stack_name, TemplateBody=template(**members))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ assert [h[4] for h in _cfn_asg_hooks(autoscaling, group)] == ["v2"]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
+def test_cfn_asg_lifecycle_hook_group_change_replaces_it(cfn, autoscaling):
+ """A hook moved to another group gets a new generated name and leaves the old group."""
+ stack_name = f"cfn-asg-hookmv-{_uuid_mod.uuid4().hex[:8]}"
+
+ def template(group):
+ return _cfn_asg_hook_template({
+ "AutoScalingGroupName": {"Ref": group}, "HeartbeatTimeout": 300,
+ "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING"})
+
+ cfn.create_stack(StackName=stack_name, TemplateBody=template("GroupA"))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ old = _output(stack, "Hook")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=template("GroupB"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_COMPLETE", stack.get("StackStatusReason")
+ new = _output(stack, "Hook")
+ assert new != old and new.startswith(f"{stack_name}-Hook-")
+ assert _cfn_asg_hooks(autoscaling, _output(stack, "GroupA")) == []
+ assert _cfn_asg_hooks(autoscaling, _output(stack, "GroupB")) == [
+ (new, "autoscaling:EC2_INSTANCE_TERMINATING", 300, "ABANDON", None)]
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
[email protected]("change,result", [
+ ({"HeartbeatTimeout": 900}, "ABANDON"),
+ ({"HeartbeatTimeout": 900, "DefaultResult": "CONTINUE"}, "CONTINUE"),
+ ({"AutoScalingGroupName": {"Ref": "GroupB"}}, "ABANDON"),
+], ids=["in-place", "member-added", "group"])
+def test_cfn_asg_lifecycle_hook_change_is_rolled_back(cfn, autoscaling, change, result):
+ """The rollback restores the old template's members; one it lacks keeps the new value."""
+ stack_name = f"cfn-asg-hookrb-{_uuid_mod.uuid4().hex[:8]}"
+ hook = {"AutoScalingGroupName": {"Ref": "GroupA"}, "HeartbeatTimeout": 300,
+ "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING"}
+ cfn.create_stack(StackName=stack_name, TemplateBody=_cfn_asg_hook_template(hook))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ name = _output(stack, "Hook")
+
+ cfn.update_stack(StackName=stack_name, TemplateBody=_cfn_with_failing_resource(
+ _cfn_asg_hook_template({**hook, **change}), "Hook"))
+ stack = _wait_stack(cfn, stack_name)
+ assert stack["StackStatus"] == "UPDATE_ROLLBACK_COMPLETE", stack.get("StackStatusReason")
+ assert _output(stack, "Hook") == name
+ assert _cfn_asg_hooks(autoscaling, _output(stack, "GroupA")) == [
+ (name, "autoscaling:EC2_INSTANCE_TERMINATING", 300, result, None)]
+ assert _cfn_asg_hooks(autoscaling, _output(stack, "GroupB")) == []
+ finally:
+ _delete_cfn_test_stack(cfn, stack_name)
+
+
def test_cfn_ec2_vpc_update_keeps_id_and_leaves_no_default_children(cfn, ec2):
"""A VPC update keeps its id and leaves no second set of default children."""
suffix = _uuid_mod.uuid4().hex[:8]