Auto scaling template snippets - AWS CloudFormation

Auto scaling template snippets

The following examples show different snippets to include in templates for use with Amazon EC2 Auto Scaling or Application Auto Scaling.

Amazon EC2 Auto Scaling enables you to automatically scale Amazon EC2 instances, either with scaling policies or with scheduled scaling. Auto Scaling groups are collections of Amazon EC2 instances that enable automatic scaling and fleet management features, such as health checks and integration with Elastic Load Balancing.

Application Auto Scaling provides automatic scaling of different resources beyond Amazon EC2, either with scaling policies or with scheduled scaling.

Declaring a launch template with user data and an IAM Role

This snippet shows an AWS::EC2::LaunchTemplate resource that contains the instance configuration information for an Auto Scaling group. You specify values for the ImageId, InstanceType, SecurityGroups, UserData, and TagSpecifications properties. The SecurityGroups property specifies an existing EC2 security group and a new security group. The Ref function gets the ID of the AWS::EC2::SecurityGroup resource myNewEC2SecurityGroup that's declared elsewhere in the stack template.

The launch template includes a section for custom user data. You can pass in configuration tasks and scripts that run when an instance launches in this section. In this example, the user data installs the AWS Systems Manager Agent and starts the agent.

The launch template also includes an IAM role that allows applications running on instances in your Auto Scaling group to perform actions on your behalf. This example shows an AWS::IAM::Role resource for the launch template, which uses the IamInstanceProfile property to specify the IAM role. The Ref function gets the name of the AWS::IAM::InstanceProfile resource myInstanceProfile. To configure the permissions of the IAM role, you specify a value for the ManagedPolicyArns property.

JSON

{ "Resources":{ "myLaunchTemplate":{ "Type":"AWS::EC2::LaunchTemplate", "Properties":{ "LaunchTemplateName":{ "Fn::Sub": "${AWS::StackName}-launch-template" }, "LaunchTemplateData":{ "ImageId":"ami-02354e95b3example", "InstanceType":"t3.micro", "IamInstanceProfile":{ "Name":{ "Ref":"myInstanceProfile" } }, "SecurityGroupIds":[ { "Ref":"myNewEC2SecurityGroup" }, "sg-083cd3bfb8example" ], "UserData":{ "Fn::Base64":{ "Fn::Join": [ "", [ "#!/bin/bash\n", "cd /tmp\n", "sudo yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm\n", "sudo systemctl enable amazon-ssm-agent\n", "sudo systemctl start amazon-ssm-agent\n" ] ] } }, "TagSpecifications":[ { "ResourceType":"instance", "Tags":[ { "Key":"environment", "Value":"development" } ] }, { "ResourceType":"volume", "Tags":[ { "Key":"environment", "Value":"development" } ] } ] } } }, "myInstanceRole":{ "Type":"AWS::IAM::Role", "Properties":{ "RoleName":"InstanceRole", "AssumeRolePolicyDocument":{ "Version":"2012-10-17", "Statement":[ { "Effect":"Allow", "Principal":{ "Service":[ "ec2.amazonaws.com" ] }, "Action":[ "sts:AssumeRole" ] } ] }, "ManagedPolicyArns":[ "arn:aws:iam::aws:policy/myCustomerManagedPolicy" ] } }, "myInstanceProfile":{ "Type":"AWS::IAM::InstanceProfile", "Properties":{ "Path":"/", "Roles":[ { "Ref":"myInstanceRole" } ] } } } }

YAML

--- Resources: myLaunchTemplate: Type: AWS::EC2::LaunchTemplate Properties: LaunchTemplateName: !Sub ${AWS::StackName}-launch-template LaunchTemplateData: ImageId: ami-02354e95b3example InstanceType: t3.micro IamInstanceProfile: Name: !Ref myInstanceProfile SecurityGroupIds: - !Ref myNewEC2SecurityGroup - sg-083cd3bfb8example UserData: Fn::Base64:!Sub | #!/bin/bash cd /tmp sudo yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm sudo systemctl enable amazon-ssm-agent sudo systemctl start amazon-ssm-agent TagSpecifications: - ResourceType: instance Tags: - Key: environment Value: development - ResourceType: volume Tags: - Key: environment Value: development myInstanceRole: Type: AWS::IAM::Role Properties: RoleName: InstanceRole AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: 'Allow' Principal: Service: - 'ec2.amazonaws.com' Action: - 'sts:AssumeRole' ManagedPolicyArns: - 'arn:aws:iam::aws:policy/myCustomerManagedPolicy' myInstanceProfile: Type: AWS::IAM::InstanceProfile Properties: Path: '/' Roles: - !Ref myInstanceRole

See also

For more examples of launch templates, see the Examples section in the AWS::EC2::LaunchTemplate resource and the Examples section in the AWS::AutoScaling::AutoScalingGroup resource.

Declaring a single instance Auto Scaling group

This example shows an AWS::AutoScaling::AutoScalingGroup resource with a single instance to help you get started. The VPCZoneIdentifier property of the Auto Scaling group specifies a list of existing subnets in three different Availability Zones. You must specify the applicable subnet IDs from your account before you create your stack. The LaunchTemplate property references an AWS::EC2::LaunchTemplate resource with the logical name myLaunchTemplate that is defined elsewhere in your template.

JSON

