AutoScalingGroup

class aws_cdk.aws_autoscaling.AutoScalingGroup(scope, id, *, instance_type, machine_image, vpc, init=None, init_options=None, require_imdsv2=None, role=None, security_group=None, user_data=None, allow_all_outbound=None, associate_public_ip_address=None, auto_scaling_group_name=None, block_devices=None, cooldown=None, desired_capacity=None, group_metrics=None, health_check=None, ignore_unmodified_size_properties=None, instance_monitoring=None, key_name=None, max_capacity=None, max_instance_lifetime=None, min_capacity=None, new_instances_protected_from_scale_in=None, notifications=None, notifications_topic=None, replacing_update_min_successful_instances_percent=None, resource_signal_count=None, resource_signal_timeout=None, rolling_update_configuration=None, signals=None, spot_price=None, update_policy=None, update_type=None, vpc_subnets=None)

Bases: aws_cdk.core.Resource

A Fleet represents a managed set of EC2 instances.

The Fleet models a number of AutoScalingGroups, a launch configuration, a security group and an instance role.

It allows adding arbitrary commands to the startup scripts of the instances in the fleet.

The ASG spans the availability zones specified by vpcSubnets, falling back to the Vpc default strategy if not specified.

Parameters
  • scope (Construct) –

  • id (str) –

  • instance_type (InstanceType) – Type of instance to launch.

  • machine_image (IMachineImage) – AMI to launch.

  • vpc (IVpc) – VPC to launch these instances in.

  • init (Optional[CloudFormationInit]) – Apply the given CloudFormation Init configuration to the instances in the AutoScalingGroup at startup. If you specify init, you must also specify signals to configure the number of instances to wait for and the timeout for waiting for the init process. Default: - no CloudFormation init

  • init_options (Optional[ApplyCloudFormationInitOptions]) – Use the given options for applying CloudFormation Init. Describes the configsets to use and the timeout to wait Default: - default options

  • require_imdsv2 (Optional[bool]) – Whether IMDSv2 should be required on launched instances. Default: - false

  • role (Optional[IRole]) – An IAM role to associate with the instance profile assigned to this Auto Scaling Group. The role must be assumable by the service principal ec2.amazonaws.com: Default: A role will automatically be created, it can be accessed via the role property

  • security_group (Optional[ISecurityGroup]) – Security group to launch the instances in. Default: - A SecurityGroup will be created if none is specified.

  • user_data (Optional[UserData]) – Specific UserData to use. The UserData may still be mutated after creation. Default: - A UserData object appropriate for the MachineImage’s Operating System is created.

  • allow_all_outbound (Optional[bool]) – Whether the instances can initiate connections to anywhere by default. Default: true

  • associate_public_ip_address (Optional[bool]) – Whether instances in the Auto Scaling Group should have public IP addresses associated with them. Default: - Use subnet setting.

  • auto_scaling_group_name (Optional[str]) – The name of the Auto Scaling group. This name must be unique per Region per account. Default: - Auto generated by CloudFormation

  • block_devices (Optional[Sequence[BlockDevice]]) – Specifies how block devices are exposed to the instance. You can specify virtual devices and EBS volumes. Each instance that is launched has an associated root device volume, either an Amazon EBS volume or an instance store volume. You can use block device mappings to specify additional EBS volumes or instance store volumes to attach to an instance when it is launched. Default: - Uses the block device mapping of the AMI

  • cooldown (Optional[Duration]) – Default scaling cooldown for this AutoScalingGroup. Default: Duration.minutes(5)

  • desired_capacity (Union[int, float, None]) – Initial amount of instances in the fleet. If this is set to a number, every deployment will reset the amount of instances to this number. It is recommended to leave this value blank. Default: minCapacity, and leave unchanged during deployment

  • group_metrics (Optional[Sequence[GroupMetrics]]) – Enable monitoring for group metrics, these metrics describe the group rather than any of its instances. To report all group metrics use GroupMetrics.all() Group metrics are reported in a granularity of 1 minute at no additional charge. Default: - no group metrics will be reported

  • health_check (Optional[HealthCheck]) – Configuration for health checks. Default: - HealthCheck.ec2 with no grace period

  • ignore_unmodified_size_properties (Optional[bool]) – If the ASG has scheduled actions, don’t reset unchanged group sizes. Only used if the ASG has scheduled actions (which may scale your ASG up or down regardless of cdk deployments). If true, the size of the group will only be reset if it has been changed in the CDK app. If false, the sizes will always be changed back to what they were in the CDK app on deployment. Default: true

  • instance_monitoring (Optional[Monitoring]) – Controls whether instances in this group are launched with detailed or basic monitoring. When detailed monitoring is enabled, Amazon CloudWatch generates metrics every minute and your account is charged a fee. When you disable detailed monitoring, CloudWatch generates metrics every 5 minutes. Default: - Monitoring.DETAILED

  • key_name (Optional[str]) – Name of SSH keypair to grant access to instances. Default: - No SSH access will be possible.

  • max_capacity (Union[int, float, None]) – Maximum number of instances in the fleet. Default: desiredCapacity

  • max_instance_lifetime (Optional[Duration]) – The maximum amount of time that an instance can be in service. The maximum duration applies to all current and future instances in the group. As an instance approaches its maximum duration, it is terminated and replaced, and cannot be used again. You must specify a value of at least 604,800 seconds (7 days). To clear a previously set value, leave this property undefined. Default: none

  • min_capacity (Union[int, float, None]) – Minimum number of instances in the fleet. Default: 1

  • new_instances_protected_from_scale_in (Optional[bool]) – Whether newly-launched instances are protected from termination by Amazon EC2 Auto Scaling when scaling in. By default, Auto Scaling can terminate an instance at any time after launch when scaling in an Auto Scaling Group, subject to the group’s termination policy. However, you may wish to protect newly-launched instances from being scaled in if they are going to run critical applications that should not be prematurely terminated. This flag must be enabled if the Auto Scaling Group will be associated with an ECS Capacity Provider with managed termination protection. Default: false

  • notifications (Optional[Sequence[NotificationConfiguration]]) – Configure autoscaling group to send notifications about fleet changes to an SNS topic(s). Default: - No fleet change notifications will be sent.

  • notifications_topic (Optional[ITopic]) – (deprecated) SNS topic to send notifications about fleet changes. Default: - No fleet change notifications will be sent.

  • replacing_update_min_successful_instances_percent (Union[int, float, None]) – (deprecated) Configuration for replacing updates. Only used if updateType == UpdateType.ReplacingUpdate. Specifies how many instances must signal success for the update to succeed. Default: minSuccessfulInstancesPercent

  • resource_signal_count (Union[int, float, None]) – (deprecated) How many ResourceSignal calls CloudFormation expects before the resource is considered created. Default: 1 if resourceSignalTimeout is set, 0 otherwise

  • resource_signal_timeout (Optional[Duration]) – (deprecated) The length of time to wait for the resourceSignalCount. The maximum value is 43200 (12 hours). Default: Duration.minutes(5) if resourceSignalCount is set, N/A otherwise

  • rolling_update_configuration (Optional[RollingUpdateConfiguration]) – (deprecated) Configuration for rolling updates. Only used if updateType == UpdateType.RollingUpdate. Default: - RollingUpdateConfiguration with defaults.

  • signals (Optional[Signals]) – Configure waiting for signals during deployment. Use this to pause the CloudFormation deployment to wait for the instances in the AutoScalingGroup to report successful startup during creation and updates. The UserData script needs to invoke cfn-signal with a success or failure code after it is done setting up the instance. Without waiting for signals, the CloudFormation deployment will proceed as soon as the AutoScalingGroup has been created or updated but before the instances in the group have been started. For example, to have instances wait for an Elastic Load Balancing health check before they signal success, add a health-check verification by using the cfn-init helper script. For an example, see the verify_instance_health command in the Auto Scaling rolling updates sample template: https://github.com/awslabs/aws-cloudformation-templates/blob/master/aws/services/AutoScaling/AutoScalingRollingUpdates.yaml Default: - Do not wait for signals

  • spot_price (Optional[str]) – The maximum hourly price (in USD) to be paid for any Spot Instance launched to fulfill the request. Spot Instances are launched when the price you specify exceeds the current Spot market price. Default: none

  • update_policy (Optional[UpdatePolicy]) – What to do when an AutoScalingGroup’s instance configuration is changed. This is applied when any of the settings on the ASG are changed that affect how the instances should be created (VPC, instance type, startup scripts, etc.). It indicates how the existing instances should be replaced with new instances matching the new config. By default, nothing is done and only new instances are launched with the new config. Default: - UpdatePolicy.rollingUpdate() if using init, UpdatePolicy.none() otherwise

  • update_type (Optional[UpdateType]) – (deprecated) What to do when an AutoScalingGroup’s instance configuration is changed. This is applied when any of the settings on the ASG are changed that affect how the instances should be created (VPC, instance type, startup scripts, etc.). It indicates how the existing instances should be replaced with new instances matching the new config. By default, nothing is done and only new instances are launched with the new config. Default: UpdateType.None

  • vpc_subnets (Optional[SubnetSelection]) – Where to place instances within the VPC. Default: - All Private subnets.

