与 AWS SDK或EnableMetricsCollection一起使用 CLI - AWS SDK代码示例

AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

与 AWS SDK或EnableMetricsCollection一起使用 CLI

以下代码示例演示如何使用 EnableMetricsCollection

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

/// <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对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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

示例 1:启用自动扩缩组的指标收集

此示例将启用指定自动扩缩组的数据收集。

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

此命令不生成任何输出。

有关更多信息,请参阅 Amazon Auto Scaling 用户指南中的 Aut EC2 o S caling 组和实例的监控 CloudWatch 指标

示例 2:收集自动扩缩组指定指标的相关数据

要收集特定指标的相关数据,请使用 --metrics 选项。

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

此命令不生成任何输出。

有关更多信息,请参阅 Amazon Auto Scaling 用户指南中的 Aut EC2 o S caling 组和实例的监控 CloudWatch 指标

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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

示例 1:此示例启用对指定自动扩缩组指定指标的监控。

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

示例 2:此示例启用对指定自动扩缩组所有指标的监控。

Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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对于 Rust
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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;