Use EnableMetricsCollection
with an Amazon SDK or CLI
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
-
- Amazon SDK for .NET (v4)
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon 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 API details, see EnableMetricsCollection in Amazon SDK for .NET API Reference.
-
- C++
-
- SDK for C++
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon 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; }
-
For API details, see EnableMetricsCollection in Amazon SDK for C++ API Reference.
-
- CLI
-
- Amazon 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
\ --metricsGroupDesiredCapacity
--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. -
For API details, see EnableMetricsCollection
in Amazon CLI Command Reference.
-
- 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 Amazon 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); } }
-
For API details, see EnableMetricsCollection in Amazon SDK for Java 2.x API Reference.
-
- Kotlin
-
- SDK for Kotlin
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon 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") } }
-
For API details, see EnableMetricsCollection
in Amazon SDK for Kotlin API reference.
-
- PHP
-
- SDK for PHP
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon Code Examples Repository
. public function enableMetricsCollection($autoScalingGroupName, $granularity) { return $this->autoScalingClient->enableMetricsCollection([ 'AutoScalingGroupName' => $autoScalingGroupName, 'Granularity' => $granularity, ]); }
-
For API details, see EnableMetricsCollection in Amazon SDK for PHP API Reference.
-
- PowerShell
-
- Tools for PowerShell V4
-
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
-
For API details, see EnableMetricsCollection
in Amazon Tools for PowerShell Cmdlet Reference (V4).
-
- Tools for PowerShell V5
-
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
-
For API details, see EnableMetricsCollection
in Amazon Tools for PowerShell Cmdlet Reference (V5).
-
- 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 Amazon 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
-
For API details, see EnableMetricsCollection in Amazon SDK for Python (Boto3) API Reference.
-
- Rust
-
- SDK for Rust
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the Amazon 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;
-
For API details, see EnableMetricsCollection
in Amazon SDK for Rust API reference.
-
For a complete list of Amazon SDK developer guides and code examples, see Using this service with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.