aws-cdk.aws-autoscaling


Nameaws-cdk.aws-autoscaling JSON
Version 1.203.0 PyPI version JSON
download
home_pagehttps://github.com/aws/aws-cdk
SummaryThe CDK Construct Library for AWS::AutoScaling
upload_time2023-05-31 23:00:51
maintainer
docs_urlNone
authorAmazon Web Services
requires_python~=3.7
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Amazon EC2 Auto Scaling Construct Library

<!--BEGIN STABILITY BANNER-->---


![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)

![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)

---
<!--END STABILITY BANNER-->

This module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.

## Auto Scaling Group

An `AutoScalingGroup` represents a number of instances on which you run your code. You
pick the size of the fleet, the instance type and the OS image:

```python
# vpc: ec2.Vpc


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
    machine_image=ec2.AmazonLinuxImage()
)
```

NOTE: AutoScalingGroup has an property called `allowAllOutbound` (allowing the instances to contact the
internet) which is set to `true` by default. Be sure to set this to `false`  if you don't want
your instances to be able to start arbitrary connections. Alternatively, you can specify an existing security
group to attach to the instances that are launched, rather than have the group create a new one.

```python
# vpc: ec2.Vpc


my_security_group = ec2.SecurityGroup(self, "SecurityGroup", vpc=vpc)
autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),
    machine_image=ec2.AmazonLinuxImage(),
    security_group=my_security_group
)
```

Alternatively you can create an `AutoScalingGroup` from a `LaunchTemplate`:

```python
# vpc: ec2.Vpc
# launch_template: ec2.LaunchTemplate


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    launch_template=launch_template
)
```

To launch a mixture of Spot and on-demand instances, and/or with multiple instance types, you can create an `AutoScalingGroup` from a MixedInstancesPolicy:

```python
# vpc: ec2.Vpc
# launch_template1: ec2.LaunchTemplate
# launch_template2: ec2.LaunchTemplate


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    mixed_instances_policy=autoscaling.MixedInstancesPolicy(
        instances_distribution=autoscaling.InstancesDistribution(
            on_demand_percentage_above_base_capacity=50
        ),
        launch_template=launch_template1,
        launch_template_overrides=[autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType("t3.micro")), autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType("t3a.micro")), autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType("t4g.micro"), launch_template=launch_template2)]
    )
)
```

## Machine Images (AMIs)

AMIs control the OS that gets launched when you start your EC2 instance. The EC2
library contains constructs to select the AMI you want to use.

Depending on the type of AMI, you select it a different way.

The latest version of Amazon Linux and Microsoft Windows images are
selectable by instantiating one of these classes:

```python
# Pick a Windows edition to use
windows = ec2.WindowsImage(ec2.WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE)

# Pick the right Amazon Linux edition. All arguments shown are optional
# and will default to these values when omitted.
amzn_linux = ec2.AmazonLinuxImage(
    generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX,
    edition=ec2.AmazonLinuxEdition.STANDARD,
    virtualization=ec2.AmazonLinuxVirt.HVM,
    storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE
)

# For other custom (Linux) images, instantiate a `GenericLinuxImage` with
# a map giving the AMI to in for each region:

linux = ec2.GenericLinuxImage({
    "us-east-1": "ami-97785bed",
    "eu-west-1": "ami-12345678"
})
```

> NOTE: The Amazon Linux images selected will be cached in your `cdk.json`, so that your
> AutoScalingGroups don't automatically change out from under you when you're making unrelated
> changes. To update to the latest version of Amazon Linux, remove the cache entry from the `context`
> section of your `cdk.json`.
>
> We will add command-line options to make this step easier in the future.

## AutoScaling Instance Counts

AutoScalingGroups make it possible to raise and lower the number of instances in the group,
in response to (or in advance of) changes in workload.

When you create your AutoScalingGroup, you specify a `minCapacity` and a
`maxCapacity`. AutoScaling policies that respond to metrics will never go higher
or lower than the indicated capacity (but scheduled scaling actions might, see
below).

There are three ways to scale your capacity:

* **In response to a metric** (also known as step scaling); for example, you
  might want to scale out if the CPU usage across your cluster starts to rise,
  and scale in when it drops again.
* **By trying to keep a certain metric around a given value** (also known as
  target tracking scaling); you might want to automatically scale out and in to
  keep your CPU usage around 50%.
* **On a schedule**; you might want to organize your scaling around traffic
  flows you expect, by scaling out in the morning and scaling in in the
  evening.

The general pattern of autoscaling will look like this:

```python
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage


auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=instance_type,
    machine_image=machine_image,

    min_capacity=5,
    max_capacity=100
)
```

### Step Scaling

This type of scaling scales in and out in deterministics steps that you
configure, in response to metric values. For example, your scaling strategy to
scale in response to a metric that represents your average worker pool usage
might look like this:

