AWS CDK AutoScaling Lifecycle Hook Targets (v1)

1.204.0 · deprecated · verified Fri Apr 17

This library provides high-level constructs for defining targets for AWS Auto Scaling group lifecycle hooks, such as sending notifications to an SNS topic or SQS queue, or invoking a Lambda function. It is part of the AWS Cloud Development Kit (CDK) v1 ecosystem, specifically module version 1.204.0, and follows the CDK's rapid release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an AWS Auto Scaling Group with a lifecycle hook configured to publish notifications to an SNS Topic upon instance launch, using the `TopicHookTarget` from this library. This example is for CDK v1. Make sure to replace `os.environ.get('CDK_DEFAULT_REGION')` with a concrete region if not set.

import os
from aws_cdk import (
    Stack,
    App,
    Duration,
    aws_ec2 as ec2,
    aws_autoscaling as autoscaling,
    aws_sns as sns,
)
from aws_cdk.aws_autoscaling_hooktargets import TopicHookTarget
from constructs import Construct

class AutoScalingHookStack(Stack):
    def __init__(self, scope: Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        vpc = ec2.Vpc(self, "VPC", max_azs=2)

        # Create an SNS Topic to receive notifications
        topic = sns.Topic(self, "LifecycleHookTopic")

        # Create an Auto Scaling Group
        asg = autoscaling.AutoScalingGroup(self, "ASG",
            vpc=vpc,
            instance_type=ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
            machine_image=ec2.AmazonLinuxImage(),
            min_capacity=0,
            max_capacity=1,
            desired_capacity=0 # Start at 0 to see hooks fire on scale-out
        )

        # Add a lifecycle hook targeting the SNS Topic
        asg.add_lifecycle_hook("ScalingOutHook",
            lifecycle_transition=autoscaling.LifecycleTransition.AUTO_SCALING_LAUNCH,
            notification_target=TopicHookTarget(topic),
            default_result=autoscaling.DefaultResult.CONTINUE,
            heartbeat_timeout=Duration.minutes(5)
        )

# Example of how to synthesize the stack
# app = App()
# AutoScalingHookStack(app, "AutoScalingHookExampleStack",
#   env={'region': os.environ.get('CDK_DEFAULT_REGION', 'us-east-1')})
# app.synth()

view raw JSON →