Methods

add_lifecycle_hook(id, *, lifecycle_transition, notification_target, default_result=None, heartbeat_timeout=None, lifecycle_hook_name=None, notification_metadata=None, role=None)

Send a message to either an SQS queue or SNS topic when instances launch or terminate.

Parameters
  • id (str) –

  • lifecycle_transition (LifecycleTransition) – The state of the Amazon EC2 instance to which you want to attach the lifecycle hook.

  • notification_target (ILifecycleHookTarget) – The target of the lifecycle hook.

  • default_result (Optional[DefaultResult]) – The action the Auto Scaling group takes when the lifecycle hook timeout elapses or if an unexpected failure occurs. Default: Continue

  • heartbeat_timeout (Optional[Duration]) – Maximum time between calls to RecordLifecycleActionHeartbeat for the hook. If the lifecycle hook times out, perform the action in DefaultResult. Default: - No heartbeat timeout.

  • lifecycle_hook_name (Optional[str]) – Name of the lifecycle hook. Default: - Automatically generated name.

  • notification_metadata (Optional[str]) – Additional data to pass to the lifecycle hook target. Default: - No metadata.

  • role (Optional[IRole]) – The role that allows publishing to the notification target. Default: - A role is automatically created.

Return type

LifecycleHook

add_security_group(security_group)