"myASG" : { "Type" : "AWS::AutoScaling::AutoScalingGroup", "Properties" : { "VPCZoneIdentifier" : [ "subnetIdAz1", "subnetIdAz2", "subnetIdAz3" ], "LaunchTemplate" : { "LaunchTemplateId" : { "Ref" : "myLaunchTemplate" }, "Version" : { "Fn::GetAtt" : [ "myLaunchTemplate", "LatestVersionNumber" ] } }, "MaxSize" : "1", "MinSize" : "0", "DesiredCapacity" : "1" } }

YAML

myASG: Type: AWS::AutoScaling::AutoScalingGroup Properties: VPCZoneIdentifier: - subnetIdAz1 - subnetIdAz2 - subnetIdAz3 LaunchTemplate: LaunchTemplateId: !Ref myLaunchTemplate Version: !GetAtt myLaunchTemplate.LatestVersionNumber MaxSize: '1' MinSize: '0' DesiredCapacity: '1'

Declaring an Auto Scaling group with an attached load balancer

This example shows an AWS::AutoScaling::AutoScalingGroup resource for load balancing over multiple servers. It specifies the logical names of AWS resources declared elsewhere in the same template.

  1. The VPCZoneIdentifier property specifies the logical names of two AWS::EC2::Subnet resources where the Auto Scaling group's EC2 instances will be created: myPublicSubnet1 and myPublicSubnet2.

  2. The LaunchTemplate property specifies an AWS::EC2::LaunchTemplate resource with the logical name myLaunchTemplate.

  3. The TargetGroupARNs property lists the target groups for an Application Load Balancer or Network Load Balancer used to route traffic to the Auto Scaling group. In this example, one target group is specified, an AWS::ElasticLoadBalancingV2::TargetGroup resource with the logical name myTargetGroup.

JSON

"myServerGroup" : { "Type" : "AWS::AutoScaling::AutoScalingGroup", "Properties" : { "VPCZoneIdentifier" : [ { "Ref" : "myPublicSubnet1" }, { "Ref" : "myPublicSubnet2" } ], "LaunchTemplate" : { "LaunchTemplateId" : { "Ref" : "myLaunchTemplate" }, "Version" : { "Fn::GetAtt" : [ "myLaunchTemplate", "LatestVersionNumber" ] } }, "MaxSize" : "5", "MinSize" : "1", "TargetGroupARNs" : [ { "Ref" : "myTargetGroup" } ] } }

YAML

myServerGroup: Type: AWS::AutoScaling::AutoScalingGroup Properties: VPCZoneIdentifier: - !Ref myPublicSubnet1 - !Ref myPublicSubnet2 LaunchTemplate: LaunchTemplateId: !Ref myLaunchTemplate Version: !GetAtt myLaunchTemplate.LatestVersionNumber MaxSize: '5' MinSize: '1' TargetGroupARNs: - !Ref myTargetGroup

See also

For a detailed example that creates an Auto Scaling group with a target tracking scaling policy based on the ALBRequestCountPerTarget predefined metric for your Application Load Balancer, see the Examples section in the AWS::AutoScaling::ScalingPolicy resource.

Declaring an Auto Scaling group with notifications

This example shows an AWS::AutoScaling::AutoScalingGroup resource that sends Amazon SNS notifications when the specified events take place. The NotificationConfigurations property specifies the SNS topic where AWS CloudFormation sends a notification and the events that will cause AWS CloudFormation to send notifications. When the events specified by NotificationTypes occur, AWS CloudFormation will send a notification to the SNS topic specified by TopicARN. When you launch the stack, AWS CloudFormation creates an AWS::SNS::Subscription resource (snsTopicForAutoScalingGroup) that's declared within the same template.

The VPCZoneIdentifier property of the Auto Scaling group specifies a list of existing subnets in three different Availability Zones. You must specify the applicable subnet IDs from your account before you create your stack. The LaunchTemplate property references the logical name of an AWS::EC2::LaunchTemplate resource declared elsewhere in the same template.

JSON

"myASG" : { "Type" : "AWS::AutoScaling::AutoScalingGroup", "DependsOn": [ "snsTopicForAutoScalingGroup" ], "Properties" : { "VPCZoneIdentifier" : [ "subnetIdAz1", "subnetIdAz2", "subnetIdAz3" ], "LaunchTemplate" : { "LaunchTemplateId" : { "Ref" : "logicalName" }, "Version" : { "Fn::GetAtt" : [ "logicalName", "LatestVersionNumber" ] } }, "MaxSize" : "5", "MinSize" : "1", "NotificationConfigurations" : [ { "TopicARN" : { "Ref" : "snsTopicForAutoScalingGroup" }, "NotificationTypes" : [ "autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_LAUNCH_ERROR", "autoscaling:EC2_INSTANCE_TERMINATE", "autoscaling:EC2_INSTANCE_TERMINATE_ERROR", "autoscaling:TEST_NOTIFICATION" ] } ] } }

YAML

myASG: Type: AWS::AutoScaling::AutoScalingGroup DependsOn: - snsTopicForAutoScalingGroup Properties: VPCZoneIdentifier: - subnetIdAz1 - subnetIdAz2 - subnetIdAz3 LaunchTemplate: LaunchTemplateId: !Ref logicalName Version: !GetAtt logicalName.LatestVersionNumber MaxSize: '5' MinSize: '1' NotificationConfigurations: - TopicARN: !Ref snsTopicForAutoScalingGroup NotificationTypes: - autoscaling:EC2_INSTANCE_LAUNCH - autoscaling:EC2_INSTANCE_LAUNCH_ERROR - autoscaling:EC2_INSTANCE_TERMINATE - autoscaling:EC2_INSTANCE_TERMINATE_ERROR - autoscaling:TEST_NOTIFICATION

