Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

Use EnableMetricsCollection with an AWS SDK or CLI

Focus mode
Use EnableMetricsCollection with an AWS SDK or CLI - Amazon EC2 Auto Scaling

The following code examples show how to use EnableMetricsCollection.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example:

.NET
SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/// <summary> /// Enable the collection of metric data for an Auto Scaling group. /// </summary> /// <param name="groupName">The name of the Auto Scaling group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> EnableMetricsCollectionAsync(string groupName) { var listMetrics = new List<string> { "GroupMaxSize", }; var collectionRequest = new EnableMetricsCollectionRequest { AutoScalingGroupName = groupName, Metrics = listMetrics, Granularity = "1Minute", }; var response = await _amazonAutoScaling.EnableMetricsCollectionAsync(collectionRequest); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
C++
SDK for C++
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig); Aws::AutoScaling::Model::EnableMetricsCollectionRequest request; request.SetAutoScalingGroupName(groupName); request.AddMetrics("GroupMinSize"); request.AddMetrics("GroupMaxSize"); request.AddMetrics("GroupDesiredCapacity"); request.AddMetrics("GroupInServiceInstances"); request.AddMetrics("GroupTotalInstances"); request.SetGranularity("1Minute"); Aws::AutoScaling::Model::EnableMetricsCollectionOutcome outcome = autoScalingClient.EnableMetricsCollection(request); if (outcome.IsSuccess()) { std::cout << "Auto Scaling metrics have been enabled." << std::endl; } else { std::cerr << "Error with AutoScaling::EnableMetricsCollection. " << outcome.GetError().GetMessage() << std::endl; }
CLI
AWS CLI

Example 1: To enable metrics collection for an Auto Scaling group

This example enables data collection for the specified Auto Scaling group.

aws autoscaling enable-metrics-collection \ --auto-scaling-group-name my-asg \ --granularity "1Minute"

This command produces no output.

For more information, see Monitoring CloudWatch metrics for your Auto Scaling groups and instances in the Amazon EC2 Auto Scaling User Guide.

Example 2: To collect data for the specified metric for an Auto Scaling group

To collect data for a specific metric, use the --metrics option.

aws autoscaling enable-metrics-collection \ --auto-scaling-group-name my-asg \ --metrics GroupDesiredCapacity --granularity "1Minute"

This command produces no output.

For more information, see Monitoring CloudWatch metrics for your Auto Scaling groups and instances in the Amazon EC2 Auto Scaling User Guide.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

public static void enableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) { try { EnableMetricsCollectionRequest collectionRequest = EnableMetricsCollectionRequest.builder() .autoScalingGroupName(groupName) .metrics("GroupMaxSize") .granularity("1Minute") .build(); autoScalingClient.enableMetricsCollection(collectionRequest); System.out.println("The enable metrics collection operation was successful"); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun enableMetricsCollection(groupName: String?) { val collectionRequest = EnableMetricsCollectionRequest { autoScalingGroupName = groupName metrics = listOf("GroupMaxSize") granularity = "1Minute" } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.enableMetricsCollection(collectionRequest) println("The enable metrics collection operation was successful") } }
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

public function enableMetricsCollection($autoScalingGroupName, $granularity) { return $this->autoScalingClient->enableMetricsCollection([ 'AutoScalingGroupName' => $autoScalingGroupName, 'Granularity' => $granularity, ]); }
PowerShell
Tools for PowerShell

Example 1: This example enables monitoring of the specified metrics for the specified Auto Scaling group.

Enable-ASMetricsCollection -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute

Example 2: This example enables monitoring of all metrics for the specified Auto Scaling group.

Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

class AutoScalingWrapper: """Encapsulates Amazon EC2 Auto Scaling actions.""" def __init__(self, autoscaling_client): """ :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client. """ self.autoscaling_client = autoscaling_client def enable_metrics(self, group_name: str, metrics: List[str]) -> Dict[str, Any]: """ Enables CloudWatch metric collection for Amazon EC2 Auto Scaling activities. :param group_name: The name of the group to enable. :param metrics: A list of metrics to collect. :return: A dictionary with the response from enabling the metrics collection. :raises ClientError: If there is an error enabling metrics collection. """ try: response = self.autoscaling_client.enable_metrics_collection( AutoScalingGroupName=group_name, Metrics=metrics, Granularity="1Minute" ) logger.info( f"Successfully enabled metrics for Auto Scaling group '{group_name}'." ) except ClientError as err: error_code = err.response["Error"]["Code"] logger.error( f"Couldn't enable metrics on '{group_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}" ) if error_code == "ResourceContentionFault": logger.error( f"There is a conflict with another operation that is modifying the Auto Scaling group '{group_name}'. " "Please try again later." ) elif error_code == "InvalidParameterCombination": logger.error( f"The combination of parameters provided for enabling metrics on '{group_name}' is not valid. " "Please check the parameters and try again." ) raise else: return response
Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

let enable_metrics_collection = autoscaling .enable_metrics_collection() .auto_scaling_group_name(auto_scaling_group_name.as_str()) .granularity("1Minute") .set_metrics(Some(vec![ String::from("GroupMinSize"), String::from("GroupMaxSize"), String::from("GroupDesiredCapacity"), String::from("GroupInServiceInstances"), String::from("GroupTotalInstances"), ])) .send() .await;
SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/// <summary> /// Enable the collection of metric data for an Auto Scaling group. /// </summary> /// <param name="groupName">The name of the Auto Scaling group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> EnableMetricsCollectionAsync(string groupName) { var listMetrics = new List<string> { "GroupMaxSize", }; var collectionRequest = new EnableMetricsCollectionRequest { AutoScalingGroupName = groupName, Metrics = listMetrics, Granularity = "1Minute", }; var response = await _amazonAutoScaling.EnableMetricsCollectionAsync(collectionRequest); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }

For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions.

PrivacySite termsCookie preferences
© 2025, Amazon Web Services, Inc. or its affiliates. All rights reserved.