```plaintext
 Scaling        -1          (no change)          +1       +3
            │        │                       │        │        │
            ├────────┼───────────────────────┼────────┼────────┤
            │        │                       │        │        │
Worker use  0%      10%                     50%       70%     100%
```

(Note that this is not necessarily a recommended scaling strategy, but it's
a possible one. You will have to determine what thresholds are right for you).

Note that in order to set up this scaling strategy, you will have to emit a
metric representing your worker utilization from your instances. After that,
you would configure the scaling something like this:

```python
# auto_scaling_group: autoscaling.AutoScalingGroup


worker_utilization_metric = cloudwatch.Metric(
    namespace="MyService",
    metric_name="WorkerUtilization"
)

auto_scaling_group.scale_on_metric("ScaleToCPU",
    metric=worker_utilization_metric,
    scaling_steps=[autoscaling.ScalingInterval(upper=10, change=-1), autoscaling.ScalingInterval(lower=50, change=+1), autoscaling.ScalingInterval(lower=70, change=+3)
    ],

    # Change this to AdjustmentType.PERCENT_CHANGE_IN_CAPACITY to interpret the
    # 'change' numbers before as percentages instead of capacity counts.
    adjustment_type=autoscaling.AdjustmentType.CHANGE_IN_CAPACITY
)
```

The AutoScaling construct library will create the required CloudWatch alarms and
AutoScaling policies for you.

### Target Tracking Scaling

This type of scaling scales in and out in order to keep a metric around a value
you prefer. There are four types of predefined metrics you can track, or you can
choose to track a custom metric. If you do choose to track a custom metric,
be aware that the metric has to represent instance utilization in some way
(AutoScaling will scale out if the metric is higher than the target, and scale
in if the metric is lower than the target).

If you configure multiple target tracking policies, AutoScaling will use the
one that yields the highest capacity.

The following example scales to keep the CPU usage of your instances around
50% utilization:

```python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.scale_on_cpu_utilization("KeepSpareCPU",
    target_utilization_percent=50
)
```

To scale on average network traffic in and out of your instances:

```python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.scale_on_incoming_bytes("LimitIngressPerInstance",
    target_bytes_per_second=10 * 1024 * 1024
)
auto_scaling_group.scale_on_outgoing_bytes("LimitEgressPerInstance",
    target_bytes_per_second=10 * 1024 * 1024
)
```

To scale on the average request count per instance (only works for
AutoScalingGroups that have been attached to Application Load
Balancers):

```python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.scale_on_request_count("LimitRPS",
    target_requests_per_second=1000
)
```

### Scheduled Scaling

This type of scaling is used to change capacities based on time. It works by
changing `minCapacity`, `maxCapacity` and `desiredCapacity` of the
AutoScalingGroup, and so can be used for two purposes:

* Scale in and out on a schedule by setting the `minCapacity` high or
  the `maxCapacity` low.
* Still allow the regular scaling actions to do their job, but restrict
  the range they can scale over (by setting both `minCapacity` and
  `maxCapacity` but changing their range over time).

A schedule is expressed as a cron expression. The `Schedule` class has a `cron` method to help build cron expressions.

The following example scales the fleet out in the morning, going back to natural
scaling (all the way down to 1 instance if necessary) at night:

```python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.scale_on_schedule("PrescaleInTheMorning",
    schedule=autoscaling.Schedule.cron(hour="8", minute="0"),
    min_capacity=20
)

auto_scaling_group.scale_on_schedule("AllowDownscalingAtNight",
    schedule=autoscaling.Schedule.cron(hour="20", minute="0"),
    min_capacity=1
)
```

## Configuring Instances using CloudFormation Init

It is possible to use the CloudFormation Init mechanism to configure the
instances in the AutoScalingGroup. You can write files to it, run commands,
start services, etc. See the documentation of
[AWS::CloudFormation::Init](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html)
and the documentation of CDK's `aws-ec2` library for more information.

When you specify a CloudFormation Init configuration for an AutoScalingGroup:

* you *must* also specify `signals` to configure how long CloudFormation
  should wait for the instances to successfully configure themselves.
* you *should* also specify an `updatePolicy` to configure how instances
  should be updated when the AutoScalingGroup is updated (for example,
  when the AMI is updated). If you don't specify an update policy, a *rolling
  update* is chosen by default.

Here's an example of using CloudFormation Init to write a file to the
instance hosts on startup:

```python
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=instance_type,
    machine_image=machine_image,

    # ...

    init=ec2.CloudFormationInit.from_elements(
        ec2.InitFile.from_string("/etc/my_instance", "This got written during instance startup")),
    signals=autoscaling.Signals.wait_for_all(
        timeout=Duration.minutes(10)
    )
)
```