Declaring an Auto Scaling group with a CreationPolicy and an UpdatePolicy

The following example shows how to add CreationPolicy attribute and UpdatePolicy attributes to an AWS::AutoScaling::AutoScalingGroup resource.

The sample creation policy prevents the Auto Scaling group from reaching CREATE_COMPLETE status until AWS CloudFormation receives Count number of success signals when the group is ready. To signal that the Auto Scaling group is ready, a cfn-signal helper script added to the launch template's user data (not shown) is run on the instances. If the instances don't send a signal within the specified Timeout, CloudFormation assumes that the instances were not created, the resource creation fails, and CloudFormation rolls the stack back.

The sample update policy instructs CloudFormation to perform a rolling update using the AutoScalingRollingUpdate property. The rolling update makes changes to the Auto Scaling group in small batches (for this example, instance by instance) based on the MaxBatchSize and a pause time between batches of updates based on the PauseTime. The MinInstancesInService attribute specifies the minimum number of instances that must be in service within the Auto Scaling group while CloudFormation updates old instances.

The WaitOnResourceSignals attribute is set to true. CloudFormation must receive a signal from each new instance within the specified PauseTime before continuing the update. While the stack update is in progress, the following EC2 Auto Scaling processes are suspended: HealthCheck, ReplaceUnhealthy, AZRebalance, AlarmNotification, and ScheduledActions. Note: Don't suspend the Launch, Terminate, or AddToLoadBalancer (if the Auto Scaling group is being used with Elastic Load Balancing) process types because doing so can prevent the rolling update from functioning properly.

The VPCZoneIdentifier property of the Auto Scaling group specifies a list of existing subnets in three different Availability Zones. You must specify the applicable subnet IDs from your account before you create your stack. The LaunchTemplate property references the logical name of an AWS::EC2::LaunchTemplate resource declared elsewhere in the same template.

JSON

{ "Resources":{ "myASG":{ "CreationPolicy":{ "ResourceSignal":{ "Count":"3", "Timeout":"PT15M" } }, "UpdatePolicy":{ "AutoScalingRollingUpdate":{ "MinInstancesInService":"1", "MaxBatchSize":"1", "PauseTime":"PT12M5S", "WaitOnResourceSignals":"true", "SuspendProcesses":[ "HealthCheck", "ReplaceUnhealthy", "AZRebalance", "AlarmNotification", "ScheduledActions" ] } }, "Type":"AWS::AutoScaling::AutoScalingGroup", "Properties":{ "VPCZoneIdentifier":[ "subnetIdAz1", "subnetIdAz2", "subnetIdAz3" ], "LaunchTemplate":{ "LaunchTemplateId":{ "Ref":"logicalName" }, "Version":{ "Fn::GetAtt":[ "logicalName", "LatestVersionNumber" ] } }, "MaxSize":"5", "MinSize":"3" } } } }

YAML

--- Resources: myASG: CreationPolicy: ResourceSignal: Count: '3' Timeout: PT15M UpdatePolicy: AutoScalingRollingUpdate: MinInstancesInService: '1' MaxBatchSize: '1' PauseTime: PT12M5S WaitOnResourceSignals: true SuspendProcesses: - HealthCheck - ReplaceUnhealthy - AZRebalance - AlarmNotification - ScheduledActions Type: AWS::AutoScaling::AutoScalingGroup Properties: VPCZoneIdentifier: - subnetIdAz1 - subnetIdAz2 - subnetIdAz3 LaunchTemplate: LaunchTemplateId: !Ref logicalName Version: !GetAtt logicalName.LatestVersionNumber MaxSize: '5' MinSize: '3'

Declaring a step scaling policy with a CloudWatch alarm

This example shows an AWS::AutoScaling::ScalingPolicy resource that scales out the Auto Scaling group using a step scaling policy. The AdjustmentType property specifies ChangeInCapacity, which means that the ScalingAdjustment represents the number of instances to add (if ScalingAdjustment is positive) or delete (if it is negative). In this example, ScalingAdjustment is 1; therefore, the policy increments the number of EC2 instances in the group by 1 when the alarm threshold is breached.

The AWS::CloudWatch::Alarm resource CPUAlarmHigh specifies the scaling policy ASGScalingPolicyHigh as the action to run when the alarm is in an ALARM state (AlarmActions). The Dimensions property references the logical name of an AWS::AutoScaling::AutoScalingGroup resource declared elsewhere in the same template.

JSON

{ "Resources":{ "ASGScalingPolicyHigh":{ "Type":"AWS::AutoScaling::ScalingPolicy", "Properties":{ "AutoScalingGroupName":{ "Ref":"logicalName" }, "PolicyType":"StepScaling", "AdjustmentType":"ChangeInCapacity", "StepAdjustments":[ { "MetricIntervalLowerBound":0, "ScalingAdjustment":1 } ] } }, "CPUAlarmHigh":{ "Type":"AWS::CloudWatch::Alarm", "Properties":{ "EvaluationPeriods":"2", "Statistic":"Average", "Threshold":"90", "AlarmDescription":"Scale out if CPU > 90% for 2 minutes", "Period":"60", "AlarmActions":[ { "Ref":"ASGScalingPolicyHigh" } ], "Namespace":"AWS/EC2", "Dimensions":[ { "Name":"AutoScalingGroupName", "Value":{ "Ref":"logicalName" } } ], "ComparisonOperator":"GreaterThanThreshold", "MetricName":"CPUUtilization" } } } }

