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 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 is specified in the template, and an existing EC2 security group named myExistingEC2SecurityGroup.

JSON

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

YAML

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

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 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" }, "MinSize" : "0", "MaxSize" : "1", "DesiredCapacity" : "1" } }

YAML

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

Declaring an Auto Scaling group with load balancing

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 LaunchConfigurationName property specifies an AWS::AutoScaling::LaunchConfiguration resource with the logical name mySimpleConfig.

  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" } ], "LaunchConfigurationName" : { "Ref" : "mySimpleConfig" }, "MinSize" : "1", "MaxSize" : "5", "HealthCheckGracePeriod" : 300, "MaxInstanceLifetime" : 2592000, "TargetGroupARNs" : [ { "Ref" : "myTargetGroup" } ] } }

YAML

myServerGroup: Type: AWS::AutoScaling::AutoScalingGroup Properties: VPCZoneIdentifier: - !Ref myPublicSubnet1 - !Ref myPublicSubnet2 LaunchConfigurationName: !Ref mySimpleConfig MinSize: '1' MaxSize: '5' HealthCheckGracePeriod: 300 MaxInstanceLifetime: 2592000 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 a scaling policy with a CloudWatch alarm

This example shows an AWS::AutoScaling::ScalingPolicy resource that scales out the Auto Scaling group using a simple 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 myScaleOutPolicy as the action to run when the alarm is in an ALARM state (AlarmActions).

JSON

"myScaleOutPolicy" : { "Type" : "AWS::AutoScaling::ScalingPolicy", "Properties" : { "AdjustmentType" : "ChangeInCapacity", "AutoScalingGroupName" : { "Ref" : "logicalName" }, "ScalingAdjustment" : "1" } }, "CPUAlarmHigh" : { "Type" : "AWS::CloudWatch::Alarm", "Properties" : { "EvaluationPeriods" : "1", "Statistic" : "Average", "Threshold" : "10", "AlarmDescription" : "Alarm if CPU too high or metric disappears indicating instance is down", "Period" : "60", "AlarmActions" : [ { "Ref" : "myScaleOutPolicy" } ], "Namespace" : "AWS/EC2", "Dimensions" : [ { "Name" : "AutoScalingGroupName", "Value" : { "Ref" : "logicalName" } } ], "ComparisonOperator" : "GreaterThanThreshold", "MetricName" : "CPUUtilization" } }

YAML

myScaleOutPolicy: Type: AWS::AutoScaling::ScalingPolicy Properties: AdjustmentType: ChangeInCapacity AutoScalingGroupName: !Ref logicalName ScalingAdjustment: '1' CPUAlarmHigh: Type: AWS::CloudWatch::Alarm Properties: EvaluationPeriods: '1' Statistic: Average Threshold: '10' AlarmDescription: Alarm if CPU too high or metric disappears indicating instance is down Period: '60' AlarmActions: - !Ref myScaleOutPolicy Namespace: AWS/EC2 Dimensions: - Name: AutoScalingGroupName Value: Ref: logicalName ComparisonOperator: GreaterThanThreshold MetricName: CPUUtilization

See also

For example templates for the TargetTrackingScaling and StepScaling policy types, see the Examples section in the AWS::AutoScaling::ScalingPolicy resource.

Declaring an Auto Scaling group with a launch template and 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 AvailabilityZones and VPCZoneIdentifier properties of the Auto Scaling group reference parameter values that you pass to the template when creating or updating a 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" : { "AvailabilityZones" : { "Ref" : "AZs" }, "VPCZoneIdentifier" : { "Ref" : "Subnets" }, "LaunchTemplate" : { "LaunchTemplateId" : { "Ref" : "logicalName" }, "Version" : { "Fn::GetAtt" : [ "logicalName", "LatestVersionNumber" ] } }, "MinSize" : "1", "MaxSize" : "5", "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: AvailabilityZones: !Ref AZs VPCZoneIdentifier: !Ref Subnets LaunchTemplate: LaunchTemplateId: !Ref logicalName Version: !GetAtt logicalName.LatestVersionNumber MinSize: '1' MaxSize: '5' 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

See also

For more examples that specify a launch template for an Auto Scaling group, see the Examples section in the AWS::AutoScaling::AutoScalingGroup resource.

Declaring an Auto Scaling group with an UpdatePolicy