## Signals

In normal operation, CloudFormation will send a Create or Update command to
an AutoScalingGroup and proceed with the rest of the deployment without waiting
for the *instances in the AutoScalingGroup*.

Configure `signals` to tell CloudFormation to wait for a specific number of
instances in the AutoScalingGroup to have been started (or failed to start)
before moving on. An instance is supposed to execute the
[`cfn-signal`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-signal.html)
program as part of its startup to indicate whether it was started
successfully or not.

If you use CloudFormation Init support (described in the previous section),
the appropriate call to `cfn-signal` is automatically added to the
AutoScalingGroup's UserData. If you don't use the `signals` directly, you are
responsible for adding such a call yourself.

The following type of `Signals` are available:

* `Signals.waitForAll([options])`: wait for all of `desiredCapacity` amount of instances
  to have started (recommended).
* `Signals.waitForMinCapacity([options])`: wait for a `minCapacity` amount of instances
  to have started (use this if waiting for all instances takes too long and you are happy
  with a minimum count of healthy hosts).
* `Signals.waitForCount(count, [options])`: wait for a specific amount of instances to have
  started.

There are two `options` you can configure:

* `timeout`: maximum time a host startup is allowed to take. If a host does not report
  success within this time, it is considered a failure. Default is 5 minutes.
* `minSuccessPercentage`: percentage of hosts that needs to be healthy in order for the
  update to succeed. If you set this value lower than 100, some percentage of hosts may
  report failure, while still considering the deployment a success. Default is 100%.

## Update Policy

The *update policy* describes what should happen to running instances when the definition
of the AutoScalingGroup is changed. For example, if you add a command to the UserData
of an AutoScalingGroup, do the existing instances get replaced with new instances that
have executed the new UserData? Or do the "old" instances just keep on running?

It is recommended to always use an update policy, otherwise the current state of your
instances also depends the previous state of your instances, rather than just on your
source code. This degrades the reproducibility of your deployments.

The following update policies are available:

* `UpdatePolicy.none()`: leave existing instances alone (not recommended).
* `UpdatePolicy.rollingUpdate([options])`: progressively replace the existing
  instances with new instances, in small batches. At any point in time,
  roughly the same amount of total instances will be running. If the deployment
  needs to be rolled back, the fresh instances will be replaced with the "old"
  configuration again.
* `UpdatePolicy.replacingUpdate([options])`: build a completely fresh copy
  of the new AutoScalingGroup next to the old one. Once the AutoScalingGroup
  has been successfully created (and the instances started, if `signals` is
  configured on the AutoScalingGroup), the old AutoScalingGroup is deleted.
  If the deployment needs to be rolled back, the new AutoScalingGroup is
  deleted and the old one is left unchanged.

## Allowing Connections

See the documentation of the `@aws-cdk/aws-ec2` package for more information
about allowing connections between resources backed by instances.

## Max Instance Lifetime

To enable the max instance lifetime support, specify `maxInstanceLifetime` property
for the `AutoscalingGroup` resource. The value must be between 7 and 365 days(inclusive).
To clear a previously set value, leave this property undefined.

## Instance Monitoring

To disable detailed instance monitoring, specify `instanceMonitoring` property
for the `AutoscalingGroup` resource as `Monitoring.BASIC`. Otherwise detailed monitoring
will be enabled.

## Monitoring Group Metrics

Group metrics are used to monitor group level properties; they describe the group rather than any of its instances (e.g GroupMaxSize, the group maximum size). To enable group metrics monitoring, use the `groupMetrics` property.
All group metrics are reported in a granularity of 1 minute at no additional charge.