YAML

--- Resources: ASGScalingPolicyHigh: Type: AWS::AutoScaling::ScalingPolicy Properties: AutoScalingGroupName: !Ref logicalName PolicyType: StepScaling AdjustmentType: ChangeInCapacity StepAdjustments: - MetricIntervalLowerBound: 0 ScalingAdjustment: 1 CPUAlarmHigh: Type: AWS::CloudWatch::Alarm Properties: EvaluationPeriods: 2 Statistic: Average Threshold: 90 AlarmDescription: 'Scale out if CPU > 90% for 2 minutes' Period: 60 AlarmActions: - !Ref ASGScalingPolicyHigh Namespace: AWS/EC2 Dimensions: - Name: AutoScalingGroupName Value: !Ref logicalName ComparisonOperator: GreaterThanThreshold MetricName: CPUUtilization

See also

For more example templates for scaling policies, see the Examples section in the AWS::AutoScaling::ScalingPolicy resource.

Mixed instances group examples

Declaring an Auto Scaling group that uses a mixed instances policy and attribute-based instance type selection

This example shows an AWS::AutoScaling::AutoScalingGroup resource that contains the information to launch a mixed instances group using attribute-based instance type selection. You specify the minimum and maximum values for the VCpuCount property and the minimum value for the MemoryMiB property. Any instance types used by the Auto Scaling group must match your required instance attributes.

The VPCZoneIdentifier property of the Auto Scaling group specifies a list of existing subnets in three different Availability Zones. You must specify the applicable subnet IDs from your account before you create your stack. The LaunchTemplate property references the logical name of an AWS::EC2::LaunchTemplate resource declared elsewhere in the same template.

JSON

{ "Resources":{ "myASG":{ "Type":"AWS::AutoScaling::AutoScalingGroup", "Properties":{ "VPCZoneIdentifier":[ "subnetIdAz1", "subnetIdAz2", "subnetIdAz3" ], "MixedInstancesPolicy":{ "LaunchTemplate":{ "LaunchTemplateSpecification":{ "LaunchTemplateId":{ "Ref":"logicalName" }, "Version":{ "Fn::GetAtt":[ "logicalName", "LatestVersionNumber" ] } }, "Overrides":[ { "InstanceRequirements":{ "VCpuCount":{ "Min":2, "Max":4 }, "MemoryMiB":{ "Min":2048 } } } ] } }, "MaxSize":"5", "MinSize":"1", "DesiredCapacity":"3" } } } }

YAML

--- Resources: myASG: Type: AWS::AutoScaling::AutoScalingGroup Properties: VPCZoneIdentifier: - subnetIdAz1 - subnetIdAz2 - subnetIdAz3 MixedInstancesPolicy: LaunchTemplate: LaunchTemplateSpecification: LaunchTemplateId: !Ref logicalName Version: !GetAtt logicalName.LatestVersionNumber Overrides: - InstanceRequirements: VCpuCount: Min: 2 Max: 4 MemoryMiB: Min: 2048 MaxSize: '5' MinSize: '1' DesiredCapacity: '3'

Launch configuration examples

Declaring a launch configuration

This example shows an AWS::AutoScaling::LaunchConfiguration resource for an Auto Scaling group where you specify values for the ImageId, InstanceType, and SecurityGroups properties. The SecurityGroups property specifies both the logical name of an AWS::EC2::SecurityGroup resource that's specified elsewhere in the template, and an existing EC2 security group named myExistingEC2SecurityGroup.

JSON

"mySimpleConfig" : { "Type" : "AWS::AutoScaling::LaunchConfiguration", "Properties" : { "ImageId" : "ami-02354e95b3example", "InstanceType" : "t3.micro", "SecurityGroups" : [ { "Ref" : "logicalName" }, "myExistingEC2SecurityGroup" ] } }

YAML

mySimpleConfig: Type: AWS::AutoScaling::LaunchConfiguration Properties: ImageId: ami-02354e95b3example InstanceType: t3.micro SecurityGroups: - !Ref logicalName - myExistingEC2SecurityGroup

Declaring an Auto Scaling group that uses a launch configuration

This example shows an AWS::AutoScaling::AutoScalingGroup resource with a single instance. The VPCZoneIdentifier property of the Auto Scaling group specifies a list of existing subnets in three different Availability Zones. You must specify the applicable subnet IDs from your account before you create your stack. The LaunchConfigurationName property references an AWS::AutoScaling::LaunchConfiguration resource with the logical name mySimpleConfig that is defined in your template.

JSON

"myASG" : { "Type" : "AWS::AutoScaling::AutoScalingGroup", "Properties" : { "VPCZoneIdentifier" : [ "subnetIdAz1", "subnetIdAz2", "subnetIdAz3" ], "LaunchConfigurationName" : { "Ref" : "mySimpleConfig" }, "MaxSize" : "1", "MinSize" : "0", "DesiredCapacity" : "1" } }