Add the security group to all instances via the launch configuration security groups array.

Parameters

security_group (ISecurityGroup) – : The security group to add.

Return type

None

add_to_role_policy(statement)

Adds a statement to the IAM role assumed by instances of this fleet.

Parameters

statement (PolicyStatement) –

Return type

None

add_user_data(*commands)

Add command to the startup script of fleet instances.

The command must be in the scripting language supported by the fleet’s OS (i.e. Linux/Windows). Does nothing for imported ASGs.

Parameters

commands (str) –

Return type

None

apply_cloud_formation_init(init, *, config_sets=None, embed_fingerprint=None, ignore_failures=None, include_role=None, include_url=None, print_log=None)

Use a CloudFormation Init configuration at instance startup.

This does the following:

  • Attaches the CloudFormation Init metadata to the AutoScalingGroup resource.

  • Add commands to the UserData to run cfn-init and cfn-signal.

  • Update the instance’s CreationPolicy to wait for cfn-init to finish before reporting success.

Parameters
  • init (CloudFormationInit) –

  • config_sets (Optional[Sequence[str]]) – ConfigSet to activate. Default: [‘default’]

  • embed_fingerprint (Optional[bool]) – Force instance replacement by embedding a config fingerprint. If true (the default), a hash of the config will be embedded into the UserData, so that if the config changes, the UserData changes and instances will be replaced (given an UpdatePolicy has been configured on the AutoScalingGroup). If false, no such hash will be embedded, and if the CloudFormation Init config changes nothing will happen to the running instances. If a config update introduces errors, you will not notice until after the CloudFormation deployment successfully finishes and the next instance fails to launch. Default: true

  • ignore_failures (Optional[bool]) – Don’t fail the instance creation when cfn-init fails. You can use this to prevent CloudFormation from rolling back when instances fail to start up, to help in debugging. Default: false

  • include_role (Optional[bool]) – Include –role argument when running cfn-init and cfn-signal commands. This will be the IAM instance profile attached to the EC2 instance Default: false

  • include_url (Optional[bool]) – Include –url argument when running cfn-init and cfn-signal commands. This will be the cloudformation endpoint in the deployed region e.g. https://cloudformation.us-east-1.amazonaws.com Default: false

  • print_log (Optional[bool]) – Print the results of running cfn-init to the Instance System Log. By default, the output of running cfn-init is written to a log file on the instance. Set this to true to print it to the System Log (visible from the EC2 Console), false to not print it. (Be aware that the system log is refreshed at certain points in time of the instance life cycle, and successful execution may not always show up). Default: true