See [EC2 docs](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html#as-group-metrics) for a list of all available group metrics.

To enable group metrics monitoring using the `groupMetrics` property:

```python
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage


# Enable monitoring of all group metrics
autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=instance_type,
    machine_image=machine_image,

    # ...

    group_metrics=[autoscaling.GroupMetrics.all()]
)

# Enable monitoring for a subset of group metrics
autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=instance_type,
    machine_image=machine_image,

    # ...

    group_metrics=[autoscaling.GroupMetrics(autoscaling.GroupMetric.MIN_SIZE, autoscaling.GroupMetric.MAX_SIZE)]
)
```

## Termination policies

Auto Scaling uses [termination policies](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html)
to determine which instances it terminates first during scale-in events. You
can specify one or more termination policies with the `terminationPolicies`
property:

```python
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=instance_type,
    machine_image=machine_image,

    # ...

    termination_policies=[autoscaling.TerminationPolicy.OLDEST_INSTANCE, autoscaling.TerminationPolicy.DEFAULT
    ]
)
```

## Protecting new instances from being terminated on scale-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](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html).

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. EC2 Capacity Providers for Amazon ECS requires this attribute be
set to `true`.

```python
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=instance_type,
    machine_image=machine_image,

    # ...

    new_instances_protected_from_scale_in=True
)
```

## Configuring Instance Metadata Service (IMDS)

### Toggling IMDSv1

You can configure [EC2 Instance Metadata Service](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) options to either
allow both IMDSv1 and IMDSv2 or enforce IMDSv2 when interacting with the IMDS.

To do this for a single `AutoScalingGroup`, you can use set the `requireImdsv2` property.
The example below demonstrates IMDSv2 being required on a single `AutoScalingGroup`:

```python
# vpc: ec2.Vpc
# instance_type: ec2.InstanceType
# machine_image: ec2.IMachineImage


autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=instance_type,
    machine_image=machine_image,

    # ...

    require_imdsv2=True
)
```

You can also use `AutoScalingGroupRequireImdsv2Aspect` to apply the operation to multiple AutoScalingGroups.
The example below demonstrates the `AutoScalingGroupRequireImdsv2Aspect` being used to require IMDSv2 for all AutoScalingGroups in a stack:

```python
aspect = autoscaling.AutoScalingGroupRequireImdsv2Aspect()

Aspects.of(self).add(aspect)
```

## Warm Pool

Auto Scaling offers [a warm pool](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html) which gives an ability to decrease latency for applications that have exceptionally long boot times. You can create a warm pool with default parameters as below:

```python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.add_warm_pool()
```

You can also customize a warm pool by configuring parameters:

```python
# auto_scaling_group: autoscaling.AutoScalingGroup


auto_scaling_group.add_warm_pool(
    min_size=1,
    reuse_on_scale_in=True
)
```

## Future work

* [ ] CloudWatch Events (impossible to add currently as the AutoScalingGroup ARN is
  necessary to make this rule and this cannot be accessed from CloudFormation).



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aws/aws-cdk",
    "name": "aws-cdk.aws-autoscaling",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "~=3.7",
    "maintainer_email": "",
    "keywords": "",
    "author": "Amazon Web Services",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/1c/90/ae638816583486bbcf8ef9ba693ab67852275e9ee28439da701d6e1e02ab/aws-cdk.aws-autoscaling-1.203.0.tar.gz",
    "platform": null,
    "description": "# Amazon EC2 Auto Scaling Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)\n\n![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)\n\n---\n<!--END STABILITY BANNER-->\n\nThis module is part of the [AWS Cloud Development Kit](https://github.com/aws/aws-cdk) project.\n\n## Auto Scaling Group\n\nAn `AutoScalingGroup` represents a number of instances on which you run your code. You\npick the size of the fleet, the instance type and the OS image:\n\n```python\n# vpc: ec2.Vpc\n\n\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),\n    machine_image=ec2.AmazonLinuxImage()\n)\n```\n\nNOTE: AutoScalingGroup has an property called `allowAllOutbound` (allowing the instances to contact the\ninternet) which is set to `true` by default. Be sure to set this to `false`  if you don't want\nyour instances to be able to start arbitrary connections. Alternatively, you can specify an existing security\ngroup to attach to the instances that are launched, rather than have the group create a new one.\n\n```python\n# vpc: ec2.Vpc\n\n\nmy_security_group = ec2.SecurityGroup(self, \"SecurityGroup\", vpc=vpc)\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.MICRO),\n    machine_image=ec2.AmazonLinuxImage(),\n    security_group=my_security_group\n)\n```\n\nAlternatively you can create an `AutoScalingGroup` from a `LaunchTemplate`:\n\n```python\n# vpc: ec2.Vpc\n# launch_template: ec2.LaunchTemplate\n\n\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    launch_template=launch_template\n)\n```\n\nTo launch a mixture of Spot and on-demand instances, and/or with multiple instance types, you can create an `AutoScalingGroup` from a MixedInstancesPolicy:\n\n```python\n# vpc: ec2.Vpc\n# launch_template1: ec2.LaunchTemplate\n# launch_template2: ec2.LaunchTemplate\n\n\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    mixed_instances_policy=autoscaling.MixedInstancesPolicy(\n        instances_distribution=autoscaling.InstancesDistribution(\n            on_demand_percentage_above_base_capacity=50\n        ),\n        launch_template=launch_template1,\n        launch_template_overrides=[autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType(\"t3.micro\")), autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType(\"t3a.micro\")), autoscaling.LaunchTemplateOverrides(instance_type=ec2.InstanceType(\"t4g.micro\"), launch_template=launch_template2)]\n    )\n)\n```\n\n## Machine Images (AMIs)\n\nAMIs control the OS that gets launched when you start your EC2 instance. The EC2\nlibrary contains constructs to select the AMI you want to use.\n\nDepending on the type of AMI, you select it a different way.\n\nThe latest version of Amazon Linux and Microsoft Windows images are\nselectable by instantiating one of these classes:\n\n```python\n# Pick a Windows edition to use\nwindows = ec2.WindowsImage(ec2.WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE)\n\n# Pick the right Amazon Linux edition. All arguments shown are optional\n# and will default to these values when omitted.\namzn_linux = ec2.AmazonLinuxImage(\n    generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX,\n    edition=ec2.AmazonLinuxEdition.STANDARD,\n    virtualization=ec2.AmazonLinuxVirt.HVM,\n    storage=ec2.AmazonLinuxStorage.GENERAL_PURPOSE\n)\n\n# For other custom (Linux) images, instantiate a `GenericLinuxImage` with\n# a map giving the AMI to in for each region:\n\nlinux = ec2.GenericLinuxImage({\n    \"us-east-1\": \"ami-97785bed\",\n    \"eu-west-1\": \"ami-12345678\"\n})\n```\n\n> NOTE: The Amazon Linux images selected will be cached in your `cdk.json`, so that your\n> AutoScalingGroups don't automatically change out from under you when you're making unrelated\n> changes. To update to the latest version of Amazon Linux, remove the cache entry from the `context`\n> section of your `cdk.json`.\n>\n> We will add command-line options to make this step easier in the future.\n\n## AutoScaling Instance Counts\n\nAutoScalingGroups make it possible to raise and lower the number of instances in the group,\nin response to (or in advance of) changes in workload.\n\nWhen you create your AutoScalingGroup, you specify a `minCapacity` and a\n`maxCapacity`. AutoScaling policies that respond to metrics will never go higher\nor lower than the indicated capacity (but scheduled scaling actions might, see\nbelow).\n\nThere are three ways to scale your capacity:\n\n* **In response to a metric** (also known as step scaling); for example, you\n  might want to scale out if the CPU usage across your cluster starts to rise,\n  and scale in when it drops again.\n* **By trying to keep a certain metric around a given value** (also known as\n  target tracking scaling); you might want to automatically scale out and in to\n  keep your CPU usage around 50%.\n* **On a schedule**; you might want to organize your scaling around traffic\n  flows you expect, by scaling out in the morning and scaling in in the\n  evening.\n\nThe general pattern of autoscaling will look like this:\n\n```python\n# vpc: ec2.Vpc\n# instance_type: ec2.InstanceType\n# machine_image: ec2.IMachineImage\n\n\nauto_scaling_group = autoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=instance_type,\n    machine_image=machine_image,\n\n    min_capacity=5,\n    max_capacity=100\n)\n```\n\n### Step Scaling\n\nThis type of scaling scales in and out in deterministics steps that you\nconfigure, in response to metric values. For example, your scaling strategy to\nscale in response to a metric that represents your average worker pool usage\nmight look like this:\n\n```plaintext\n Scaling        -1          (no change)          +1       +3\n            \u2502        \u2502                       \u2502        \u2502        \u2502\n            \u251c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524\n            \u2502        \u2502                       \u2502        \u2502        \u2502\nWorker use  0%      10%                     50%       70%     100%\n```\n\n(Note that this is not necessarily a recommended scaling strategy, but it's\na possible one. You will have to determine what thresholds are right for you).\n\nNote that in order to set up this scaling strategy, you will have to emit a\nmetric representing your worker utilization from your instances. After that,\nyou would configure the scaling something like this:\n\n```python\n# auto_scaling_group: autoscaling.AutoScalingGroup\n\n\nworker_utilization_metric = cloudwatch.Metric(\n    namespace=\"MyService\",\n    metric_name=\"WorkerUtilization\"\n)\n\nauto_scaling_group.scale_on_metric(\"ScaleToCPU\",\n    metric=worker_utilization_metric,\n    scaling_steps=[autoscaling.ScalingInterval(upper=10, change=-1), autoscaling.ScalingInterval(lower=50, change=+1), autoscaling.ScalingInterval(lower=70, change=+3)\n    ],\n\n    # Change this to AdjustmentType.PERCENT_CHANGE_IN_CAPACITY to interpret the\n    # 'change' numbers before as percentages instead of capacity counts.\n    adjustment_type=autoscaling.AdjustmentType.CHANGE_IN_CAPACITY\n)\n```\n\nThe AutoScaling construct library will create the required CloudWatch alarms and\nAutoScaling policies for you.\n\n### Target Tracking Scaling\n\nThis type of scaling scales in and out in order to keep a metric around a value\nyou prefer. There are four types of predefined metrics you can track, or you can\nchoose to track a custom metric. If you do choose to track a custom metric,\nbe aware that the metric has to represent instance utilization in some way\n(AutoScaling will scale out if the metric is higher than the target, and scale\nin if the metric is lower than the target).\n\nIf you configure multiple target tracking policies, AutoScaling will use the\none that yields the highest capacity.\n\nThe following example scales to keep the CPU usage of your instances around\n50% utilization:\n\n```python\n# auto_scaling_group: autoscaling.AutoScalingGroup\n\n\nauto_scaling_group.scale_on_cpu_utilization(\"KeepSpareCPU\",\n    target_utilization_percent=50\n)\n```\n\nTo scale on average network traffic in and out of your instances:\n\n```python\n# auto_scaling_group: autoscaling.AutoScalingGroup\n\n\nauto_scaling_group.scale_on_incoming_bytes(\"LimitIngressPerInstance\",\n    target_bytes_per_second=10 * 1024 * 1024\n)\nauto_scaling_group.scale_on_outgoing_bytes(\"LimitEgressPerInstance\",\n    target_bytes_per_second=10 * 1024 * 1024\n)\n```\n\nTo scale on the average request count per instance (only works for\nAutoScalingGroups that have been attached to Application Load\nBalancers):\n\n```python\n# auto_scaling_group: autoscaling.AutoScalingGroup\n\n\nauto_scaling_group.scale_on_request_count(\"LimitRPS\",\n    target_requests_per_second=1000\n)\n```\n\n### Scheduled Scaling\n\nThis type of scaling is used to change capacities based on time. It works by\nchanging `minCapacity`, `maxCapacity` and `desiredCapacity` of the\nAutoScalingGroup, and so can be used for two purposes:\n\n* Scale in and out on a schedule by setting the `minCapacity` high or\n  the `maxCapacity` low.\n* Still allow the regular scaling actions to do their job, but restrict\n  the range they can scale over (by setting both `minCapacity` and\n  `maxCapacity` but changing their range over time).\n\nA schedule is expressed as a cron expression. The `Schedule` class has a `cron` method to help build cron expressions.\n\nThe following example scales the fleet out in the morning, going back to natural\nscaling (all the way down to 1 instance if necessary) at night:\n\n```python\n# auto_scaling_group: autoscaling.AutoScalingGroup\n\n\nauto_scaling_group.scale_on_schedule(\"PrescaleInTheMorning\",\n    schedule=autoscaling.Schedule.cron(hour=\"8\", minute=\"0\"),\n    min_capacity=20\n)\n\nauto_scaling_group.scale_on_schedule(\"AllowDownscalingAtNight\",\n    schedule=autoscaling.Schedule.cron(hour=\"20\", minute=\"0\"),\n    min_capacity=1\n)\n```\n\n## Configuring Instances using CloudFormation Init\n\nIt is possible to use the CloudFormation Init mechanism to configure the\ninstances in the AutoScalingGroup. You can write files to it, run commands,\nstart services, etc. See the documentation of\n[AWS::CloudFormation::Init](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html)\nand the documentation of CDK's `aws-ec2` library for more information.\n\nWhen you specify a CloudFormation Init configuration for an AutoScalingGroup:\n\n* you *must* also specify `signals` to configure how long CloudFormation\n  should wait for the instances to successfully configure themselves.\n* you *should* also specify an `updatePolicy` to configure how instances\n  should be updated when the AutoScalingGroup is updated (for example,\n  when the AMI is updated). If you don't specify an update policy, a *rolling\n  update* is chosen by default.\n\nHere's an example of using CloudFormation Init to write a file to the\ninstance hosts on startup:\n\n```python\n# vpc: ec2.Vpc\n# instance_type: ec2.InstanceType\n# machine_image: ec2.IMachineImage\n\n\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=instance_type,\n    machine_image=machine_image,\n\n    # ...\n\n    init=ec2.CloudFormationInit.from_elements(\n        ec2.InitFile.from_string(\"/etc/my_instance\", \"This got written during instance startup\")),\n    signals=autoscaling.Signals.wait_for_all(\n        timeout=Duration.minutes(10)\n    )\n)\n```\n\n## Signals\n\nIn normal operation, CloudFormation will send a Create or Update command to\nan AutoScalingGroup and proceed with the rest of the deployment without waiting\nfor the *instances in the AutoScalingGroup*.\n\nConfigure `signals` to tell CloudFormation to wait for a specific number of\ninstances in the AutoScalingGroup to have been started (or failed to start)\nbefore moving on. An instance is supposed to execute the\n[`cfn-signal`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-signal.html)\nprogram as part of its startup to indicate whether it was started\nsuccessfully or not.\n\nIf you use CloudFormation Init support (described in the previous section),\nthe appropriate call to `cfn-signal` is automatically added to the\nAutoScalingGroup's UserData. If you don't use the `signals` directly, you are\nresponsible for adding such a call yourself.\n\nThe following type of `Signals` are available:\n\n* `Signals.waitForAll([options])`: wait for all of `desiredCapacity` amount of instances\n  to have started (recommended).\n* `Signals.waitForMinCapacity([options])`: wait for a `minCapacity` amount of instances\n  to have started (use this if waiting for all instances takes too long and you are happy\n  with a minimum count of healthy hosts).\n* `Signals.waitForCount(count, [options])`: wait for a specific amount of instances to have\n  started.\n\nThere are two `options` you can configure:\n\n* `timeout`: maximum time a host startup is allowed to take. If a host does not report\n  success within this time, it is considered a failure. Default is 5 minutes.\n* `minSuccessPercentage`: percentage of hosts that needs to be healthy in order for the\n  update to succeed. If you set this value lower than 100, some percentage of hosts may\n  report failure, while still considering the deployment a success. Default is 100%.\n\n## Update Policy\n\nThe *update policy* describes what should happen to running instances when the definition\nof the AutoScalingGroup is changed. For example, if you add a command to the UserData\nof an AutoScalingGroup, do the existing instances get replaced with new instances that\nhave executed the new UserData? Or do the \"old\" instances just keep on running?\n\nIt is recommended to always use an update policy, otherwise the current state of your\ninstances also depends the previous state of your instances, rather than just on your\nsource code. This degrades the reproducibility of your deployments.\n\nThe following update policies are available:\n\n* `UpdatePolicy.none()`: leave existing instances alone (not recommended).\n* `UpdatePolicy.rollingUpdate([options])`: progressively replace the existing\n  instances with new instances, in small batches. At any point in time,\n  roughly the same amount of total instances will be running. If the deployment\n  needs to be rolled back, the fresh instances will be replaced with the \"old\"\n  configuration again.\n* `UpdatePolicy.replacingUpdate([options])`: build a completely fresh copy\n  of the new AutoScalingGroup next to the old one. Once the AutoScalingGroup\n  has been successfully created (and the instances started, if `signals` is\n  configured on the AutoScalingGroup), the old AutoScalingGroup is deleted.\n  If the deployment needs to be rolled back, the new AutoScalingGroup is\n  deleted and the old one is left unchanged.\n\n## Allowing Connections\n\nSee the documentation of the `@aws-cdk/aws-ec2` package for more information\nabout allowing connections between resources backed by instances.\n\n## Max Instance Lifetime\n\nTo enable the max instance lifetime support, specify `maxInstanceLifetime` property\nfor the `AutoscalingGroup` resource. The value must be between 7 and 365 days(inclusive).\nTo clear a previously set value, leave this property undefined.\n\n## Instance Monitoring\n\nTo disable detailed instance monitoring, specify `instanceMonitoring` property\nfor the `AutoscalingGroup` resource as `Monitoring.BASIC`. Otherwise detailed monitoring\nwill be enabled.\n\n## Monitoring Group Metrics\n\nGroup metrics are used to monitor group level properties; they describe the group rather than any of its instances (e.g GroupMaxSize, the group maximum size). To enable group metrics monitoring, use the `groupMetrics` property.\nAll group metrics are reported in a granularity of 1 minute at no additional charge.\n\nSee [EC2 docs](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html#as-group-metrics) for a list of all available group metrics.\n\nTo enable group metrics monitoring using the `groupMetrics` property:\n\n```python\n# vpc: ec2.Vpc\n# instance_type: ec2.InstanceType\n# machine_image: ec2.IMachineImage\n\n\n# Enable monitoring of all group metrics\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=instance_type,\n    machine_image=machine_image,\n\n    # ...\n\n    group_metrics=[autoscaling.GroupMetrics.all()]\n)\n\n# Enable monitoring for a subset of group metrics\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=instance_type,\n    machine_image=machine_image,\n\n    # ...\n\n    group_metrics=[autoscaling.GroupMetrics(autoscaling.GroupMetric.MIN_SIZE, autoscaling.GroupMetric.MAX_SIZE)]\n)\n```\n\n## Termination policies\n\nAuto Scaling uses [termination policies](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html)\nto determine which instances it terminates first during scale-in events. You\ncan specify one or more termination policies with the `terminationPolicies`\nproperty:\n\n```python\n# vpc: ec2.Vpc\n# instance_type: ec2.InstanceType\n# machine_image: ec2.IMachineImage\n\n\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=instance_type,\n    machine_image=machine_image,\n\n    # ...\n\n    termination_policies=[autoscaling.TerminationPolicy.OLDEST_INSTANCE, autoscaling.TerminationPolicy.DEFAULT\n    ]\n)\n```\n\n## Protecting new instances from being terminated on scale-in\n\nBy default, Auto Scaling can terminate an instance at any time after launch when\nscaling in an Auto Scaling Group, subject to the group's [termination\npolicy](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html).\n\nHowever, you may wish to protect newly-launched instances from being scaled in\nif they are going to run critical applications that should not be prematurely\nterminated. EC2 Capacity Providers for Amazon ECS requires this attribute be\nset to `true`.\n\n```python\n# vpc: ec2.Vpc\n# instance_type: ec2.InstanceType\n# machine_image: ec2.IMachineImage\n\n\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=instance_type,\n    machine_image=machine_image,\n\n    # ...\n\n    new_instances_protected_from_scale_in=True\n)\n```\n\n## Configuring Instance Metadata Service (IMDS)\n\n### Toggling IMDSv1\n\nYou can configure [EC2 Instance Metadata Service](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html) options to either\nallow both IMDSv1 and IMDSv2 or enforce IMDSv2 when interacting with the IMDS.\n\nTo do this for a single `AutoScalingGroup`, you can use set the `requireImdsv2` property.\nThe example below demonstrates IMDSv2 being required on a single `AutoScalingGroup`:\n\n```python\n# vpc: ec2.Vpc\n# instance_type: ec2.InstanceType\n# machine_image: ec2.IMachineImage\n\n\nautoscaling.AutoScalingGroup(self, \"ASG\",\n    vpc=vpc,\n    instance_type=instance_type,\n    machine_image=machine_image,\n\n    # ...\n\n    require_imdsv2=True\n)\n```\n\nYou can also use `AutoScalingGroupRequireImdsv2Aspect` to apply the operation to multiple AutoScalingGroups.\nThe example below demonstrates the `AutoScalingGroupRequireImdsv2Aspect` being used to require IMDSv2 for all AutoScalingGroups in a stack:\n\n```python\naspect = autoscaling.AutoScalingGroupRequireImdsv2Aspect()\n\nAspects.of(self).add(aspect)\n```\n\n## Warm Pool\n\nAuto Scaling offers [a warm pool](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html) which gives an ability to decrease latency for applications that have exceptionally long boot times. You can create a warm pool with default parameters as below:\n\n```python\n# auto_scaling_group: autoscaling.AutoScalingGroup\n\n\nauto_scaling_group.add_warm_pool()\n```\n\nYou can also customize a warm pool by configuring parameters:\n\n```python\n# auto_scaling_group: autoscaling.AutoScalingGroup\n\n\nauto_scaling_group.add_warm_pool(\n    min_size=1,\n    reuse_on_scale_in=True\n)\n```\n\n## Future work\n\n* [ ] CloudWatch Events (impossible to add currently as the AutoScalingGroup ARN is\n  necessary to make this rule and this cannot be accessed from CloudFormation).\n\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "The CDK Construct Library for AWS::AutoScaling",
    "version": "1.203.0",
    "project_urls": {
        "Homepage": "https://github.com/aws/aws-cdk",
        "Source": "https://github.com/aws/aws-cdk.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "29405ebad44210aaa2da13c01ca0c25f3cea517d8ede563d53270b374f33ddd4",
                "md5": "d3340f780bb2edce1243f37ee5c7e286",
                "sha256": "39b2d50d16621310426d085827afb21f2d0ce950ccf3ef6978cbf2aa49b7c011"
            },
            "downloads": -1,
            "filename": "aws_cdk.aws_autoscaling-1.203.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d3340f780bb2edce1243f37ee5c7e286",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.7",
            "size": 631476,
            "upload_time": "2023-05-31T22:52:56",
            "upload_time_iso_8601": "2023-05-31T22:52:56.050206Z",
            "url": "https://files.pythonhosted.org/packages/29/40/5ebad44210aaa2da13c01ca0c25f3cea517d8ede563d53270b374f33ddd4/aws_cdk.aws_autoscaling-1.203.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1c90ae638816583486bbcf8ef9ba693ab67852275e9ee28439da701d6e1e02ab",
                "md5": "28ee7ba33e920782e2ce1dde6649ee63",
                "sha256": "3e1d83b19676384d99b850210bb36d31d580a253cf33e26289b416d14ec245d3"
            },
            "downloads": -1,
            "filename": "aws-cdk.aws-autoscaling-1.203.0.tar.gz",
            "has_sig": false,
            "md5_digest": "28ee7ba33e920782e2ce1dde6649ee63",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.7",
            "size": 632135,
            "upload_time": "2023-05-31T23:00:51",
            "upload_time_iso_8601": "2023-05-31T23:00:51.440644Z",
            "url": "https://files.pythonhosted.org/packages/1c/90/ae638816583486bbcf8ef9ba693ab67852275e9ee28439da701d6e1e02ab/aws-cdk.aws-autoscaling-1.203.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-31 23:00:51",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aws",
    "github_project": "aws-cdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aws-cdk.aws-autoscaling"
}
        
Elapsed time: 0.19872s