YAML

myASG: Type: AWS::AutoScaling::AutoScalingGroup Properties: VPCZoneIdentifier: - subnetIdAz1 - subnetIdAz2 - subnetIdAz3 LaunchConfigurationName: !Ref mySimpleConfig MaxSize: '1' MinSize: '0' DesiredCapacity: '1'

Application Auto Scaling template examples

This section provides AWS CloudFormation template examples for Application Auto Scaling scaling policies and scheduled actions for different AWS resources.

Important

When an Application Auto Scaling snippet is included in the template, you might need to declare a dependency on the specific scalable resource that's created through the template using the DependsOn attribute. This overrides the default parallelism and directs AWS CloudFormation to operate on resources in a specified order. Otherwise, the scaling configuration might be applied before the resource has been set up completely.

Declaring a scaling policy for an AppStream fleet

This snippet shows how to create a policy and apply it to an AWS::AppStream::Fleet resource using the AWS::ApplicationAutoScaling::ScalingPolicy resource. The AWS::ApplicationAutoScaling::ScalableTarget resource declares a scalable target to which this policy is applied. Application Auto Scaling can scale the number of fleet instances at a minimum of 1 instance and a maximum of 20. The policy keeps the average capacity utilization of the fleet at 75 percent, with scale-out and scale-in cooldown periods of 300 seconds (5 minutes).

It uses the Fn::Join and Ref intrinsic functions to construct the ResourceId property with the logical name of the AWS::AppStream::Fleet resource that's specified in the same template.

JSON