Return type

None

apply_removal_policy(policy)

Apply the given removal policy to this resource.

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you’ve removed it from the CDK application or because you’ve made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

Parameters

policy (RemovalPolicy) –

Return type

None

are_new_instances_protected_from_scale_in()

Returns true if newly-launched instances are protected from scale-in.

Return type

bool

attach_to_application_target_group(target_group)

Attach to ELBv2 Application Target Group.

Parameters

target_group (IApplicationTargetGroup) –

Return type

LoadBalancerTargetProps

attach_to_classic_lb(load_balancer)

Attach to a classic load balancer.

Parameters

load_balancer (LoadBalancer) –

Return type

None

attach_to_network_target_group(target_group)

Attach to ELBv2 Application Target Group.

Parameters

target_group (INetworkTargetGroup) –

Return type

LoadBalancerTargetProps

protect_new_instances_from_scale_in()

Ensures newly-launched instances are protected from scale-in.

Return type

None

scale_on_cpu_utilization(id, *, target_utilization_percent, cooldown=None, disable_scale_in=None, estimated_instance_warmup=None)

Scale out or in to achieve a target CPU utilization.

Parameters
  • id (str) –

  • target_utilization_percent (Union[int, float]) – Target average CPU utilization across the task.

  • cooldown (Optional[Duration]) – Period after a scaling completes before another scaling activity can start. Default: - The default cooldown configured on the AutoScalingGroup.

  • disable_scale_in (Optional[bool]) – Indicates whether scale in by the target tracking policy is disabled. If the value is true, scale in is disabled and the target tracking policy won’t remove capacity from the autoscaling group. Otherwise, scale in is enabled and the target tracking policy can remove capacity from the group. Default: false

  • estimated_instance_warmup (Optional[Duration]) – Estimated time until a newly launched instance can send metrics to CloudWatch. Default: - Same as the cooldown.

Return type

TargetTrackingScalingPolicy

scale_on_incoming_bytes(id, *, target_bytes_per_second, cooldown=None, disable_scale_in=None, estimated_instance_warmup=None)

Scale out or in to achieve a target network ingress rate.

Parameters
  • id (str) –

  • target_bytes_per_second (Union[int, float]) – Target average bytes/seconds on each instance.

  • cooldown (Optional[Duration]) – Period after a scaling completes before another scaling activity can start. Default: - The default cooldown configured on the AutoScalingGroup.

  • disable_scale_in (Optional[bool]) – Indicates whether scale in by the target tracking policy is disabled. If the value is true, scale in is disabled and the target tracking policy won’t remove capacity from the autoscaling group. Otherwise, scale in is enabled and the target tracking policy can remove capacity from the group. Default: false

  • estimated_instance_warmup (Optional[Duration]) – Estimated time until a newly launched instance can send metrics to CloudWatch. Default: - Same as the cooldown.