The following example specifies an UpdatePolicy attribute for an Auto Scaling group. 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. To signal the Auto Scaling group, a cfn-signal helper script (not shown) is run on each instance. While the stack update is in progress, the following EC2 Auto Scaling processes are suspended: HealthCheck, ReplaceUnhealthy, AZRebalance, AlarmNotification, and ScheduledActions. Note: Do not 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.

JSON

"myASG" : { "UpdatePolicy" : { "AutoScalingRollingUpdate" : { "MinInstancesInService" : "1", "MaxBatchSize" : "1", "PauseTime" : "PT12M5S", "WaitOnResourceSignals" : "true", "SuspendProcesses" : [ "HealthCheck", "ReplaceUnhealthy", "AZRebalance", "AlarmNotification", "ScheduledActions" ] } }, "Type" : "AWS::AutoScaling::AutoScalingGroup", "Properties" : { "AvailabilityZones" : { "Ref" : "AZs" }, "VPCZoneIdentifier" : { "Ref" : "Subnets" }, "LaunchConfigurationName" : { "Ref" : "logicalName" }, "MaxSize" : "5", "MinSize" : "1" } }

YAML

myASG: UpdatePolicy: AutoScalingRollingUpdate: MinInstancesInService: '1' MaxBatchSize: '1' PauseTime: PT12M5S WaitOnResourceSignals: true SuspendProcesses: - HealthCheck - ReplaceUnhealthy - AZRebalance - AlarmNotification - ScheduledActions Type: AWS::AutoScaling::AutoScalingGroup Properties: AvailabilityZones: !Ref AZs VPCZoneIdentifier: !Ref Subnets LaunchConfigurationName: !Ref logicalName MaxSize: '5' MinSize: '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 should declare a dependency on the specific scalable resource that is 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 Aurora DB cluster

In this snippet, you register an existing AWS::RDS::DBCluster resource named my-db-cluster. 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.

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" : "cluster:my-db-cluster" } }, "ScalingPolicyDBCluster" : { "Type" : "AWS::ApplicationAutoScaling::ScalingPolicy", "Properties" : { "PolicyName" : { "Fn::Sub" : "${AWS::StackName}-target-tracking-cpu40" }, "PolicyType" : "TargetTrackingScaling", "ServiceNamespace" : "rds", "ScalableDimension" : "rds:cluster:ReadReplicaCount", "ResourceId" : "cluster:my-db-cluster", "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: 'cluster:my-db-cluster' ScalingPolicyDBCluster: Type: 'AWS::ApplicationAutoScaling::ScalingPolicy' Properties: PolicyName: !Sub ${AWS::StackName}-target-tracking-cpu40 PolicyType: TargetTrackingScaling ServiceNamespace: rds ScalableDimension: 'rds:cluster:ReadReplicaCount' ResourceId: 'cluster:my-db-cluster' 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 is 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

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 2.

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" : "2", "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: '2' 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

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 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.

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).

Note

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" : 0, "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" : [ { "EndTime" : "2020-12-31T12:00:00.000Z", "ScalableTargetAction" : { "MaxCapacity" : "500", "MinCapacity" : "50" }, "ScheduledActionName" : "First", "Schedule" : "cron(0 18 * * ? *)" } ] } } }

YAML

ScalableTarget: Type: AWS::ApplicationAutoScaling::ScalableTarget Properties: MaxCapacity: 0 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: - EndTime: '2020-12-31T12:00:00.000Z' ScalableTargetAction: MaxCapacity: '500' MinCapacity: '50' ScheduledActionName: First Schedule: 'cron(0 18 * * ? *)'

Declaring a scheduled action for a Spot Fleet

This snippet shows how to create a scheduled action and apply it to an AWS::EC2::SpotFleet resource using the AWS::ApplicationAutoScaling::ScalableTarget resource. 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 is not 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" : [ { "EndTime" : "2020-12-31T12:00:00.000Z", "ScalableTargetAction" : { "MaxCapacity" : "20", "MinCapacity" : "5" }, "ScheduledActionName" : "First", "Schedule" : "cron(0 18 * * ? *)" } ] } } } }

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: - EndTime: '2020-12-31T12:00:00.000Z' ScalableTargetAction: MaxCapacity: '20' MinCapacity: '5' ScheduledActionName: First Schedule: 'cron(0 18 * * ? *)'