{ "Resources" : { "ScalableTarget" : { "Type" : "AWS::ApplicationAutoScaling::ScalableTarget", "Properties" : { "MaxCapacity" : 20, "MinCapacity" : 1, "RoleARN" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/appstream.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_AppStreamFleet" }, "ServiceNamespace" : "appstream", "ScalableDimension" : "appstream:fleet:DesiredCapacity", "ResourceId" : { "Fn::Join" : [ "/", [ "fleet", { "Ref" : "logicalName" } ] ] } } }, "ScalingPolicyAppStreamFleet" : { "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties" : { "PolicyName" : { "Fn::Sub" : "${AWS::StackName}-target-tracking-cpu75" }, "PolicyType" : "TargetTrackingScaling", "ServiceNamespace" : "appstream", "ScalableDimension" : "appstream:fleet:DesiredCapacity", "ResourceId" : { "Fn::Join" : [ "/", [ "fleet", { "Ref" : "logicalName" } ] ] }, "TargetTrackingScalingPolicyConfiguration" : { "TargetValue" : 75, "PredefinedMetricSpecification" : { "PredefinedMetricType" : "AppStreamAverageCapacityUtilization" }, "ScaleInCooldown" : 300, "ScaleOutCooldown" : 300 } } } } }

YAML

--- Resources: ScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 20 MinCapacity: 1 RoleARN: Fn::Sub: 'arn:aws:iam::${AWS::AccountId}:role/aws-service-role/appstream.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_AppStreamFleet' ServiceNamespace: appstream ScalableDimension: appstream:fleet:DesiredCapacity ResourceId: !Join - / - - fleet - !Ref logicalName ScalingPolicyAppStreamFleet: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: !Sub ${AWS::StackName}-target-tracking-cpu75 PolicyType: TargetTrackingScaling ServiceNamespace: appstream ScalableDimension: appstream:fleet:DesiredCapacity ResourceId: !Join - / - - fleet - !Ref logicalName TargetTrackingScalingPolicyConfiguration: TargetValue: 75 PredefinedMetricSpecification: PredefinedMetricType: AppStreamAverageCapacityUtilization ScaleInCooldown: 300 ScaleOutCooldown: 300

Declaring a scaling policy for an Aurora DB cluster

In this snippet, you register an AWS::RDS::DBCluster resource. The AWS::ApplicationAutoScaling::ScalableTarget resource indicates that the DB cluster should be dynamically scaled to have from one to eight Aurora Replicas. You also apply a target tracking scaling policy to the cluster using the AWS::ApplicationAutoScaling::ScalingPolicy resource.

In this configuration, the RDSReaderAverageCPUUtilization predefined metric is used to adjust an Aurora DB cluster based on an average CPU utilization of 40 percent across all Aurora Replicas in that Aurora DB cluster. The configuration provides a scale-in cooldown period of 10 minutes and a scale-out cooldown period of 5 minutes.

This example uses the Fn::Sub intrinsic function to construct the ResourceId property with the logical name of the AWS::RDS::DBCluster resource that is specified in the same template.

JSON

{ "Resources" : { "ScalableTarget" : { "Type" : "AWS::ApplicationAutoScaling::ScalableTarget", "Properties" : { "MaxCapacity" : 8, "MinCapacity" : 1, "RoleARN" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/rds.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_RDSCluster" }, "ServiceNamespace" : "rds", "ScalableDimension" : "rds:cluster:ReadReplicaCount", "ResourceId" : { "Fn::Sub" : "cluster:${logicalName}" } } }, "ScalingPolicyDBCluster" : { "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties" : { "PolicyName" : { "Fn::Sub" : "${AWS::StackName}-target-tracking-cpu40" }, "PolicyType" : "TargetTrackingScaling", "ServiceNamespace" : "rds", "ScalableDimension" : "rds:cluster:ReadReplicaCount", "ResourceId" : { "Fn::Sub" : "cluster:${logicalName}" }, "TargetTrackingScalingPolicyConfiguration" : { "TargetValue" : 40, "PredefinedMetricSpecification" : { "PredefinedMetricType" : "RDSReaderAverageCPUUtilization" }, "ScaleInCooldown" : 600, "ScaleOutCooldown" : 300 } } } } }

YAML

--- Resources: ScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 8 MinCapacity: 1 RoleARN: Fn::Sub: 'arn:aws:iam::${AWS::AccountId}:role/aws-service-role/rds.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_RDSCluster' ServiceNamespace: rds ScalableDimension: rds:cluster:ReadReplicaCount ResourceId: !Sub cluster:${logicalName} ScalingPolicyDBCluster: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: !Sub ${AWS::StackName}-target-tracking-cpu40 PolicyType: TargetTrackingScaling ServiceNamespace: rds ScalableDimension: rds:cluster:ReadReplicaCount ResourceId: !Sub cluster:${logicalName} TargetTrackingScalingPolicyConfiguration: TargetValue: 40 PredefinedMetricSpecification: PredefinedMetricType: RDSReaderAverageCPUUtilization ScaleInCooldown: 600 ScaleOutCooldown: 300

Declaring a scaling policy for a DynamoDB table

This snippet shows how to create a policy with the TargetTrackingScaling policy type and apply it to an AWS::DynamoDB::Table resource using the AWS::ApplicationAutoScaling::ScalingPolicy resource. The AWS::ApplicationAutoScaling::ScalableTarget resource declares a scalable target to which this policy is applied, with a minimum of five write capacity units and a maximum of 15. The scaling policy scales the table's write capacity throughput to maintain the target utilization at 50 percent based on the DynamoDBWriteCapacityUtilization predefined metric.

It uses the Fn::Join and Ref intrinsic functions to construct the ResourceId property with the logical name of the AWS::DynamoDB::Table resource that's specified in the same template.

Note

For more information about how to create an AWS CloudFormation template for DynamoDB resources, see the blog post How to use AWS CloudFormation to configure auto scaling for Amazon DynamoDB tables and indexes on the AWS Database Blog.

JSON

{ "Resources" : { "WriteCapacityScalableTarget" : { "Type" : "AWS::ApplicationAutoScaling::ScalableTarget", "Properties" : { "MaxCapacity" : 15, "MinCapacity" : 5, "RoleARN" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable" }, "ServiceNamespace" : "dynamodb", "ScalableDimension" : "dynamodb:table:WriteCapacityUnits", "ResourceId" : { "Fn::Join" : [ "/", [ "table", { "Ref" : "logicalName" } ] ] } } }, "WriteScalingPolicy" : { "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties" : { "PolicyName" : "WriteScalingPolicy", "PolicyType" : "TargetTrackingScaling", "ScalingTargetId" : { "Ref" : "WriteCapacityScalableTarget" }, "TargetTrackingScalingPolicyConfiguration" : { "TargetValue" : 50.0, "ScaleInCooldown" : 60, "ScaleOutCooldown" : 60, "PredefinedMetricSpecification" : { "PredefinedMetricType" : "DynamoDBWriteCapacityUtilization" } } } } } }

YAML

--- Resources: WriteCapacityScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 15 MinCapacity: 5 RoleARN: Fn::Sub: 'arn:aws:iam::${AWS::AccountId}:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable' ServiceNamespace: dynamodb ScalableDimension: dynamodb:table:WriteCapacityUnits ResourceId: !Join - / - - table - !Ref logicalName WriteScalingPolicy: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: WriteScalingPolicy PolicyType: TargetTrackingScaling ScalingTargetId: !Ref WriteCapacityScalableTarget TargetTrackingScalingPolicyConfiguration: TargetValue: 50.0 ScaleInCooldown: 60 ScaleOutCooldown: 60 PredefinedMetricSpecification: PredefinedMetricType: DynamoDBWriteCapacityUtilization

Declaring a scaling policy for an Amazon ECS service (metrics: average CPU and memory)

This snippet shows how to create a policy and apply it to an AWS::ECS::Service resource using the AWS::ApplicationAutoScaling::ScalingPolicy resource. The AWS::ApplicationAutoScaling::ScalableTarget resource declares a scalable target to which this policy is applied. Application Auto Scaling can scale the number of tasks at a minimum of 1 task and a maximum of 6.

It creates two scaling policies with the TargetTrackingScaling policy type. The policies are used to scale the ECS service based on the service's average CPU and memory usage. It uses the Fn::Join and Ref intrinsic functions to construct the ResourceId property with the logical names of the AWS::ECS::Cluster (myContainerCluster) and AWS::ECS::Service (myService) resources that are specified in the same template.

JSON

{ "Resources" : { "ECSScalableTarget" : { "Type" : "AWS::ApplicationAutoScaling::ScalableTarget", "Properties" : { "MaxCapacity" : "6", "MinCapacity" : "1", "RoleARN" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService" }, "ServiceNamespace" : "ecs", "ScalableDimension" : "ecs:service:DesiredCount", "ResourceId" : { "Fn::Join" : [ "/", [ "service", { "Ref" : "myContainerCluster" }, { "Fn::GetAtt" : [ "myService", "Name" ] } ] ] } } }, "ServiceScalingPolicyCPU" : { "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties" : { "PolicyName" : { "Fn::Sub" : "${AWS::StackName}-target-tracking-cpu70" }, "PolicyType" : "TargetTrackingScaling", "ScalingTargetId" : { "Ref" : "ECSScalableTarget" }, "TargetTrackingScalingPolicyConfiguration" : { "TargetValue" : 70.0, "ScaleInCooldown" : 180, "ScaleOutCooldown" : 60, "PredefinedMetricSpecification" : { "PredefinedMetricType" : "ECSServiceAverageCPUUtilization" } } } }, "ServiceScalingPolicyMem" : { "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties" : { "PolicyName" : { "Fn::Sub" : "${AWS::StackName}-target-tracking-mem90" }, "PolicyType" : "TargetTrackingScaling", "ScalingTargetId" : { "Ref" : "ECSScalableTarget" }, "TargetTrackingScalingPolicyConfiguration" : { "TargetValue" : 90.0, "ScaleInCooldown" : 180, "ScaleOutCooldown" : 60, "PredefinedMetricSpecification" : { "PredefinedMetricType" : "ECSServiceAverageMemoryUtilization" } } } } } }

YAML

--- Resources: ECSScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 6 MinCapacity: 1 RoleARN: Fn::Sub: 'arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService' ServiceNamespace: ecs ScalableDimension: 'ecs:service:DesiredCount' ResourceId: !Join - / - - service - !Ref myContainerCluster - !GetAtt myService.Name ServiceScalingPolicyCPU: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: !Sub ${AWS::StackName}-target-tracking-cpu70 PolicyType: TargetTrackingScaling ScalingTargetId: !Ref ECSScalableTarget TargetTrackingScalingPolicyConfiguration: TargetValue: 70.0 ScaleInCooldown: 180 ScaleOutCooldown: 60 PredefinedMetricSpecification: PredefinedMetricType: ECSServiceAverageCPUUtilization ServiceScalingPolicyMem: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: !Sub ${AWS::StackName}-target-tracking-mem90 PolicyType: TargetTrackingScaling ScalingTargetId: !Ref ECSScalableTarget TargetTrackingScalingPolicyConfiguration: TargetValue: 90.0 ScaleInCooldown: 180 ScaleOutCooldown: 60 PredefinedMetricSpecification: PredefinedMetricType: ECSServiceAverageMemoryUtilization

Declaring a scaling policy for an Amazon ECS service (metric: average request count per target)

The following example applies a target tracking scaling policy with the ALBRequestCountPerTarget predefined metric to an ECS service. The policy is used to add capacity to the ECS service when the request count per target (per minute) exceeds the target value. Because the value of DisableScaleIn is set to true, the target tracking policy won't remove capacity from the scalable target.

It uses the Fn::Join and Fn::GetAtt intrinsic functions to construct the ResourceLabel property with the logical names of the AWS::ElasticLoadBalancingV2::LoadBalancer (myLoadBalancer) and AWS::ElasticLoadBalancingV2::TargetGroup (myTargetGroup) resources that are specified in the same template.

The MaxCapacity and MinCapacity properties of the scalable target and the TargetValue property of the scaling policy reference parameter values that you pass to the template when creating or updating a stack.

JSON

{ "Resources" : { "ECSScalableTarget" : { "Type" : "AWS::ApplicationAutoScaling::ScalableTarget", "Properties" : { "MaxCapacity" : { "Ref" : "MaxCount" }, "MinCapacity" : { "Ref" : "MinCount" }, "RoleARN" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService" }, "ServiceNamespace" : "ecs", "ScalableDimension" : "ecs:service:DesiredCount", "ResourceId" : { "Fn::Join" : [ "/", [ "service", { "Ref" : "myContainerCluster" }, { "Fn::GetAtt" : [ "myService", "Name" ] } ] ] } } }, "ServiceScalingPolicyALB" : { "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties" : { "PolicyName" : "alb-requests-per-target-per-minute", "PolicyType" : "TargetTrackingScaling", "ScalingTargetId" : { "Ref" : "ECSScalableTarget" }, "TargetTrackingScalingPolicyConfiguration" : { "TargetValue" : { "Ref" : "ALBPolicyTargetValue" }, "ScaleInCooldown" : 180, "ScaleOutCooldown" : 30, "DisableScaleIn" : true, "PredefinedMetricSpecification" : { "PredefinedMetricType" : "ALBRequestCountPerTarget", "ResourceLabel" : { "Fn::Join" : [ "/", [ { "Fn::GetAtt" : [ "myLoadBalancer", "LoadBalancerFullName" ] }, { "Fn::GetAtt" : [ "myTargetGroup", "TargetGroupFullName" ] } ] ] } } } } } } }

YAML

--- Resources: ECSScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: !Ref MaxCount MinCapacity: !Ref MinCount RoleARN: Fn::Sub: 'arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService' ServiceNamespace: ecs ScalableDimension: 'ecs:service:DesiredCount' ResourceId: !Join - / - - service - !Ref myContainerCluster - !GetAtt myService.Name ServiceScalingPolicyALB: Type: AWS::ApplicationAutoScaling::ScalingPolicy Properties: PolicyName: alb-requests-per-target-per-minute PolicyType: TargetTrackingScaling ScalingTargetId: !Ref ECSScalableTarget TargetTrackingScalingPolicyConfiguration: TargetValue: !Ref ALBPolicyTargetValue ScaleInCooldown: 180 ScaleOutCooldown: 30 DisableScaleIn: true PredefinedMetricSpecification: PredefinedMetricType: ALBRequestCountPerTarget ResourceLabel: !Join - '/' - - !GetAtt myLoadBalancer.LoadBalancerFullName - !GetAtt myTargetGroup.TargetGroupFullName

Declaring a scheduled action with a cron expression for a Lambda function

This snippet registers the provisioned concurrency for a function alias (AWS::Lambda::Alias) named BLUE using the AWS::ApplicationAutoScaling::ScalableTarget resource. It also creates a scheduled action with a recurring schedule using a cron expression. The time zone for the recurring schedule is UTC.

It uses the Fn::Join and Ref intrinsic functions in the RoleARN property to specify the ARN of the service-linked role. It uses the Fn::Sub intrinsic function to construct the ResourceId property with the logical name of the AWS::Lambda::Function or AWS::Serverless::Function resource that is specified in the same template.

Note

You can't allocate provisioned concurrency on an alias that points to the unpublished version ($LATEST).

For more information about how to create an AWS CloudFormation template for Lambda resources, see the blog post Scheduling AWS Lambda Provisioned Concurrency for recurring peak usage on the AWS Compute Blog.

JSON

{ "ScalableTarget" : { "Type" : "AWS::ApplicationAutoScaling::ScalableTarget", "Properties" : { "MaxCapacity" : 250, "MinCapacity" : 0, "RoleARN" : { "Fn::Join" : [ ":", [ "arn:aws:iam:", { "Ref" : "AWS::AccountId" }, "role/aws-service-role/lambda.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_LambdaConcurrency" ] ] }, "ServiceNamespace" : "lambda", "ScalableDimension" : "lambda:function:ProvisionedConcurrency", "ResourceId" : { "Fn::Sub" : "function:${logicalName}:BLUE" }, "ScheduledActions" : [ { "ScalableTargetAction" : { "MinCapacity" : "250" }, "ScheduledActionName" : "my-scale-out-scheduled-action", "Schedule" : "cron(0 18 * * ? *)", "EndTime" : "2022-12-31T12:00:00.000Z" } ] } } }

YAML

ScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 250 MinCapacity: 0 RoleARN: !Join - ':' - - 'arn:aws:iam:' - !Ref 'AWS::AccountId' - role/aws-service-role/lambda.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_LambdaConcurrency ServiceNamespace: lambda ScalableDimension: lambda:function:ProvisionedConcurrency ResourceId: !Sub function:${logicalName}:BLUE ScheduledActions: - ScalableTargetAction: MinCapacity: 250 ScheduledActionName: my-scale-out-scheduled-action Schedule: 'cron(0 18 * * ? *)' EndTime: '2022-12-31T12:00:00.000Z'

Declaring a scheduled action with an at expression for a Spot Fleet

This snippet shows how to create two scheduled actions that occur only once for an AWS::EC2::SpotFleet resource using the AWS::ApplicationAutoScaling::ScalableTarget resource. The time zone for each one-time scheduled action is UTC.

It uses the Fn::Join and Ref intrinsic functions to construct the ResourceId property with the logical name of the AWS::EC2::SpotFleet resource that is specified in the same template.

Note

The Spot Fleet request must have a request type of maintain. Automatic scaling isn't supported for one-time requests or Spot blocks.

JSON

{ "Resources" : { "SpotFleetScalableTarget" : { "Type" : "AWS::ApplicationAutoScaling::ScalableTarget", "Properties" : { "MaxCapacity" : 0, "MinCapacity" : 0, "RoleARN" : { "Fn::Sub" : "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ec2.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_EC2SpotFleetRequest" }, "ServiceNamespace" : "ec2", "ScalableDimension" : "ec2:spot-fleet-request:TargetCapacity", "ResourceId" : { "Fn::Join" : [ "/", [ "spot-fleet-request", { "Ref" : "logicalName" } ] ] }, "ScheduledActions" : [ { "ScalableTargetAction" : { "MaxCapacity" : "10", "MinCapacity" : "10" }, "ScheduledActionName" : "my-scale-out-scheduled-action", "Schedule" : "at(2022-05-20T13:00:00)" }, { "ScalableTargetAction" : { "MaxCapacity" : "0", "MinCapacity" : "0" }, "ScheduledActionName" : "my-scale-in-scheduled-action", "Schedule" : "at(2022-05-20T21:00:00)" } ] } } } }

YAML

--- Resources: SpotFleetScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 0 MinCapacity: 0 RoleARN: Fn::Sub: 'arn:aws:iam::${AWS::AccountId}:role/aws-service-role/ec2.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_EC2SpotFleetRequest' ServiceNamespace: ec2 ScalableDimension: 'ec2:spot-fleet-request:TargetCapacity' ResourceId: !Join - / - - spot-fleet-request - !Ref logicalName ScheduledActions: - ScalableTargetAction: MaxCapacity: 10 MinCapacity: 10 ScheduledActionName: my-scale-out-scheduled-action Schedule: 'at(2022-05-20T13:00:00)' - ScalableTargetAction: MaxCapacity: 0 MinCapacity: 0 ScheduledActionName: my-scale-in-scheduled-action Schedule: 'at(2022-05-20T21:00:00)'