Return type

TargetTrackingScalingPolicy

scale_on_metric(id, *, metric, scaling_steps, adjustment_type=None, cooldown=None, estimated_instance_warmup=None, evaluation_periods=None, metric_aggregation_type=None, min_adjustment_magnitude=None)

Scale out or in, in response to a metric.

Parameters
  • id (str) –

  • metric (IMetric) – Metric to scale on.

  • scaling_steps (Sequence[ScalingInterval]) – The intervals for scaling. Maps a range of metric values to a particular scaling behavior.

  • adjustment_type (Optional[AdjustmentType]) – How the adjustment numbers inside ‘intervals’ are interpreted. Default: ChangeInCapacity

  • cooldown (Optional[Duration]) – Grace period after scaling activity. Default: Default cooldown period on your AutoScalingGroup

  • estimated_instance_warmup (Optional[Duration]) – Estimated time until a newly launched instance can send metrics to CloudWatch. Default: Same as the cooldown

  • evaluation_periods (Union[int, float, None]) – How many evaluation periods of the metric to wait before triggering a scaling action. Raising this value can be used to smooth out the metric, at the expense of slower response times. Default: 1

  • metric_aggregation_type (Optional[MetricAggregationType]) – Aggregation to apply to all data points over the evaluation periods. Only has meaning if evaluationPeriods != 1. Default: - The statistic from the metric if applicable (MIN, MAX, AVERAGE), otherwise AVERAGE.

  • min_adjustment_magnitude (Union[int, float, None]) – Minimum absolute number to adjust capacity with as result of percentage scaling. Only when using AdjustmentType = PercentChangeInCapacity, this number controls the minimum absolute effect size. Default: No minimum scaling effect

Return type

StepScalingPolicy

scale_on_outgoing_bytes(id, *, target_bytes_per_second, cooldown=None, disable_scale_in=None, estimated_instance_warmup=None)

Scale out or in to achieve a target network egress rate.

Parameters
  • id (str) –

  • target_bytes_per_second (Union[int, float]) – Target average bytes/seconds on each instance.

  • cooldown (Optional[Duration]) – Period after a scaling completes before another scaling activity can start. Default: - The default cooldown configured on the AutoScalingGroup.

  • disable_scale_in (Optional[bool]) – Indicates whether scale in by the target tracking policy is disabled. If the value is true, scale in is disabled and the target tracking policy won’t remove capacity from the autoscaling group. Otherwise, scale in is enabled and the target tracking policy can remove capacity from the group. Default: false

  • estimated_instance_warmup (Optional[Duration]) – Estimated time until a newly launched instance can send metrics to CloudWatch. Default: - Same as the cooldown.

Return type

TargetTrackingScalingPolicy

scale_on_request_count(id, *, target_requests_per_minute=None, target_requests_per_second=None, cooldown=None, disable_scale_in=None, estimated_instance_warmup=None)

Scale out or in to achieve a target request handling rate.

The AutoScalingGroup must have been attached to an Application Load Balancer in order to be able to call this.

Parameters
  • id (str) –

  • target_requests_per_minute (Union[int, float, None]) – Target average requests/minute on each instance. Default: - Specify exactly one of ‘targetRequestsPerMinute’ and ‘targetRequestsPerSecond’

  • target_requests_per_second (Union[int, float, None]) – (deprecated) Target average requests/seconds on each instance. Default: - Specify exactly one of ‘targetRequestsPerMinute’ and ‘targetRequestsPerSecond’

  • cooldown (Optional[Duration]) – Period after a scaling completes before another scaling activity can start. Default: - The default cooldown configured on the AutoScalingGroup.

  • disable_scale_in (Optional[bool]) – Indicates whether scale in by the target tracking policy is disabled. If the value is true, scale in is disabled and the target tracking policy won’t remove capacity from the autoscaling group. Otherwise, scale in is enabled and the target tracking policy can remove capacity from the group. Default: false

  • estimated_instance_warmup (Optional[Duration]) – Estimated time until a newly launched instance can send metrics to CloudWatch. Default: - Same as the cooldown.

Return type

TargetTrackingScalingPolicy

scale_on_schedule(id, *, schedule, desired_capacity=None, end_time=None, max_capacity=None, min_capacity=None, start_time=None)

Scale out or in based on time.

Parameters
  • id (str) –

  • schedule (Schedule) – When to perform this action. Supports cron expressions. For more information about cron expressions, see https://en.wikipedia.org/wiki/Cron.

  • desired_capacity (Union[int, float, None]) – The new desired capacity. At the scheduled time, set the desired capacity to the given capacity. At least one of maxCapacity, minCapacity, or desiredCapacity must be supplied. Default: - No new desired capacity.

  • end_time (Optional[datetime]) – When this scheduled action expires. Default: - The rule never expires.

  • max_capacity (Union[int, float, None]) – The new maximum capacity. At the scheduled time, set the maximum capacity to the given capacity. At least one of maxCapacity, minCapacity, or desiredCapacity must be supplied. Default: - No new maximum capacity.

  • min_capacity (Union[int, float, None]) – The new minimum capacity. At the scheduled time, set the minimum capacity to the given capacity. At least one of maxCapacity, minCapacity, or desiredCapacity must be supplied. Default: - No new minimum capacity.

  • start_time (Optional[datetime]) – When this scheduled action becomes active. Default: - The rule is activate immediately.

Return type

ScheduledAction

scale_to_track_metric(id, *, metric, target_value, cooldown=None, disable_scale_in=None, estimated_instance_warmup=None)

Scale out or in in order to keep a metric around a target value.

Parameters
  • id (str) –

  • metric (IMetric) – Metric to track. The metric must represent a utilization, so that if it’s higher than the target value, your ASG should scale out, and if it’s lower it should scale in.

  • target_value (Union[int, float]) – Value to keep the metric around.

  • cooldown (Optional[Duration]) – Period after a scaling completes before another scaling activity can start. Default: - The default cooldown configured on the AutoScalingGroup.

  • disable_scale_in (Optional[bool]) – Indicates whether scale in by the target tracking policy is disabled. If the value is true, scale in is disabled and the target tracking policy won’t remove capacity from the autoscaling group. Otherwise, scale in is enabled and the target tracking policy can remove capacity from the group. Default: false

  • estimated_instance_warmup (Optional[Duration]) – Estimated time until a newly launched instance can send metrics to CloudWatch. Default: - Same as the cooldown.

Return type

TargetTrackingScalingPolicy

to_string()

Returns a string representation of this construct.

Return type

str

Attributes

auto_scaling_group_arn

Arn of the AutoScalingGroup.

Return type

str

auto_scaling_group_name

Name of the AutoScalingGroup.

Return type

str

connections

Allows specify security group connections for instances of this fleet.

Return type

Connections

env

The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.

Return type

ResourceEnvironment

grant_principal

The principal to grant permissions to.

Return type

IPrincipal

max_instance_lifetime

The maximum amount of time that an instance can be in service.

Return type

Optional[Duration]

node

The construct tree node associated with this construct.

Return type

ConstructNode

os_type

The type of OS instances of this fleet are running.

Return type

OperatingSystemType

role

The IAM role assumed by instances of this fleet.

Return type

IRole

spot_price

The maximum spot price configured for the autoscaling group.

undefined indicates that this group uses on-demand capacity.

Return type

Optional[str]

stack

The stack in which this resource is defined.

Return type

Stack

user_data

UserData for the instances.

Return type

UserData

Static Methods

classmethod from_auto_scaling_group_name(scope, id, auto_scaling_group_name)
Parameters
  • scope (Construct) –

  • id (str) –

  • auto_scaling_group_name (str) –

Return type

IAutoScalingGroup

classmethod is_construct(x)

Return whether the given object is a Construct.

Parameters

x (Any) –

Return type

bool

classmethod is_resource(construct)

Check whether the given construct is a Resource.

Parameters

construct (IConstruct) –

Return type

bool