

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

# 使用 Auto Scaling 的操作 AWS SDKs
<a name="service_code_examples_actions"></a>

以下代码示例演示了如何使用执行单个 Auto Scaling 操作 AWS SDKs。每个示例都包含一个指向的链接 GitHub，您可以在其中找到有关设置和运行代码的说明。

这些代码节选调用了 Auto Scaling API，是必须在上下文中运行的大型程序的代码节选。您可以在[使用 Auto Scaling 的场景 AWS SDKs](service_code_examples_scenarios.md)中结合上下文查看操作。

 以下示例仅包括最常用的操作。有关完整列表，请参阅《[Amazon EC2 Auto Scaling API Reference](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/Welcome.html)》。

**Topics**
+ [`AttachInstances`](example_auto-scaling_AttachInstances_section.md)
+ [`AttachLoadBalancerTargetGroups`](example_auto-scaling_AttachLoadBalancerTargetGroups_section.md)
+ [`AttachLoadBalancers`](example_auto-scaling_AttachLoadBalancers_section.md)
+ [`CompleteLifecycleAction`](example_auto-scaling_CompleteLifecycleAction_section.md)
+ [`CreateAutoScalingGroup`](example_auto-scaling_CreateAutoScalingGroup_section.md)
+ [`CreateLaunchConfiguration`](example_auto-scaling_CreateLaunchConfiguration_section.md)
+ [`CreateOrUpdateTags`](example_auto-scaling_CreateOrUpdateTags_section.md)
+ [`DeleteAutoScalingGroup`](example_auto-scaling_DeleteAutoScalingGroup_section.md)
+ [`DeleteLaunchConfiguration`](example_auto-scaling_DeleteLaunchConfiguration_section.md)
+ [`DeleteLifecycleHook`](example_auto-scaling_DeleteLifecycleHook_section.md)
+ [`DeleteNotificationConfiguration`](example_auto-scaling_DeleteNotificationConfiguration_section.md)
+ [`DeletePolicy`](example_auto-scaling_DeletePolicy_section.md)
+ [`DeleteScheduledAction`](example_auto-scaling_DeleteScheduledAction_section.md)
+ [`DeleteTags`](example_auto-scaling_DeleteTags_section.md)
+ [`DescribeAccountLimits`](example_auto-scaling_DescribeAccountLimits_section.md)
+ [`DescribeAdjustmentTypes`](example_auto-scaling_DescribeAdjustmentTypes_section.md)
+ [`DescribeAutoScalingGroups`](example_auto-scaling_DescribeAutoScalingGroups_section.md)
+ [`DescribeAutoScalingInstances`](example_auto-scaling_DescribeAutoScalingInstances_section.md)
+ [`DescribeAutoScalingNotificationTypes`](example_auto-scaling_DescribeAutoScalingNotificationTypes_section.md)
+ [`DescribeLaunchConfigurations`](example_auto-scaling_DescribeLaunchConfigurations_section.md)
+ [`DescribeLifecycleHookTypes`](example_auto-scaling_DescribeLifecycleHookTypes_section.md)
+ [`DescribeLifecycleHooks`](example_auto-scaling_DescribeLifecycleHooks_section.md)
+ [`DescribeLoadBalancers`](example_auto-scaling_DescribeLoadBalancers_section.md)
+ [`DescribeMetricCollectionTypes`](example_auto-scaling_DescribeMetricCollectionTypes_section.md)
+ [`DescribeNotificationConfigurations`](example_auto-scaling_DescribeNotificationConfigurations_section.md)
+ [`DescribePolicies`](example_auto-scaling_DescribePolicies_section.md)
+ [`DescribeScalingActivities`](example_auto-scaling_DescribeScalingActivities_section.md)
+ [`DescribeScalingProcessTypes`](example_auto-scaling_DescribeScalingProcessTypes_section.md)
+ [`DescribeScheduledActions`](example_auto-scaling_DescribeScheduledActions_section.md)
+ [`DescribeTags`](example_auto-scaling_DescribeTags_section.md)
+ [`DescribeTerminationPolicyTypes`](example_auto-scaling_DescribeTerminationPolicyTypes_section.md)
+ [`DetachInstances`](example_auto-scaling_DetachInstances_section.md)
+ [`DetachLoadBalancers`](example_auto-scaling_DetachLoadBalancers_section.md)
+ [`DisableMetricsCollection`](example_auto-scaling_DisableMetricsCollection_section.md)
+ [`EnableMetricsCollection`](example_auto-scaling_EnableMetricsCollection_section.md)
+ [`EnterStandby`](example_auto-scaling_EnterStandby_section.md)
+ [`ExecutePolicy`](example_auto-scaling_ExecutePolicy_section.md)
+ [`ExitStandby`](example_auto-scaling_ExitStandby_section.md)
+ [`PutLifecycleHook`](example_auto-scaling_PutLifecycleHook_section.md)
+ [`PutNotificationConfiguration`](example_auto-scaling_PutNotificationConfiguration_section.md)
+ [`PutScalingPolicy`](example_auto-scaling_PutScalingPolicy_section.md)
+ [`PutScheduledUpdateGroupAction`](example_auto-scaling_PutScheduledUpdateGroupAction_section.md)
+ [`RecordLifecycleActionHeartbeat`](example_auto-scaling_RecordLifecycleActionHeartbeat_section.md)
+ [`ResumeProcesses`](example_auto-scaling_ResumeProcesses_section.md)
+ [`SetDesiredCapacity`](example_auto-scaling_SetDesiredCapacity_section.md)
+ [`SetInstanceHealth`](example_auto-scaling_SetInstanceHealth_section.md)
+ [`SetInstanceProtection`](example_auto-scaling_SetInstanceProtection_section.md)
+ [`SuspendProcesses`](example_auto-scaling_SuspendProcesses_section.md)
+ [`TerminateInstanceInAutoScalingGroup`](example_auto-scaling_TerminateInstanceInAutoScalingGroup_section.md)
+ [`UpdateAutoScalingGroup`](example_auto-scaling_UpdateAutoScalingGroup_section.md)

# 将 `AttachInstances` 与 CLI 配合使用
<a name="example_auto-scaling_AttachInstances_section"></a>

以下代码示例演示如何使用 `AttachInstances`。

------
#### [ CLI ]

**AWS CLI**  
**将实例附加到自动扩缩组**  
此示例将指定的实例附加到指定的自动扩缩组。  

```
aws autoscaling attach-instances \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[AttachInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/attach-instances.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的实例附加到指定的自动扩缩组。Auto Scaling 会自动增加自动扩缩组的所需容量。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [AttachInstances](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的实例附加到指定的自动扩缩组。Auto Scaling 会自动增加自动扩缩组的所需容量。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `AttachLoadBalancerTargetGroups`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_AttachLoadBalancerTargetGroups_section"></a>

以下代码示例演示如何使用 `AttachLoadBalancerTargetGroups`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [构建和管理弹性服务](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
    /// The
    /// </summary>
    /// <param name="autoScalingGroupName">The name of the Auto Scaling group.</param>
    /// <param name="targetGroupArn">The Arn for the target group.</param>
    /// <returns>Async task.</returns>
    public async Task AttachLoadBalancerToGroup(string autoScalingGroupName, string targetGroupArn)
    {
        await _amazonAutoScaling.AttachLoadBalancerTargetGroupsAsync(
            new AttachLoadBalancerTargetGroupsRequest()
            {
                AutoScalingGroupName = autoScalingGroupName,
                TargetGroupARNs = new List<string>() { targetGroupArn }
            });
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)*中的。

------
#### [ CLI ]

**AWS CLI**  
**将目标组附加到自动扩缩组**  
此示例将指定目标组附加到指定的自动扩缩组。  

```
aws autoscaling attach-load-balancer-target-groups \
    --auto-scaling-group-name my-asg \
    --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[弹性负载均衡和 Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[AttachLoadBalancerTargetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/attach-load-balancer-target-groups.html)*中的。

------
#### [ JavaScript ]

**适用于 JavaScript (v3) 的软件开发工具包**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    const client = new AutoScalingClient({});
    await client.send(
      new AttachLoadBalancerTargetGroupsCommand({
        AutoScalingGroupName: NAMES.autoScalingGroupName,
        TargetGroupARNs: [state.targetGroupArn],
      }),
    );
```
+  有关 API 的详细信息，请参阅 *适用于 JavaScript 的 AWS SDK API 参考[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/AttachLoadBalancerTargetGroupsCommand)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def attach_load_balancer_target_group(
        self, lb_target_group: Dict[str, Any]
    ) -> None:
        """
        Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
        The target group specifies how the load balancer forwards requests to the instances
        in the group.

        :param lb_target_group: Data about the ELB target group to attach.
        """
        try:
            self.autoscaling_client.attach_load_balancer_target_groups(
                AutoScalingGroupName=self.group_name,
                TargetGroupARNs=[lb_target_group["TargetGroupArn"]],
            )
            log.info(
                "Attached load balancer target group %s to auto scaling group %s.",
                lb_target_group["TargetGroupName"],
                self.group_name,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to attach load balancer target group '{lb_target_group['TargetGroupName']}'."
            )
            if error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            elif error_code == "ServiceLinkedRoleFailure":
                log.error(
                    "The operation failed because the service-linked role is not ready or does not exist. "
                    "Check that the service-linked role exists and is correctly configured."
                )
            log.error(f"Full error:\n\t{err}")
```
+  有关 API 的详细信息，请参阅适用[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)于 *Python 的AWS SDK (Boto3) API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `AttachLoadBalancers` 与 CLI 配合使用
<a name="example_auto-scaling_AttachLoadBalancers_section"></a>

以下代码示例演示如何使用 `AttachLoadBalancers`。

------
#### [ CLI ]

**AWS CLI**  
**将经典负载均衡器附加到自动扩缩组**  
此示例将指定的经典负载均衡器附加到指定的自动扩缩组。  

```
aws autoscaling attach-load-balancers \
    --load-balancer-names my-load-balancer \
    --auto-scaling-group-name my-asg
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[弹性负载均衡和 Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[AttachLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/attach-load-balancers.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的负载均衡器附加到指定的自动扩缩组。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的负载均衡器附加到指定的自动扩缩组。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `CompleteLifecycleAction` 与 CLI 配合使用
<a name="example_auto-scaling_CompleteLifecycleAction_section"></a>

以下代码示例演示如何使用 `CompleteLifecycleAction`。

------
#### [ CLI ]

**AWS CLI**  
**完成生命周期操作**  
此示例通知 Amazon EC2 Auto Scaling 指定的生命周期操作已完成，因此它可以完成启动或终止实例。  

```
aws autoscaling complete-lifecycle-action \
    --lifecycle-hook-name my-launch-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-action-result CONTINUE \
    --lifecycle-action-token bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 生命周期挂钩](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CompleteLifecycleAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/complete-lifecycle-action.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例完成了指定的生命周期操作。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例完成了指定的生命周期操作。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `CreateAutoScalingGroup`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_CreateAutoScalingGroup_section"></a>

以下代码示例演示如何使用 `CreateAutoScalingGroup`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [构建和管理弹性服务](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Create a new Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name to use for the new Auto Scaling
    /// group.</param>
    /// <param name="launchTemplateName">The name of the Amazon EC2 Auto Scaling
    /// launch template to use to create instances in the group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateAutoScalingGroupAsync(
        string groupName,
        string launchTemplateName,
        string availabilityZone)
    {
        var templateSpecification = new LaunchTemplateSpecification
        {
            LaunchTemplateName = launchTemplateName,
        };

        var zoneList = new List<string>
            {
                availabilityZone,
            };

        var request = new CreateAutoScalingGroupRequest
        {
            AutoScalingGroupName = groupName,
            AvailabilityZones = zoneList,
            LaunchTemplate = templateSpecification,
            MaxSize = 6,
            MinSize = 1
        };
        try
        {
            var response = await _amazonAutoScaling.CreateAutoScalingGroupAsync(request);
            Console.WriteLine($"{groupName} Auto Scaling Group created");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine($"{groupName} Auto Scaling Group already exists.");
            return true;
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/CreateAutoScalingGroup)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::CreateAutoScalingGroupRequest request;
        request.SetAutoScalingGroupName(groupName);
        Aws::Vector<Aws::String> availabilityGroupZones;
        availabilityGroupZones.push_back(
                availabilityZones[availabilityZoneChoice - 1].GetZoneName());
        request.SetAvailabilityZones(availabilityGroupZones);
        request.SetMaxSize(1);
        request.SetMinSize(1);

        Aws::AutoScaling::Model::LaunchTemplateSpecification launchTemplateSpecification;
        launchTemplateSpecification.SetLaunchTemplateName(templateName);
        request.SetLaunchTemplate(launchTemplateSpecification);

        Aws::AutoScaling::Model::CreateAutoScalingGroupOutcome outcome =
                autoScalingClient.CreateAutoScalingGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "Created Auto Scaling group '" << groupName << "'..."
                      << std::endl;
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::AutoScaling::AutoScalingErrors::ALREADY_EXISTS_FAULT) {
            std::cout << "Auto Scaling group '" << groupName << "' already exists."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::CreateAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/CreateAutoScalingGroup)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：创建自动扩缩组**  
以下 `create-auto-scaling-group` 示例在区域内多个可用区中的子网中创建自动扩缩组。实例以指定启动模板的默认版本启动。请注意，大多数其他设置都使用默认值，例如，终止策略和运行状况检查配置。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12 \
    --min-size 1 \
    --max-size 5 \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[自动扩缩组](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)。  
**示例 2：附加应用程序负载均衡器、网络负载均衡器或网关负载均衡器**  
此示例为支持预期流量的负载均衡器指定目标组的 ARN。运行状况检查类型指定 `ELB`，以便在 Elastic Load Balancing 报告实例运行状况不佳时，自动扩缩组将取代它。该命令还定义了以 `600` 秒为单位的运行状况检查宽限期。宽限期有助于防止新启动的实例过早终止。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12 \
    --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/943f017f100becff \
    --health-check-type ELB \
    --health-check-grace-period 600 \
    --min-size 1 \
    --max-size 5 \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Elastic Load Balancing 和 Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)。  
**示例 3：指定置放群组，并使用最新版本的启动模板**  
此示例将实例启动到单个可用区中的置放群组。这对于具有 HPC 工作负载的低延迟群组很有用。此示例还将指定群组的最小大小、最大大小和所需容量。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest' \
    --min-size 1 \
    --max-size 5 \
    --desired-capacity 3 \
    --placement-group my-placement-group \
    --vpc-zone-identifier "subnet-6194ea3b"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 用户指南（适用于 Linux 实例）》**中的[置放群组](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html)。  
**示例 4：指定单个实例自动扩缩组，并使用特定版本的启动模板**  
此示例创建一个自动扩缩组，并将其最小和最大容量均设置为 `1` 以强制运行一个实例。该命令还指定了启动模板的 v1，其中指定了现有 ENI 的 ID。当您使用为 eth0 指定现有 ENI 的启动模板时，必须为自动扩缩组指定与网络接口匹配的可用区，而无需在请求中同时指定子网 ID。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg-single-instance \
    --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='1' \
    --min-size 1 \
    --max-size 1 \
    --availability-zones us-west-2a
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[自动扩缩组](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)。  
**示例 5：指定不同的终止策略**  
此示例使用启动配置创建自动扩缩组，并将终止策略设置为首先终止最旧的实例。该命令还将标签应用于该组及其实例，其密钥为 `Role`，值为 `WebServer`。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-configuration-name my-lc \
    --min-size 1 \
    --max-size 5 \
    --termination-policies "OldestInstance" \
    --tags "ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Role,Value=WebServer,PropagateAtLaunch=true" \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[使用 Amazon EC2 Auto Scaling 终止策略](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-termination-policies.html)。  
**示例 6：指定启动生命周期挂钩**  
此示例将使用生命周期挂钩创建一个自动扩缩组，该挂钩支持在实例启动时的自定义操作。  

```
aws autoscaling create-auto-scaling-group \
    --cli-input-json file://~/config.json
```
`config.json` 文件的内容：  

```
{
    "AutoScalingGroupName": "my-asg",
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-1234567890abcde12"
    },
    "LifecycleHookSpecificationList": [{
        "LifecycleHookName": "my-launch-hook",
        "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING",
        "NotificationTargetARN": "arn:aws:sqs:us-west-2:123456789012:my-sqs-queue",
        "RoleARN": "arn:aws:iam::123456789012:role/my-notification-role",
        "NotificationMetadata": "SQS message metadata",
        "HeartbeatTimeout": 4800,
        "DefaultResult": "ABANDON"
    }],
    "MinSize": 1,
    "MaxSize": 5,
    "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782",
    "Tags": [{
        "ResourceType": "auto-scaling-group",
        "ResourceId": "my-asg",
        "PropagateAtLaunch": true,
        "Value": "test",
        "Key": "environment"
    }]
}
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 生命周期挂钩](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)。  
**示例 7：指定终止生命周期挂钩**  
此示例将使用生命周期挂钩创建一个自动扩缩组，该挂钩支持在实例终止时的自定义操作。  

```
aws autoscaling create-auto-scaling-group \
    --cli-input-json file://~/config.json
```
`config.json` 的内容：  

```
{
    "AutoScalingGroupName": "my-asg",
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-1234567890abcde12"
    },
    "LifecycleHookSpecificationList": [{
        "LifecycleHookName": "my-termination-hook",
        "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING",
        "HeartbeatTimeout": 120,
        "DefaultResult": "CONTINUE"
    }],
    "MinSize": 1,
    "MaxSize": 5,
    "TargetGroupARNs": [
        "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"
    ],
    "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
}
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 生命周期挂钩](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)。  
**示例 8：指定自定义终止策略**  
此示例创建一个自动扩缩组，该组指定自定义 Lambda 函数终止策略，以指示 Amazon EC2 Auto Scaling 哪些实例可以安全地在横向缩减时终止。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg-single-instance \
    --launch-template LaunchTemplateName=my-template-for-auto-scaling \
    --min-size 1 \
    --max-size 5 \
    --termination-policies "arn:aws:lambda:us-west-2:123456789012:function:HelloFunction:prod" \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[通过 Lambda 创建自定义终止策略](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lambda-custom-termination-policy.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/create-auto-scaling-group.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
import software.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;
import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification;
import software.amazon.awssdk.services.autoscaling.waiters.AutoScalingWaiter;

/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CreateAutoScalingGroup {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <groupName> <launchTemplateName> <serviceLinkedRoleARN> <vpcZoneId>

                Where:
                    groupName - The name of the Auto Scaling group.
                    launchTemplateName - The name of the launch template.\s
                    vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created.
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String groupName = args[0];
        String launchTemplateName = args[1];
        String vpcZoneId = args[2];
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_EAST_1)
                .build();

        createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId);
        autoScalingClient.close();
    }

    public static void createAutoScalingGroup(AutoScalingClient autoScalingClient,
            String groupName,
            String launchTemplateName,
            String vpcZoneId) {

        try {
            AutoScalingWaiter waiter = autoScalingClient.waiter();
            LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder()
                    .launchTemplateName(launchTemplateName)
                    .build();

            CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder()
                    .autoScalingGroupName(groupName)
                    .availabilityZones("us-east-1a")
                    .launchTemplate(templateSpecification)
                    .maxSize(1)
                    .minSize(1)
                    .vpcZoneIdentifier(vpcZoneId)
                    .build();

            autoScalingClient.createAutoScalingGroup(request);
            DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter
                    .waitUntilGroupExists(groupsRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Auto Scaling Group created");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun createAutoScalingGroup(
    groupName: String,
    launchTemplateNameVal: String,
    serviceLinkedRoleARNVal: String,
    vpcZoneIdVal: String,
) {
    val templateSpecification =
        LaunchTemplateSpecification {
            launchTemplateName = launchTemplateNameVal
        }

    val request =
        CreateAutoScalingGroupRequest {
            autoScalingGroupName = groupName
            availabilityZones = listOf("us-east-1a")
            launchTemplate = templateSpecification
            maxSize = 1
            minSize = 1
            vpcZoneIdentifier = vpcZoneIdVal
            serviceLinkedRoleArn = serviceLinkedRoleARNVal
        }

    // This object is required for the waiter call.
    val groupsRequestWaiter =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.createAutoScalingGroup(request)
        autoScalingClient.waitUntilGroupExists(groupsRequestWaiter)
        println("$groupName was created!")
    }
}
```
+  有关 API 的详细信息，请参阅适用[CreateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function createAutoScalingGroup(
        $autoScalingGroupName,
        $availabilityZones,
        $minSize,
        $maxSize,
        $launchTemplateId
    ) {
        return $this->autoScalingClient->createAutoScalingGroup([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'AvailabilityZones' => $availabilityZones,
            'MinSize' => $minSize,
            'MaxSize' => $maxSize,
            'LaunchTemplate' => [
                'LaunchTemplateId' => $launchTemplateId,
            ],
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/CreateAutoScalingGroup)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例使用指定的名称和属性创建自动扩缩组。默认所需容量为最小大小。因此，此自动扩缩组启动两个实例，指定的两个可用区中各一个。**  

```
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例使用指定的名称和属性创建自动扩缩组。默认所需容量为最小大小。因此，此自动扩缩组启动两个实例，指定的两个可用区中各一个。**  

```
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 create_group(
        self,
        group_name: str,
        group_zones: List[str],
        launch_template_name: str,
        min_size: int,
        max_size: int,
    ) -> None:
        """
        Creates an Auto Scaling group.

        :param group_name: The name to give to the group.
        :param group_zones: The Availability Zones in which instances can be created.
        :param launch_template_name: The name of an existing Amazon EC2 launch template.
                                     The launch template specifies the configuration of
                                     instances that are created by auto scaling activities.
        :param min_size: The minimum number of active instances in the group.
        :param max_size: The maximum number of active instances in the group.
        :return: None
        :raises ClientError: If there is an error creating the Auto Scaling group.
        """
        try:
            self.autoscaling_client.create_auto_scaling_group(
                AutoScalingGroupName=group_name,
                AvailabilityZones=group_zones,
                LaunchTemplate={
                    "LaunchTemplateName": launch_template_name,
                    "Version": "$Default",
                },
                MinSize=min_size,
                MaxSize=max_size,
            )

            # Wait for the group to exist.
            waiter = self.autoscaling_client.get_waiter("group_exists")
            waiter.wait(AutoScalingGroupNames=[group_name])

            logger.info(f"Successfully created Auto Scaling group {group_name}.")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to create Auto Scaling group {group_name}.")
            if error_code == "AlreadyExistsFault":
                logger.error(
                    f"An Auto Scaling group with the name '{group_name}' already exists. "
                    "Please use a different name or update the existing group.",
                )
            elif error_code == "LimitExceededFault":
                logger.error(
                    "The request failed because you have reached the limit "
                    "on the number of Auto Scaling groups or launch configurations. "
                    "Consider deleting unused resources or request a limit increase. "
                    "\nSee Auto Scaling Service Quota documentation here:"
                    "\n\thttps://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-quotas.html"
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  有关 API 的详细信息，请参阅适用[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
async fn create_group(client: &Client, name: &str, id: &str) -> Result<(), Error> {
    client
        .create_auto_scaling_group()
        .auto_scaling_group_name(name)
        .instance_id(id)
        .min_size(1)
        .max_size(5)
        .send()
        .await?;

    println!("Created AutoScaling group");

    Ok(())
}
```
+  有关 API 的详细信息，请参阅适用[CreateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.create_auto_scaling_group)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    DATA lo_launch_template TYPE REF TO /aws1/cl_asclaunchtemplatespec.
    
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: iv_launch_template_name = 'my-launch-template'
    " Example: iv_min_size = 1
    " Example: iv_max_size = 3
    " Example: iv_vpc_zone_identifier = 'subnet-12345,subnet-67890' (for VPC)
    
    TRY.
        " Create launch template specification
        lo_launch_template = NEW /aws1/cl_asclaunchtemplatespec(
          iv_launchtemplatename = iv_launch_template_name
          iv_version = '$Default' ).

        " Create the Auto Scaling group
        " Use VPCZoneIdentifier for VPC subnets, or AvailabilityZones for EC2-Classic
        IF iv_vpc_zone_identifier IS NOT INITIAL.
          " VPC-based deployment - use subnet IDs
          ao_asc->createautoscalinggroup(
            iv_autoscalinggroupname = iv_group_name
            iv_vpczoneidentifier = iv_vpc_zone_identifier
            io_launchtemplate = lo_launch_template
            iv_minsize = iv_min_size
            iv_maxsize = iv_max_size ).
        ELSE.
          " EC2-Classic or default VPC - use availability zones
          ao_asc->createautoscalinggroup(
            iv_autoscalinggroupname = iv_group_name
            it_availabilityzones = it_group_zones
            io_launchtemplate = lo_launch_template
            iv_minsize = iv_min_size
            iv_maxsize = iv_max_size ).
        ENDIF.

        " Wait for the group to be created (simplified - in production use proper polling)
        WAIT UP TO 10 SECONDS.

        MESSAGE 'Auto Scaling group created successfully' TYPE 'I'.

      CATCH /aws1/cx_ascalreadyexistsfault INTO DATA(lo_already_exists).
        RAISE EXCEPTION lo_already_exists.
      CATCH /aws1/cx_asclimitexceededfault INTO DATA(lo_limit_exceeded).
        RAISE EXCEPTION lo_limit_exceeded.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[CreateAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `CreateLaunchConfiguration` 与 CLI 配合使用
<a name="example_auto-scaling_CreateLaunchConfiguration_section"></a>

以下代码示例演示如何使用 `CreateLaunchConfiguration`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：创建启动配置**  
此示例创建一个简单的启动配置。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[创建启动配置](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-config.html)。  
**示例 2：使用安全组、key pair 和引导脚本创建启动配置**  
此示例使用用户数据中包含的安全组、key pair 和引导脚本创建启动配置。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --security-groups sg-eb2af88example \
    --key-name my-key-pair \
    --user-data file://myuserdata.txt
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[创建启动配置](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-config.html)。  
**示例 3：使用 IAM 角色创建启动配置**  
此示例使用 IAM 角色的实例配置文件名称创建启动配置。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --iam-instance-profile my-autoscaling-role
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》中的[在 Amazon EC2 实例上运行的应用程序的 IAM 角色](https://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html)。  
**示例 4：创建启用详细监控的启动配置**  
此示例创建了启用 EC2 详细监控的启动配置，该配置会 CloudWatch 在 1 分钟内将 EC2 指标发送到。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --instance-monitoring Enabled=true
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[配置自动扩缩实例的监控](https://docs.aws.amazon.com/autoscaling/ec2/userguide/enable-as-instance-metrics.html)。  
**示例 5：创建启动竞价型实例的启动配置**  
此示例创建使用竞价型实例作为唯一购买选项的启动配置。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --spot-price "0.50"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[请求竞价型实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html)。  
**示例 6：使用 EC2 实例创建启动配置**  
此示例基于现有实例的属性创建启动配置。它通过包含 `--placement-tenancy` 和 `--no-associate-public-ip-address` 选项来覆盖置放租赁以及是否设置公有 IP 地址。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc-from-instance \
    --instance-id i-0123a456700123456 \
    --instance-type m5.large \
    --no-associate-public-ip-address \
    --placement-tenancy dedicated
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[使用 EC2 实例创建启动配置](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html)。  
**示例 7：为 Amazon EBS 卷创建具有块设备映射的启动配置**  
此示例为设备名称为 `/dev/sdh` 和卷大小为 20 的 Amazon EBS `gp3` 卷创建具有块设备映射的启动配置。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --block-device-mappings '[{"DeviceName":"/dev/sdh","Ebs":{"VolumeSize":20,"VolumeType":"gp3"}}]'
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling API Reference》**中的 [EBS](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_Ebs.html)。  
有关引用 JSON 格式参数值的语法的信息，请参阅《*AWS 命令行界面用户*[指南》中的 CL AWS I 中对字符串使用引号](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html)。  
**示例 8：为实例存储卷创建具有块设备映射的启动配置**  
此示例创建一个启动配置，将 `ephemeral1` 作为实例存储卷，设备名称为 `/dev/sdc`。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --block-device-mappings '[{"DeviceName":"/dev/sdc","VirtualName":"ephemeral1"}]'
```
此命令不生成任何输出。  
有关更多信息，请参阅[BlockDeviceMapping](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_BlockDeviceMapping.html)《*亚马逊 EC2 Auto Scaling API 参考*》。  
有关引用 JSON 格式参数值的语法的信息，请参阅《*AWS 命令行界面用户*[指南》中的 CL AWS I 中对字符串使用引号](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html)。  
**示例 9：创建启动配置并禁止在启动时附加块设备**  
此示例创建一个启动配置，用于禁止通过 AMI 的块设备映射指定的块设备（例如，`/dev/sdf`）。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --block-device-mappings '[{"DeviceName":"/dev/sdf","NoDevice":""}]'
```
此命令不生成任何输出。  
有关更多信息，请参阅[BlockDeviceMapping](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_BlockDeviceMapping.html)《*亚马逊 EC2 Auto Scaling API 参考*》。  
有关引用 JSON 格式参数值的语法的信息，请参阅《*AWS 命令行界面用户*[指南》中的 CL AWS I 中对字符串使用引号](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateLaunchConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/create-launch-configuration.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例创建一个名为“my-lc”的启动配置。使用此启动配置的自动扩缩组启动的 EC2 实例，使用指定的实例类型、AMI、安全组和 IAM 角色。**  

```
New-ASLaunchConfiguration -LaunchConfigurationName my-lc -InstanceType "m3.medium" -ImageId "ami-12345678" -SecurityGroup "sg-12345678" -IamInstanceProfile "myIamRole"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建一个名为“my-lc”的启动配置。使用此启动配置的自动扩缩组启动的 EC2 实例，使用指定的实例类型、AMI、安全组和 IAM 角色。**  

```
New-ASLaunchConfiguration -LaunchConfigurationName my-lc -InstanceType "m3.medium" -ImageId "ami-12345678" -SecurityGroup "sg-12345678" -IamInstanceProfile "myIamRole"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `CreateOrUpdateTags` 与 CLI 配合使用
<a name="example_auto-scaling_CreateOrUpdateTags_section"></a>

以下代码示例演示如何使用 `CreateOrUpdateTags`。

------
#### [ CLI ]

**AWS CLI**  
**创建或更新自动扩缩组的标签**  
此示例向指定的自动扩缩组添加两个标签。  

```
aws autoscaling create-or-update-tags \
    --tags ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Role,Value=WebServer,PropagateAtLaunch=true ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Dept,Value=Research,PropagateAtLaunch=true
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[标记自动扩缩组和实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[CreateOrUpdateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/create-or-update-tags.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例向指定的自动扩缩组添加单个标签。标签键为 “myTag”，标签值为 “myTagValue”。Auto Scaling 会将此标签传播到自动扩缩组启动的后续 EC2 实例。此示例使用的语法需要 PowerShell 版本 3 或更高版本。**  

```
Set-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag"; Value="myTagValue"; PropagateAtLaunch=$true} )
```
**示例 2：在 PowerShell 版本 2 中，必须使用 New-Object 为标签参数创建标签。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg" 
$tag.Key = "myTag" 
$tag.Value = "myTagValue"
$tag.PropagateAtLaunch = $true
Set-ASTag -Tag $tag
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例向指定的自动扩缩组添加单个标签。标签键为 “myTag”，标签值为 “myTagValue”。Auto Scaling 会将此标签传播到自动扩缩组启动的后续 EC2 实例。此示例使用的语法需要 PowerShell 版本 3 或更高版本。**  

```
Set-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag"; Value="myTagValue"; PropagateAtLaunch=$true} )
```
**示例 2：在 PowerShell 版本 2 中，必须使用 New-Object 为标签参数创建标签。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg" 
$tag.Key = "myTag" 
$tag.Value = "myTagValue"
$tag.PropagateAtLaunch = $true
Set-ASTag -Tag $tag
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `DeleteAutoScalingGroup`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_DeleteAutoScalingGroup_section"></a>

以下代码示例演示如何使用 `DeleteAutoScalingGroup`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [构建和管理弹性服务](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)中查找完整示例，了解如何进行设置和运行。
将自动扩缩组的最小大小更新为零，终止该组中的所有实例，然后删除该组。  

```
    /// <summary>
    /// Try to terminate an instance by its Id.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task TryTerminateInstanceById(string instanceId)
    {
        var stopping = false;
        Console.WriteLine($"Stopping {instanceId}...");
        while (!stopping)
        {
            try
            {
                await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(
                    new TerminateInstanceInAutoScalingGroupRequest()
                    {
                        InstanceId = instanceId,
                        ShouldDecrementDesiredCapacity = false
                    });
                stopping = true;
            }
            catch (ScalingActivityInProgressException)
            {
                Console.WriteLine($"Scaling activity in progress for {instanceId}. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress,
    /// waits and retries until the group is successfully deleted.
    /// </summary>
    /// <param name="groupName">The name of the group to try to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TryDeleteGroupByName(string groupName)
    {
        var stopped = false;
        while (!stopped)
        {
            try
            {
                await _amazonAutoScaling.DeleteAutoScalingGroupAsync(
                    new DeleteAutoScalingGroupRequest()
                    {
                        AutoScalingGroupName = groupName
                    });
                stopped = true;
            }
            catch (Exception e)
                when ((e is ScalingActivityInProgressException)
                      || (e is Amazon.AutoScaling.Model.ResourceInUseException))
            {
                Console.WriteLine($"Some instances are still running. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Terminate instances and delete the Auto Scaling group by name.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TerminateAndDeleteAutoScalingGroupWithName(string groupName)
    {
        var describeGroupsResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { groupName }
            });
        if (describeGroupsResponse.AutoScalingGroups.Any())
        {
            // Update the size to 0.
            await _amazonAutoScaling.UpdateAutoScalingGroupAsync(
                new UpdateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    MinSize = 0
                });
            var group = describeGroupsResponse.AutoScalingGroups[0];
            foreach (var instance in group.Instances)
            {
                await TryTerminateInstanceById(instance.InstanceId);
            }

            await TryDeleteGroupByName(groupName);
        }
        else
        {
            Console.WriteLine($"No groups found with name {groupName}.");
        }
    }
```

```
    /// <summary>
    /// Delete an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAutoScalingGroupAsync(
        string groupName)
    {
        var deleteAutoScalingGroupRequest = new DeleteAutoScalingGroupRequest
        {
            AutoScalingGroupName = groupName,
            ForceDelete = true,
        };

        var response = await _amazonAutoScaling.DeleteAutoScalingGroupAsync(deleteAutoScalingGroupRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You successfully deleted {groupName}");
            return true;
        }

        Console.WriteLine($"Couldn't delete {groupName}.");
        return false;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::DeleteAutoScalingGroupRequest request;
            request.SetAutoScalingGroupName(groupName);

            Aws::AutoScaling::Model::DeleteAutoScalingGroupOutcome outcome =
                    autoScalingClient.DeleteAutoScalingGroup(request);

            if (outcome.IsSuccess()) {
                std::cout << "Auto Scaling group '" << groupName << "' was deleted."
                          << std::endl;
            }
            else {
                std::cerr << "Error with AutoScaling::DeleteAutoScalingGroup. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DeleteAutoScalingGroup)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：删除指定的自动扩缩组**  
此示例将删除指定的自动扩缩组。  

```
aws autoscaling delete-auto-scaling-group \
    --auto-scaling-group-name my-asg
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[删除自动扩缩基础设施](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-process-shutdown.html)。  
**示例 2：强制删除指定的自动扩缩组**  
要在不等待自动扩缩组中的实例终止的情况下删除该组，请使用 `--force-delete` 选项。  

```
aws autoscaling delete-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --force-delete
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[删除自动扩缩基础设施](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-process-shutdown.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-auto-scaling-group.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
import software.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest;

/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DeleteAutoScalingGroup {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <groupName>

                Where:
                    groupName - The name of the Auto Scaling group.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String groupName = args[0];
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_EAST_1)
                .build();

        deleteAutoScalingGroup(autoScalingClient, groupName);
        autoScalingClient.close();
    }

    public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder()
                    .autoScalingGroupName(groupName)
                    .forceDelete(true)
                    .build();

            autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest);
            System.out.println("You successfully deleted " + groupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun deleteSpecificAutoScalingGroup(groupName: String) {
    val deleteAutoScalingGroupRequest =
        DeleteAutoScalingGroupRequest {
            autoScalingGroupName = groupName
            forceDelete = true
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest)
        println("You successfully deleted $groupName")
    }
}
```
+  有关 API 的详细信息，请参阅适用[DeleteAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function deleteAutoScalingGroup($autoScalingGroupName)
    {
        return $this->autoScalingClient->deleteAutoScalingGroup([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'ForceDelete' => true,
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：如果指定的自动扩缩组没有正在运行的实例，则此示例将删除该组。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASAutoScalingGroup (DeleteAutoScalingGroup)" on Target "my-asg".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force
```
**示例 3：此示例删除指定的自动扩缩组并终止该组包含的所有正在运行的实例。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：如果指定的自动扩缩组没有正在运行的实例，则此示例将删除该组。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASAutoScalingGroup (DeleteAutoScalingGroup)" on Target "my-asg".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force
```
**示例 3：此示例删除指定的自动扩缩组并终止该组包含的所有正在运行的实例。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。
将自动扩缩组的最小大小更新为零，终止该组中的所有实例，然后删除该组。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def delete_autoscaling_group(self, group_name: str) -> None:
        """
        Terminates all instances in the group, then deletes the EC2 Auto Scaling group.

        :param group_name: The name of the group to delete.
        """
        try:
            response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[group_name]
            )
            groups = response.get("AutoScalingGroups", [])
            if len(groups) > 0:
                self.autoscaling_client.update_auto_scaling_group(
                    AutoScalingGroupName=group_name, MinSize=0
                )
                instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]]
                for inst_id in instance_ids:
                    self.terminate_instance(inst_id)

                # Wait for all instances to be terminated
                if instance_ids:
                    waiter = self.ec2_client.get_waiter("instance_terminated")
                    log.info("Waiting for all instances to be terminated...")
                    waiter.wait(InstanceIds=instance_ids)
                    log.info("All instances have been terminated.")
            else:
                log.info(f"No groups found named '{group_name}'! Nothing to do.")
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete Auto Scaling group '{group_name}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to delete the group again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the group."
                )
            log.error(f"Full error:\n\t{err}")
```
+  有关 API 的详细信息，请参阅适用[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
async fn delete_group(client: &Client, name: &str, force: bool) -> Result<(), Error> {
    client
        .delete_auto_scaling_group()
        .auto_scaling_group_name(name)
        .set_force_delete(if force { Some(true) } else { None })
        .send()
        .await?;

    println!("Deleted Auto Scaling group");

    Ok(())
}
```
+  有关 API 的详细信息，请参阅适用[DeleteAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.delete_auto_scaling_group)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        ao_asc->deleteautoscalinggroup(
          iv_autoscalinggroupname = iv_group_name ).

        " Wait for the group to be deleted (simplified - in production use proper polling)
        WAIT UP TO 10 SECONDS.

        MESSAGE 'Auto Scaling group deleted successfully' TYPE 'I'.

      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_ascresourceinusefault INTO DATA(lo_resource_in_use).
        RAISE EXCEPTION lo_resource_in_use.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DeleteAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteLaunchConfiguration` 与 CLI 配合使用
<a name="example_auto-scaling_DeleteLaunchConfiguration_section"></a>

以下代码示例演示如何使用 `DeleteLaunchConfiguration`。

------
#### [ CLI ]

**AWS CLI**  
**删除启动配置**  
此示例删除指定的启动配置。  

```
aws autoscaling delete-launch-configuration \
    --launch-configuration-name my-launch-config
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[删除自动扩缩基础设施](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-process-shutdown.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteLaunchConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-launch-configuration.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：如果指定的启动配置未附加到自动扩缩组，则此示例将删除该配置。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLaunchConfiguration (DeleteLaunchConfiguration)" on Target "my-lc".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：如果指定的启动配置未附加到自动扩缩组，则此示例将删除该配置。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLaunchConfiguration (DeleteLaunchConfiguration)" on Target "my-lc".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteLifecycleHook` 与 CLI 配合使用
<a name="example_auto-scaling_DeleteLifecycleHook_section"></a>

以下代码示例演示如何使用 `DeleteLifecycleHook`。

------
#### [ CLI ]

**AWS CLI**  
**删除生命周期挂钩**  
此示例删除指定的生命周期挂钩。  

```
aws autoscaling delete-lifecycle-hook \
    --lifecycle-hook-name my-lifecycle-hook \
    --auto-scaling-group-name my-asg
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteLifecycleHook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-lifecycle-hook.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定生命周期挂钩。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLifecycleHook (DeleteLifecycleHook)" on Target "myLifecycleHook".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定生命周期挂钩。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLifecycleHook (DeleteLifecycleHook)" on Target "myLifecycleHook".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteNotificationConfiguration` 与 CLI 配合使用
<a name="example_auto-scaling_DeleteNotificationConfiguration_section"></a>

以下代码示例演示如何使用 `DeleteNotificationConfiguration`。

------
#### [ CLI ]

**AWS CLI**  
**删除 Auto Scaling 通知**  
此示例删除指定自动扩缩组的指定通知。  

```
aws autoscaling delete-notification-configuration \
    --auto-scaling-group-name my-asg \
    --topic-arn arn:aws:sns:us-west-2:123456789012:my-sns-topic
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[删除通知配置](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html#delete-settingupnotifications)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteNotificationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-notification-configuration.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例删除指定的通知操作。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASNotificationConfiguration (DeleteNotificationConfiguration)" on Target
"arn:aws:sns:us-west-2:123456789012:my-topic".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic" -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定的通知操作。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASNotificationConfiguration (DeleteNotificationConfiguration)" on Target
"arn:aws:sns:us-west-2:123456789012:my-topic".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic" -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeletePolicy` 与 CLI 配合使用
<a name="example_auto-scaling_DeletePolicy_section"></a>

以下代码示例演示如何使用 `DeletePolicy`。

------
#### [ CLI ]

**AWS CLI**  
**删除扩缩策略**  
此示例删除指定的扩展策略。  

```
aws autoscaling delete-policy \
    --auto-scaling-group-name my-asg \
    --policy-name alb1000-target-tracking-scaling-policy
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-policy.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定策略。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASPolicy (DeletePolicy)" on Target "myScaleInPolicy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeletePolicy](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定策略。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASPolicy (DeletePolicy)" on Target "myScaleInPolicy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteScheduledAction` 与 CLI 配合使用
<a name="example_auto-scaling_DeleteScheduledAction_section"></a>

以下代码示例演示如何使用 `DeleteScheduledAction`。

------
#### [ CLI ]

**AWS CLI**  
**从自动扩缩组中删除计划的操作**  
此示例从指定的自动扩缩组删除指定的计划操作。  

```
aws autoscaling delete-scheduled-action \
    --auto-scaling-group-name my-asg \
    --scheduled-action-name my-scheduled-action
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteScheduledAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-scheduled-action.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定计划操作。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction"
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASScheduledAction (DeleteScheduledAction)" on Target "myScheduledAction".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction" -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例删除指定自动扩缩组的指定计划操作。在操作继续之前，系统会提示您进行确认。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction"
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASScheduledAction (DeleteScheduledAction)" on Target "myScheduledAction".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction" -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DeleteTags` 与 CLI 配合使用
<a name="example_auto-scaling_DeleteTags_section"></a>

以下代码示例演示如何使用 `DeleteTags`。

------
#### [ CLI ]

**AWS CLI**  
**从自动扩缩组中删除标签**  
此示例从指定的自动扩缩组删除指定的标签。  

```
aws autoscaling delete-tags \
    --tags ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Dept,Value=Research
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[标记自动扩缩组和实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DeleteTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-tags.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例从指定的自动扩缩组删除指定的标签。在操作继续之前，系统会提示您进行确认。此示例使用的语法需要 PowerShell 版本 3 或更高版本。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } )
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ASTag (DeleteTags)" on target "Amazon.AutoScaling.Model.Tag".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } ) -Force
```
**示例 3：对于 PowerShell 版本 2，必须使用 New-Object 创建 Tag 参数的标签。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg"
$tag.Key = "myTag"
Remove-ASTag -Tag $tag -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例从指定的自动扩缩组删除指定的标签。在操作继续之前，系统会提示您进行确认。此示例使用的语法需要 PowerShell 版本 3 或更高版本。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } )
```
**输出**：  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ASTag (DeleteTags)" on target "Amazon.AutoScaling.Model.Tag".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**示例 2：如果您指定 Force 参数，则在操作继续之前，系统不会提示您进行确认。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } ) -Force
```
**示例 3：对于 PowerShell 版本 2，必须使用 New-Object 创建 Tag 参数的标签。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg"
$tag.Key = "myTag"
Remove-ASTag -Tag $tag -Force
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeAccountLimits` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeAccountLimits_section"></a>

以下代码示例演示如何使用 `DescribeAccountLimits`。

------
#### [ CLI ]

**AWS CLI**  
**描述您的 Amazon EC2 Auto Scaling 账户限制**  
此示例描述了您的 AWS 账户的 Amazon EC2 Auto Scaling 限制。  

```
aws autoscaling describe-account-limits
```
输出：  

```
{
    "NumberOfLaunchConfigurations": 5,
    "MaxNumberOfLaunchConfigurations": 100,
    "NumberOfAutoScalingGroups": 3,
    "MaxNumberOfAutoScalingGroups": 20
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 服务配额](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-account-limits.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeAccountLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-account-limits.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述了您的 AWS 账户的 Auto Scaling 资源限制。**  

```
Get-ASAccountLimit
```
**输出**：  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述了您的 AWS 账户的 Auto Scaling 资源限制。**  

```
Get-ASAccountLimit
```
**输出**：  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeAdjustmentTypes` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeAdjustmentTypes_section"></a>

以下代码示例演示如何使用 `DescribeAdjustmentTypes`。

------
#### [ CLI ]

**AWS CLI**  
**描述可用的扩缩调整类型**  
此示例描述可用的调整类型。  

```
aws autoscaling describe-adjustment-types
```
输出：  

```
{
    "AdjustmentTypes": [
        {
            "AdjustmentType": "ChangeInCapacity"
        },
        {
            "AdjustmentType": "ExactCapacity"
        },
        {
            "AdjustmentType": "PercentChangeInCapacity"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[扩展调整类型](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#as-scaling-adjustment)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeAdjustmentTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-adjustment-types.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述 Auto Scaling 所支持的调整类型。**  

```
Get-ASAdjustmentType
```
**输出**：  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述 Auto Scaling 所支持的调整类型。**  

```
Get-ASAdjustmentType
```
**输出**：  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `DescribeAutoScalingGroups`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_DescribeAutoScalingGroups_section"></a>

以下代码示例演示如何使用 `DescribeAutoScalingGroups`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [构建和管理弹性服务](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Get data about the instances in an Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling details.</returns>
    public async Task<List<AutoScalingInstanceDetails>> DescribeAutoScalingInstancesAsync(
        string groupName)
    {
        var groups = await DescribeAutoScalingGroupsAsync(groupName);
        var instanceIds = new List<string>();
        var instanceDetails = new List<AutoScalingInstanceDetails>();
        if (groups != null)
        {
            groups.ForEach(group =>
            {
                if (group.AutoScalingGroupName == groupName && group.Instances != null)
                {
                    group.Instances.ForEach(instance =>
                    {
                        instanceIds.Add(instance.InstanceId);
                    });
                }
            });

            var scalingGroupsRequest = new DescribeAutoScalingInstancesRequest
            {
                MaxRecords = 10,
                InstanceIds = instanceIds,
            };

            var response =
                await _amazonAutoScaling.DescribeAutoScalingInstancesAsync(
                    scalingGroupsRequest);
            if (response.AutoScalingInstances != null)
            {
                instanceDetails = response.AutoScalingInstances;
            }
        }

        return instanceDetails;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeAutoScalingGroups)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::DescribeAutoScalingGroupsRequest request;
    Aws::Vector<Aws::String> groupNames;
    groupNames.push_back(groupName);
    request.SetAutoScalingGroupNames(groupNames);

    Aws::AutoScaling::Model::DescribeAutoScalingGroupsOutcome outcome =
            client.DescribeAutoScalingGroups(request);

    if (outcome.IsSuccess()) {
        autoScalingGroup = outcome.GetResult().GetAutoScalingGroups();
    }
    else {
        std::cerr << "Error with AutoScaling::DescribeAutoScalingGroups. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingGroups)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：描述指定的自动扩缩组**  
此示例将描述指定的自动扩缩组。  

```
aws autoscaling describe-auto-scaling-groups \
    --auto-scaling-group-names my-asg
```
输出：  

```
{
    "AutoScalingGroups": [
        {
            "AutoScalingGroupName": "my-asg",
            "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480f03:autoScalingGroupName/my-asg",
            "LaunchTemplate": {
                "LaunchTemplateName": "my-launch-template",
                "Version": "1",
                "LaunchTemplateId": "lt-1234567890abcde12"
            },
            "MinSize": 0,
            "MaxSize": 1,
            "DesiredCapacity": 1,
            "DefaultCooldown": 300,
            "AvailabilityZones": [
                "us-west-2a",
                "us-west-2b",
                "us-west-2c"
            ],
            "LoadBalancerNames": [],
            "TargetGroupARNs": [],
            "HealthCheckType": "EC2",
            "HealthCheckGracePeriod": 0,
            "Instances": [
                {
                    "InstanceId": "i-06905f55584de02da",
                    "InstanceType": "t2.micro",
                    "AvailabilityZone": "us-west-2a",
                    "HealthStatus": "Healthy",
                    "LifecycleState": "InService",
                    "ProtectedFromScaleIn": false,
                    "LaunchTemplate": {
                        "LaunchTemplateName": "my-launch-template",
                        "Version": "1",
                        "LaunchTemplateId": "lt-1234567890abcde12"
                    }
                }
            ],
            "CreatedTime": "2023-10-28T02:39:22.152Z",
            "SuspendedProcesses": [],
            "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782",
            "EnabledMetrics": [],
            "Tags": [],
            "TerminationPolicies": [
                "Default"
            ],
            "NewInstancesProtectedFromScaleIn": false,
            "ServiceLinkedRoleARN":"arn",
            "TrafficSources": []
        }
    ]
}
```
**示例 2：描述前 100 个指定的自动扩缩组**  
此示例将描述指定的自动扩缩组。它允许您指定最多 100 个组名称。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 100 \
    --auto-scaling-group-names "group1" "group2" "group3" "group4"
```
有关输出示例，请参阅示例 1。  
**示例 3：描述指定区域中的自动扩缩组**  
此示例将描述指定区域中的自动扩缩组（最多 75 个组）。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 75 \
    --region us-east-1
```
有关输出示例，请参阅示例 1。  
**示例 4：描述指定数量的自动扩缩组**  
要返回特定数量的自动扩缩组，请使用 `--max-items` 选项。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 1
```
有关输出示例，请参阅示例 1。  
如果输出包含 `NextToken` 字段，则可描述更多组。要获取其他组，请在后续调用中使用此字段的值和 `--starting-token` 选项，如下所示。  

```
aws autoscaling describe-auto-scaling-groups \
    --starting-token Z3M3LMPEXAMPLE
```
有关输出示例，请参阅示例 1。  
**示例 5：描述使用启动配置的自动扩缩组**  
此示例使用 `--query` 选项描述使用启动配置的自动扩缩组。  

```
aws autoscaling describe-auto-scaling-groups \
    --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`]'
```
输出：  

```
[
    {
        "AutoScalingGroupName": "my-asg",
        "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480f03:autoScalingGroupName/my-asg",
        "LaunchConfigurationName": "my-lc",
        "MinSize": 0,
        "MaxSize": 1,
        "DesiredCapacity": 1,
        "DefaultCooldown": 300,
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2b",
            "us-west-2c"
        ],
        "LoadBalancerNames": [],
        "TargetGroupARNs": [],
        "HealthCheckType": "EC2",
        "HealthCheckGracePeriod": 0,
        "Instances": [
            {
                "InstanceId": "i-088c57934a6449037",
                "InstanceType": "t2.micro",
                "AvailabilityZone": "us-west-2c",
                "HealthStatus": "Healthy",
                "LifecycleState": "InService",
                "LaunchConfigurationName": "my-lc",
                "ProtectedFromScaleIn": false
            }
        ],
        "CreatedTime": "2023-10-28T02:39:22.152Z",
        "SuspendedProcesses": [],
        "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782",
        "EnabledMetrics": [],
        "Tags": [],
        "TerminationPolicies": [
            "Default"
        ],
        "NewInstancesProtectedFromScaleIn": false,
        "ServiceLinkedRoleARN":"arn",
        "TrafficSources": []
    }
]
```
有关更多信息，请参阅《*AWS 命令行界面用户指南*》中的[筛选 AWS CLI 输出](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeAutoScalingGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-groups.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest;
import software.amazon.awssdk.services.autoscaling.model.Instance;
import java.util.List;

/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DescribeAutoScalingInstances {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <groupName>

                Where:
                    groupName - The name of the Auto Scaling group.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String groupName = args[0];
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String instanceId = getAutoScaling(autoScalingClient, groupName);
        System.out.println(instanceId);
        autoScalingClient.close();
    }

    public static String getAutoScaling(AutoScalingClient autoScalingClient, String groupName) {
        try {
            String instanceId = "";
            DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            DescribeAutoScalingGroupsResponse response = autoScalingClient
                    .describeAutoScalingGroups(scalingGroupsRequest);
            List<AutoScalingGroup> groups = response.autoScalingGroups();
            for (AutoScalingGroup group : groups) {
                System.out.println("The group name is " + group.autoScalingGroupName());
                System.out.println("The group ARN is " + group.autoScalingGroupARN());

                List<Instance> instances = group.instances();
                for (Instance instance : instances) {
                    instanceId = instance.instanceId();
                }
            }
            return instanceId;
        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun getAutoScalingGroups(groupName: String) {
    val scalingGroupsRequest =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest)
        response.autoScalingGroups?.forEach { group ->
            println("The group name is ${group.autoScalingGroupName}")
            println("The group ARN is ${group.autoScalingGroupArn}")
            group.instances?.forEach { instance ->
                println("The instance id is ${instance.instanceId}")
                println("The lifecycle state is " + instance.lifecycleState)
            }
        }
    }
}
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function describeAutoScalingGroups($autoScalingGroupNames)
    {
        return $this->autoScalingClient->describeAutoScalingGroups([
            'AutoScalingGroupNames' => $autoScalingGroupNames
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出自动扩缩组的名称。**  

```
Get-ASAutoScalingGroup | format-table -property AutoScalingGroupName
```
**输出**：  

```
AutoScalingGroupName
--------------------
my-asg-1
my-asg-2
my-asg-3
my-asg-4
my-asg-5
my-asg-6
```
**示例 2：此示例描述指定的自动扩缩组。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1
```
**输出**：  

```
AutoScalingGroupARN     : arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480
                          f03:autoScalingGroupName/my-asg-1
AutoScalingGroupName    : my-asg-1
AvailabilityZones       : {us-west-2b, us-west-2a}
CreatedTime             : 3/1/2015 9:05:31 AM
DefaultCooldown         : 300
DesiredCapacity         : 2
EnabledMetrics          : {}
HealthCheckGracePeriod  : 300
HealthCheckType         : EC2
Instances               : {my-lc}
LaunchConfigurationName : my-lc
LoadBalancerNames       : {}
MaxSize                 : 0
MinSize                 : 0
PlacementGroup          :
Status                  :
SuspendedProcesses      : {}
Tags                    : {}
TerminationPolicies     : {Default}
VPCZoneIdentifier       : subnet-e4f33493,subnet-5264e837
```
**示例 3：此示例描述指定的两个自动扩缩组。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**示例 4：此示例描述指定自动扩缩组的 Auto Scaling 实例。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**示例 5：此示例描述所有自动扩缩组。**  

```
Get-ASAutoScalingGroup
```
**示例 6：此示例描述了指定 LaunchTemplate 的 Auto Scaling 组。此示例假设“实例购买选项”设置为“遵照启动模板”。如果此选项设置为 “合并购买选项和实例类型”，则 LaunchTemplate 可以使用 “进行访问MixedInstancesPolicy。 LaunchTemplate“财产。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-ag-1).LaunchTemplate
```
**输出**：  

```
LaunchTemplateId     LaunchTemplateName   Version
----------------     ------------------   -------
lt-06095fd619cb40371 test-launch-template $Default
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出自动扩缩组的名称。**  

```
Get-ASAutoScalingGroup | format-table -property AutoScalingGroupName
```
**输出**：  

```
AutoScalingGroupName
--------------------
my-asg-1
my-asg-2
my-asg-3
my-asg-4
my-asg-5
my-asg-6
```
**示例 2：此示例描述指定的自动扩缩组。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1
```
**输出**：  

```
AutoScalingGroupARN     : arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480
                          f03:autoScalingGroupName/my-asg-1
AutoScalingGroupName    : my-asg-1
AvailabilityZones       : {us-west-2b, us-west-2a}
CreatedTime             : 3/1/2015 9:05:31 AM
DefaultCooldown         : 300
DesiredCapacity         : 2
EnabledMetrics          : {}
HealthCheckGracePeriod  : 300
HealthCheckType         : EC2
Instances               : {my-lc}
LaunchConfigurationName : my-lc
LoadBalancerNames       : {}
MaxSize                 : 0
MinSize                 : 0
PlacementGroup          :
Status                  :
SuspendedProcesses      : {}
Tags                    : {}
TerminationPolicies     : {Default}
VPCZoneIdentifier       : subnet-e4f33493,subnet-5264e837
```
**示例 3：此示例描述指定的两个自动扩缩组。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**示例 4：此示例描述指定自动扩缩组的 Auto Scaling 实例。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**示例 5：此示例描述所有自动扩缩组。**  

```
Get-ASAutoScalingGroup
```
**示例 6：此示例描述了指定 LaunchTemplate 的 Auto Scaling 组。此示例假设“实例购买选项”设置为“遵照启动模板”。如果此选项设置为 “合并购买选项和实例类型”，则 LaunchTemplate 可以使用 “进行访问MixedInstancesPolicy。 LaunchTemplate“财产。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-ag-1).LaunchTemplate
```
**输出**：  

```
LaunchTemplateId     LaunchTemplateName   Version
----------------     ------------------   -------
lt-06095fd619cb40371 test-launch-template $Default
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 describe_group(self, group_name: str) -> Optional[Dict[str, Any]]:
        """
        Gets information about an Auto Scaling group.

        :param group_name: The name of the group to look up.
        :return: A dictionary with information about the group if found, otherwise None.
        :raises ClientError: If there is an error describing the Auto Scaling group.
        """
        try:
            paginator = self.autoscaling_client.get_paginator(
                "describe_auto_scaling_groups"
            )
            response_iterator = paginator.paginate(AutoScalingGroupNames=[group_name])
            groups = []
            for response in response_iterator:
                groups.extend(response.get("AutoScalingGroups", []))

            logger.info(
                f"Successfully retrieved information for Auto Scaling group {group_name}."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to describe Auto Scaling group {group_name}.")
            if error_code == "ResourceContentionFault":
                logger.error(
                    "There is a conflict with another operation that is modifying the "
                    f"Auto Scaling group '{group_name}' Please try again later."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
        else:
            return groups[0] if len(groups) > 0 else None
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
async fn list_groups(client: &Client) -> Result<(), Error> {
    let resp = client.describe_auto_scaling_groups().send().await?;

    println!("Groups:");

    let groups = resp.auto_scaling_groups();

    for group in groups {
        println!(
            "Name:  {}",
            group.auto_scaling_group_name().unwrap_or("Unknown")
        );
        println!(
            "Arn:   {}",
            group.auto_scaling_group_arn().unwrap_or("unknown"),
        );
        println!("Zones: {:?}", group.availability_zones(),);
        println!();
    }

    println!("Found {} group(s)", groups.len());

    Ok(())
}
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingGroups](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_groups)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    DATA lt_group_names TYPE /aws1/cl_ascautoscgroupnames_w=>tt_autoscalinggroupnames.
    DATA lo_group_name TYPE REF TO /aws1/cl_ascautoscgroupnames_w.
    
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        " Build group names parameter
        CREATE OBJECT lo_group_name
          EXPORTING
            iv_value = iv_group_name.
        APPEND lo_group_name TO lt_group_names.

        " Describe the Auto Scaling group
        DATA(lo_output) = ao_asc->describeautoscalinggroups(
          it_autoscalinggroupnames = lt_group_names ).

        " Return the first (and only) group in the result
        DATA(lt_groups) = lo_output->get_autoscalinggroups( ).
        IF lines( lt_groups ) > 0.
          READ TABLE lt_groups INDEX 1 INTO DATA(lo_group).
          oo_output = lo_group.
        ENDIF.

        MESSAGE 'Auto Scaling group information retrieved successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `DescribeAutoScalingInstances`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_DescribeAutoScalingInstances_section"></a>

以下代码示例演示如何使用 `DescribeAutoScalingInstances`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Get data about the instances in an Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling details.</returns>
    public async Task<List<AutoScalingInstanceDetails>> DescribeAutoScalingInstancesAsync(
        string groupName)
    {
        var groups = await DescribeAutoScalingGroupsAsync(groupName);
        var instanceIds = new List<string>();
        var instanceDetails = new List<AutoScalingInstanceDetails>();
        if (groups != null)
        {
            groups.ForEach(group =>
            {
                if (group.AutoScalingGroupName == groupName && group.Instances != null)
                {
                    group.Instances.ForEach(instance =>
                    {
                        instanceIds.Add(instance.InstanceId);
                    });
                }
            });

            var scalingGroupsRequest = new DescribeAutoScalingInstancesRequest
            {
                MaxRecords = 10,
                InstanceIds = instanceIds,
            };

            var response =
                await _amazonAutoScaling.DescribeAutoScalingInstancesAsync(
                    scalingGroupsRequest);
            if (response.AutoScalingInstances != null)
            {
                instanceDetails = response.AutoScalingInstances;
            }
        }

        return instanceDetails;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeAutoScalingInstances)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::DescribeAutoScalingInstancesRequest request;
        request.SetInstanceIds(instanceIDs);

        Aws::AutoScaling::Model::DescribeAutoScalingInstancesOutcome outcome =
                client.DescribeAutoScalingInstances(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::AutoScaling::Model::AutoScalingInstanceDetails> &instancesDetails =
                    outcome.GetResult().GetAutoScalingInstances();

        }
        else {
            std::cerr << "Error with AutoScaling::DescribeAutoScalingInstances. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingInstances)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：描述一个或多个实例**  
此示例将描述指定的实例。  

```
aws autoscaling describe-auto-scaling-instances \
    --instance-ids i-06905f55584de02da
```
输出：  

```
{
    "AutoScalingInstances": [
        {
            "InstanceId": "i-06905f55584de02da",
            "InstanceType": "t2.micro",
            "AutoScalingGroupName": "my-asg",
            "AvailabilityZone": "us-west-2b",
            "LifecycleState": "InService",
            "HealthStatus": "HEALTHY",
            "ProtectedFromScaleIn": false,
            "LaunchTemplate": {
                "LaunchTemplateId": "lt-1234567890abcde12",
                "LaunchTemplateName": "my-launch-template",
                "Version": "1"
            }
        }
    ]
}
```
**示例 2：描述一个或多个实例**  
此示例使用 `--max-items` 选项来指定通过此调用返回多少个实例。  

```
aws autoscaling describe-auto-scaling-instances \
    --max-items 1
```
如果输出包含 `NextToken` 字段，可返回更多实例。要获取其他实例，请在后续调用中使用此字段的值和 `--starting-token` 选项，如下所示。  

```
aws autoscaling describe-auto-scaling-instances \
    --starting-token Z3M3LMPEXAMPLE
```
有关输出示例，请参阅示例 1。  
**示例 3：描述使用启动配置的实例**  
此示例使用 `--query` 选项描述使用启动配置的实例。  

```
aws autoscaling describe-auto-scaling-instances \
    --query 'AutoScalingInstances[?LaunchConfigurationName!=`null`]'
```
输出：  

```
[
    {
        "InstanceId": "i-088c57934a6449037",
        "InstanceType": "t2.micro",
        "AutoScalingGroupName": "my-asg",
        "AvailabilityZone": "us-west-2c",
        "LifecycleState": "InService",
        "HealthStatus": "HEALTHY",
        "LaunchConfigurationName": "my-lc",
        "ProtectedFromScaleIn": false
    }
]
```
有关更多信息，请参阅《*AWS 命令行界面用户指南*》中的[筛选 AWS CLI 输出](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeAutoScalingInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-instances.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public static void describeAutoScalingInstance(AutoScalingClient autoScalingClient, String id) {
        try {
            DescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest = DescribeAutoScalingInstancesRequest
                    .builder()
                    .instanceIds(id)
                    .build();

            DescribeAutoScalingInstancesResponse response = autoScalingClient
                    .describeAutoScalingInstances(describeAutoScalingInstancesRequest);
            List<AutoScalingInstanceDetails> instances = response.autoScalingInstances();
            for (AutoScalingInstanceDetails instance : instances) {
                System.out.println("The instance lifecycle state is: " + instance.lifecycleState());
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingInstances)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun describeAutoScalingInstance(id: String) {
    val describeAutoScalingInstancesRequest =
        DescribeAutoScalingInstancesRequest {
            instanceIds = listOf(id)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingInstances(describeAutoScalingInstancesRequest)
        response.autoScalingInstances?.forEach { group ->
            println("The instance lifecycle state is: ${group.lifecycleState}")
        }
    }
}
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function describeAutoScalingInstances($instanceIds)
    {
        return $this->autoScalingClient->describeAutoScalingInstances([
            'InstanceIds' => $instanceIds
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingInstances)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出了您的 IDs Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance | format-table -property InstanceId
```
**输出**：  

```
InstanceId
----------
i-12345678
i-87654321
i-abcd1234
```
**示例 2：此示例描述指定的 Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance -InstanceId i-12345678
```
**输出**：  

```
AutoScalingGroupName    : my-asg
AvailabilityZone        : us-west-2b
HealthStatus            : HEALTHY
InstanceId              : i-12345678
LaunchConfigurationName : my-lc
LifecycleState          : InService
```
**示例 3：此示例描述指定的两个 Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance -InstanceId @("i-12345678", "i-87654321")
```
**示例 4：此示例描述指定自动扩缩组的 Auto Scaling 实例。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**示例 5：此示例描述所有 Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出了您的 IDs Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance | format-table -property InstanceId
```
**输出**：  

```
InstanceId
----------
i-12345678
i-87654321
i-abcd1234
```
**示例 2：此示例描述指定的 Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance -InstanceId i-12345678
```
**输出**：  

```
AutoScalingGroupName    : my-asg
AvailabilityZone        : us-west-2b
HealthStatus            : HEALTHY
InstanceId              : i-12345678
LaunchConfigurationName : my-lc
LifecycleState          : InService
```
**示例 3：此示例描述指定的两个 Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance -InstanceId @("i-12345678", "i-87654321")
```
**示例 4：此示例描述指定自动扩缩组的 Auto Scaling 实例。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**示例 5：此示例描述所有 Auto Scaling 实例。**  

```
Get-ASAutoScalingInstance
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 describe_instances(self, instance_ids: List[str]) -> List[Dict[str, Any]]:
        """
        Gets information about instances.

        :param instance_ids: A list of instance IDs to look up.
        :return: A list of dictionaries with information about each instance,
                 or an empty list if none are found.
        :raises ClientError: If there is an error describing the instances.
        """
        try:
            paginator = self.autoscaling_client.get_paginator(
                "describe_auto_scaling_instances"
            )
            response_iterator = paginator.paginate(InstanceIds=instance_ids)

            instances = []
            for response in response_iterator:
                instances.extend(response.get("AutoScalingInstances", []))

            logger.info(f"Successfully described instances: {instance_ids}")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Couldn't describe instances {instance_ids}. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )
            raise
        else:
            return instances
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingInstances)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    pub async fn list_instances(&self) -> Result<Vec<String>, ScenarioError> {
        // The direct way to list instances is by using DescribeAutoScalingGroup's instances property. However, this returns a Vec<Instance>, as opposed to a Vec<AutoScalingInstanceDetails>.
        // Ok(self.get_group().await?.instances.unwrap_or_default().map(|i| i.instance_id.clone().unwrap_or_default()).filter(|id| !id.is_empty()).collect())

        // Alternatively, and for the sake of example, DescribeAutoScalingInstances returns a list that can be filtered by the client.
        self.autoscaling
            .describe_auto_scaling_instances()
            .into_paginator()
            .items()
            .send()
            .try_collect()
            .await
            .map(|items| {
                items
                    .into_iter()
                    .filter(|i| {
                        i.auto_scaling_group_name.as_deref()
                            == Some(self.auto_scaling_group_name.as_str())
                    })
                    .map(|i| i.instance_id.unwrap_or_default())
                    .filter(|id| !id.is_empty())
                    .collect::<Vec<String>>()
            })
            .map_err(|err| ScenarioError::new("Failed to get list of auto scaling instances", &err))
    }
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingInstances](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_instances)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: it_instance_ids contains a list of instance IDs
    
    TRY.
        DATA(lo_output) = ao_asc->describeautoscalinginstances(
          it_instanceids = it_instance_ids ).

        ot_output = lo_output->get_autoscalinginstances( ).

        MESSAGE 'Auto Scaling instances information retrieved successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DescribeAutoScalingInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeAutoScalingNotificationTypes` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeAutoScalingNotificationTypes_section"></a>

以下代码示例演示如何使用 `DescribeAutoScalingNotificationTypes`。

------
#### [ CLI ]

**AWS CLI**  
**描述可用的通知类型**  
此示例描述可用的通知类型。  

```
aws autoscaling describe-auto-scaling-notification-types
```
输出：  

```
{
    "AutoScalingNotificationTypes": [
        "autoscaling:EC2_INSTANCE_LAUNCH",
        "autoscaling:EC2_INSTANCE_LAUNCH_ERROR",
        "autoscaling:EC2_INSTANCE_TERMINATE",
        "autoscaling:EC2_INSTANCE_TERMINATE_ERROR",
        "autoscaling:TEST_NOTIFICATION"
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[在自动扩缩组扩展时获取 Amazon SNS 通知](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeAutoScalingNotificationTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-notification-types.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的通知类型。**  

```
Get-ASAutoScalingNotificationType
```
**输出**：  

```
autoscaling:EC2_INSTANCE_LAUNCH
autoscaling:EC2_INSTANCE_LAUNCH_ERROR
autoscaling:EC2_INSTANCE_TERMINATE
autoscaling:EC2_INSTANCE_TERMINATE_ERROR
autoscaling:TEST_NOTIFICATION
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的通知类型。**  

```
Get-ASAutoScalingNotificationType
```
**输出**：  

```
autoscaling:EC2_INSTANCE_LAUNCH
autoscaling:EC2_INSTANCE_LAUNCH_ERROR
autoscaling:EC2_INSTANCE_TERMINATE
autoscaling:EC2_INSTANCE_TERMINATE_ERROR
autoscaling:TEST_NOTIFICATION
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeLaunchConfigurations` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeLaunchConfigurations_section"></a>

以下代码示例演示如何使用 `DescribeLaunchConfigurations`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：描述指定的启动配置**  
此示例描述指定的启动配置。  

```
aws autoscaling describe-launch-configurations \
    --launch-configuration-names my-launch-config
```
输出：  

```
{
    "LaunchConfigurations": [
        {
            "LaunchConfigurationName": "my-launch-config",
            "LaunchConfigurationARN": "arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:98d3b196-4cf9-4e88-8ca1-8547c24ced8b:launchConfigurationName/my-launch-config",
            "ImageId": "ami-0528a5175983e7f28",
            "KeyName": "my-key-pair-uswest2",
            "SecurityGroups": [
                "sg-05eaec502fcdadc2e"
            ],
            "ClassicLinkVPCSecurityGroups": [],
            "UserData": "",
            "InstanceType": "t2.micro",
            "KernelId": "",
            "RamdiskId": "",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/xvda",
                    "Ebs": {
                        "SnapshotId": "snap-06c1606ba5ca274b1",
                        "VolumeSize": 8,
                        "VolumeType": "gp2",
                        "DeleteOnTermination": true,
                        "Encrypted": false
                    }
                }
            ],
            "InstanceMonitoring": {
                "Enabled": true
            },
            "CreatedTime": "2020-10-28T02:39:22.321Z",
            "EbsOptimized": false,
            "AssociatePublicIpAddress": true,
            "MetadataOptions": {
                "HttpTokens": "required",
                "HttpPutResponseHopLimit": 1,
                "HttpEndpoint": "disabled"
            }
        }
    ]
}
```
**示例 2：描述指定数量的启动配置**  
要返回特定数量的启动配置，请使用 `--max-items` 选项。  

```
aws autoscaling describe-launch-configurations \
    --max-items 1
```
如果输出包含 `NextToken` 字段，则可返回更多启动配置。要获取其他启动配置，请在后续调用中使用此字段的值和 `--starting-token` 选项，如下所示。  

```
aws autoscaling describe-launch-configurations \
    --starting-token Z3M3LMPEXAMPLE
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeLaunchConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-launch-configurations.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出启动配置的名称。**  

```
Get-ASLaunchConfiguration | format-table -property LaunchConfigurationName
```
**输出**：  

```
LaunchConfigurationName
-----------------------
my-lc-1
my-lc-2
my-lc-3
my-lc-4
my-lc-5
```
**示例 2：此示例描述指定的启动配置。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName my-lc-1
```
**输出**：  

```
AssociatePublicIpAddress     : True
BlockDeviceMappings          : {/dev/xvda}
ClassicLinkVPCId             :
ClassicLinkVPCSecurityGroups : {}
CreatedTime                  : 12/12/2014 3:22:08 PM
EbsOptimized                 : False
IamInstanceProfile           :
ImageId                      : ami-043a5034
InstanceMonitoring           : Amazon.AutoScaling.Model.InstanceMonitoring
InstanceType                 : t2.micro
KernelId                     :
KeyName                      : 
LaunchConfigurationARN       : arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:7e5f31e4-693b-4604-9322-
                               e6f68d7fafad:launchConfigurationName/my-lc-1
LaunchConfigurationName      : my-lc-1
PlacementTenancy             :
RamdiskId                    :
SecurityGroups               : {sg-67ef0308}
SpotPrice                    :
UserData                     :
```
**示例 3：此示例描述指定的两种启动配置。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName @("my-lc-1", "my-lc-2")
```
**示例 4：此示例描述所有启动配置。**  

```
Get-ASLaunchConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出启动配置的名称。**  

```
Get-ASLaunchConfiguration | format-table -property LaunchConfigurationName
```
**输出**：  

```
LaunchConfigurationName
-----------------------
my-lc-1
my-lc-2
my-lc-3
my-lc-4
my-lc-5
```
**示例 2：此示例描述指定的启动配置。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName my-lc-1
```
**输出**：  

```
AssociatePublicIpAddress     : True
BlockDeviceMappings          : {/dev/xvda}
ClassicLinkVPCId             :
ClassicLinkVPCSecurityGroups : {}
CreatedTime                  : 12/12/2014 3:22:08 PM
EbsOptimized                 : False
IamInstanceProfile           :
ImageId                      : ami-043a5034
InstanceMonitoring           : Amazon.AutoScaling.Model.InstanceMonitoring
InstanceType                 : t2.micro
KernelId                     :
KeyName                      : 
LaunchConfigurationARN       : arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:7e5f31e4-693b-4604-9322-
                               e6f68d7fafad:launchConfigurationName/my-lc-1
LaunchConfigurationName      : my-lc-1
PlacementTenancy             :
RamdiskId                    :
SecurityGroups               : {sg-67ef0308}
SpotPrice                    :
UserData                     :
```
**示例 3：此示例描述指定的两种启动配置。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName @("my-lc-1", "my-lc-2")
```
**示例 4：此示例描述所有启动配置。**  

```
Get-ASLaunchConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeLifecycleHookTypes` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeLifecycleHookTypes_section"></a>

以下代码示例演示如何使用 `DescribeLifecycleHookTypes`。

------
#### [ CLI ]

**AWS CLI**  
**描述可用的生命周期挂钩类型**  
此示例描述可用的生命周期挂钩类型。  

```
aws autoscaling describe-lifecycle-hook-types
```
输出：  

```
{
    "LifecycleHookTypes": [
        "autoscaling:EC2_INSTANCE_LAUNCHING",
        "autoscaling:EC2_INSTANCE_TERMINATING"
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeLifecycleHookTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-lifecycle-hook-types.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的生命周期挂钩类型。**  

```
Get-ASLifecycleHookType
```
**输出**：  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的生命周期挂钩类型。**  

```
Get-ASLifecycleHookType
```
**输出**：  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeLifecycleHooks` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeLifecycleHooks_section"></a>

以下代码示例演示如何使用 `DescribeLifecycleHooks`。

------
#### [ CLI ]

**AWS CLI**  
**描述您的生命周期挂钩**  
此示例描述指定自动扩缩组的生命周期挂钩。  

```
aws autoscaling describe-lifecycle-hooks \
    --auto-scaling-group-name my-asg
```
输出：  

```
{
    "LifecycleHooks": [
        {
            "GlobalTimeout": 3000,
            "HeartbeatTimeout": 30,
            "AutoScalingGroupName": "my-asg",
            "LifecycleHookName": "my-launch-hook",
            "DefaultResult": "ABANDON",
            "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING"
        },
        {
            "GlobalTimeout": 6000,
            "HeartbeatTimeout": 60,
            "AutoScalingGroupName": "my-asg",
            "LifecycleHookName": "my-termination-hook",
            "DefaultResult": "CONTINUE",
            "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeLifecycleHooks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-lifecycle-hooks.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述指定的生命周期挂钩。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**输出**：  

```
AutoScalingGroupName  : my-asg
DefaultResult         : ABANDON
GlobalTimeout         : 172800
HeartbeatTimeout      : 3600
LifecycleHookName     : myLifecycleHook
LifecycleTransition   : auto-scaling:EC2_INSTANCE_LAUNCHING
NotificationMetadata  :
NotificationTargetARN : arn:aws:sns:us-west-2:123456789012:my-topic
RoleARN               : arn:aws:iam::123456789012:role/my-iam-role
```
**示例 2：此示例描述指定自动扩缩组的所有生命周期挂钩。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**示例 3：此示例描述所有自动扩缩组的所有生命周期挂钩。**  

```
Get-ASLifecycleHook
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定的生命周期挂钩。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**输出**：  

```
AutoScalingGroupName  : my-asg
DefaultResult         : ABANDON
GlobalTimeout         : 172800
HeartbeatTimeout      : 3600
LifecycleHookName     : myLifecycleHook
LifecycleTransition   : auto-scaling:EC2_INSTANCE_LAUNCHING
NotificationMetadata  :
NotificationTargetARN : arn:aws:sns:us-west-2:123456789012:my-topic
RoleARN               : arn:aws:iam::123456789012:role/my-iam-role
```
**示例 2：此示例描述指定自动扩缩组的所有生命周期挂钩。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**示例 3：此示例描述所有自动扩缩组的所有生命周期挂钩。**  

```
Get-ASLifecycleHook
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeLoadBalancers` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeLoadBalancers_section"></a>

以下代码示例演示如何使用 `DescribeLoadBalancers`。

------
#### [ CLI ]

**AWS CLI**  
**描述自动扩缩组的经典负载均衡器**  
此示例描述指定自动扩缩组的经典负载均衡器。  

```
aws autoscaling describe-load-balancers \
    --auto-scaling-group-name my-asg
```
输出：  

```
{
    "LoadBalancers": [
        {
            "State": "Added",
            "LoadBalancerName": "my-load-balancer"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-load-balancers.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述指定自动扩缩组的负载均衡器。**  

```
Get-ASLoadBalancer -AutoScalingGroupName my-asg
```
**输出**：  

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组的负载均衡器。**  

```
Get-ASLoadBalancer -AutoScalingGroupName my-asg
```
**输出**：  

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeMetricCollectionTypes` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeMetricCollectionTypes_section"></a>

以下代码示例演示如何使用 `DescribeMetricCollectionTypes`。

------
#### [ CLI ]

**AWS CLI**  
**描述可用的指标收集类型**  
此示例描述可用的指标收集类型。  

```
aws autoscaling describe-metric-collection-types
```
输出：  

```
{
    "Metrics": [
        {
            "Metric": "GroupMinSize"
        },
        {
            "Metric": "GroupMaxSize"
        },
        {
            "Metric": "GroupDesiredCapacity"
        },
        {
            "Metric": "GroupInServiceInstances"
        },
        {
            "Metric": "GroupInServiceCapacity"
        },
        {
            "Metric": "GroupPendingInstances"
        },
        {
            "Metric": "GroupPendingCapacity"
        },
        {
            "Metric": "GroupTerminatingInstances"
        },
        {
            "Metric": "GroupTerminatingCapacity"
        },
        {
            "Metric": "GroupStandbyInstances"
        },
        {
            "Metric": "GroupStandbyCapacity"
        },
        {
            "Metric": "GroupTotalInstances"
        },
        {
            "Metric": "GroupTotalCapacity"
        }
    ],
    "Granularities": [
        {
            "Granularity": "1Minute"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[自动扩缩组指标](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html#as-group-metrics)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeMetricCollectionTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-metric-collection-types.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的指标收集类型。**  

```
(Get-ASMetricCollectionType).Metrics
```
**输出**：  

```
Metric
------
GroupMinSize
GroupMaxSize
GroupDesiredCapacity
GroupInServiceInstances
GroupPendingInstances
GroupTerminatingInstances
GroupStandbyInstances
GroupTotalInstances
```
**示例 2：此示例列出相应的粒度。**  

```
(Get-ASMetricCollectionType).Granularities
```
**输出**：  

```
Granularity
-----------
1Minute
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的指标收集类型。**  

```
(Get-ASMetricCollectionType).Metrics
```
**输出**：  

```
Metric
------
GroupMinSize
GroupMaxSize
GroupDesiredCapacity
GroupInServiceInstances
GroupPendingInstances
GroupTerminatingInstances
GroupStandbyInstances
GroupTotalInstances
```
**示例 2：此示例列出相应的粒度。**  

```
(Get-ASMetricCollectionType).Granularities
```
**输出**：  

```
Granularity
-----------
1Minute
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeNotificationConfigurations` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeNotificationConfigurations_section"></a>

以下代码示例演示如何使用 `DescribeNotificationConfigurations`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：描述指定组的通知配置**  
此示例描述指定自动扩缩组的通知配置。  

```
aws autoscaling describe-notification-configurations \
    --auto-scaling-group-name my-asg
```
输出：  

```
{
    "NotificationConfigurations": [
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic-2"
        },
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[在自动扩缩组扩展时获取 Amazon SNS 通知](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html)。  
**示例 1：描述指定数量的通知配置**  
要返回特定数量的通知配置，请使用 `max-items` 参数。  

```
aws autoscaling describe-notification-configurations \
    --auto-scaling-group-name my-auto-scaling-group \
    --max-items 1
```
输出：  

```
{
    "NotificationConfigurations": [
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic-2"
        },
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic"
        }
    ]
}
```
如果输出包含 `NextToken` 字段，可返回更多通知配置。要获取其他通知配置，请在后续调用中使用此字段的值和 `starting-token` 选项，如下所示。  

```
aws autoscaling describe-notification-configurations \
    --auto-scaling-group-name my-asg \
    --starting-token Z3M3LMPEXAMPLE
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[在自动扩缩组扩展时获取 Amazon SNS 通知](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeNotificationConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-notification-configurations.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述与指定自动扩缩组关联的通知操作。**  

```
Get-ASNotificationConfiguration -AutoScalingGroupName my-asg | format-list
```
**输出**：  

```
AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_LAUNCH
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic

AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_TERMINATE
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic
```
**示例 2：此示例描述与所有自动扩缩组关联的通知操作。**  

```
Get-ASNotificationConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述与指定自动扩缩组关联的通知操作。**  

```
Get-ASNotificationConfiguration -AutoScalingGroupName my-asg | format-list
```
**输出**：  

```
AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_LAUNCH
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic

AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_TERMINATE
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic
```
**示例 2：此示例描述与所有自动扩缩组关联的通知操作。**  

```
Get-ASNotificationConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribePolicies` 与 CLI 配合使用
<a name="example_auto-scaling_DescribePolicies_section"></a>

以下代码示例演示如何使用 `DescribePolicies`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：描述指定组的扩缩策略**  
此示例描述指定自动扩缩组的扩展策略。  

```
aws autoscaling describe-policies \
    --auto-scaling-group-name my-asg
```
输出：  

```
{
    "ScalingPolicies": [
        {
            "AutoScalingGroupName": "my-asg",
            "PolicyName": "alb1000-target-tracking-scaling-policy",
            "PolicyARN": "arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:3065d9c8-9969-4bec-bb6a-3fbe5550fde6:autoScalingGroupName/my-asg:policyName/alb1000-target-tracking-scaling-policy",
            "PolicyType": "TargetTrackingScaling",
            "StepAdjustments": [],
            "Alarms": [
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmHigh-924887a9-12d7-4e01-8686-6f844d13a196",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmHigh-924887a9-12d7-4e01-8686-6f844d13a196"
                },
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmLow-f96f899d-b8e7-4d09-a010-c1aaa35da296",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmLow-f96f899d-b8e7-4d09-a010-c1aaa35da296"
                }
            ],
            "TargetTrackingConfiguration": {
                "PredefinedMetricSpecification": {
                    "PredefinedMetricType": "ALBRequestCountPerTarget",
                    "ResourceLabel": "app/my-alb/778d41231b141a0f/targetgroup/my-alb-target-group/943f017f100becff"
                },
                "TargetValue": 1000.0,
                "DisableScaleIn": false
            },
            "Enabled": true
        },
        {
            "AutoScalingGroupName": "my-asg",
            "PolicyName": "cpu40-target-tracking-scaling-policy",
            "PolicyARN": "arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:5fd26f71-39d4-4690-82a9-b8515c45cdde:autoScalingGroupName/my-asg:policyName/cpu40-target-tracking-scaling-policy",
            "PolicyType": "TargetTrackingScaling",
            "StepAdjustments": [],
            "Alarms": [
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmHigh-139f9789-37b9-42ad-bea5-b5b147d7f473",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmHigh-139f9789-37b9-42ad-bea5-b5b147d7f473"
                },
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmLow-bd681c67-fc18-4c56-8468-fb8e413009c9",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmLow-bd681c67-fc18-4c56-8468-fb8e413009c9"
                }
            ],
            "TargetTrackingConfiguration": {
                "PredefinedMetricSpecification": {
                    "PredefinedMetricType": "ASGAverageCPUUtilization"
                },
                "TargetValue": 40.0,
                "DisableScaleIn": false
            },
            "Enabled": true
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[动态扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html)。  
**示例 2：描述指定名称的扩展策略**  
要返回特定的扩展策略，请使用 `--policy-names` 选项。  

```
aws autoscaling describe-policies \
    --auto-scaling-group-name my-asg \
    --policy-names cpu40-target-tracking-scaling-policy
```
有关输出示例，请参阅示例 1。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[动态扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html)。  
**示例 3：描述多种扩展策略**  
要返回特定数量的策略，请使用 `--max-items` 选项。  

```
aws autoscaling describe-policies \
    --auto-scaling-group-name my-asg \
    --max-items 1
```
有关输出示例，请参阅示例 1。  
如果输出包含 `NextToken` 字段，则请在后续调用中使用此字段的值和 `--starting-token` 选项获取其他策略。  

```
aws autoscaling describe-policies --auto-scaling-group-name my-asg --starting-token Z3M3LMPEXAMPLE
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[动态扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-policies.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述指定自动扩缩组的所有策略。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg
```
**输出**：  

```
AdjustmentType          : ChangeInCapacity
Alarms                  : {}
AutoScalingGroupName    : my-asg
Cooldown                : 0
EstimatedInstanceWarmup : 0
MetricAggregationType   :
MinAdjustmentMagnitude  : 0
MinAdjustmentStep       : 0
PolicyARN               : arn:aws:auto-scaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef
                          :autoScalingGroupName/my-asg:policyName/myScaleInPolicy
PolicyName              : myScaleInPolicy
PolicyType              : SimpleScaling
ScalingAdjustment       : -1
StepAdjustments         : {}
```
**示例 2：此示例描述指定自动扩缩组的指定策略。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**示例 3：此示例描述所有自动扩缩组的所有策略。**  

```
Get-ASPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribePolicies](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组的所有策略。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg
```
**输出**：  

```
AdjustmentType          : ChangeInCapacity
Alarms                  : {}
AutoScalingGroupName    : my-asg
Cooldown                : 0
EstimatedInstanceWarmup : 0
MetricAggregationType   :
MinAdjustmentMagnitude  : 0
MinAdjustmentStep       : 0
PolicyARN               : arn:aws:auto-scaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef
                          :autoScalingGroupName/my-asg:policyName/myScaleInPolicy
PolicyName              : myScaleInPolicy
PolicyType              : SimpleScaling
ScalingAdjustment       : -1
StepAdjustments         : {}
```
**示例 2：此示例描述指定自动扩缩组的指定策略。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**示例 3：此示例描述所有自动扩缩组的所有策略。**  

```
Get-ASPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribePolicies](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `DescribeScalingActivities`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_DescribeScalingActivities_section"></a>

以下代码示例演示如何使用 `DescribeScalingActivities`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Retrieve a list of the Amazon EC2 Auto Scaling activities for an
    /// Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling activities.</returns>
    public async Task<List<Activity>> DescribeScalingActivitiesAsync(
        string groupName)
    {
        var activities = new List<Activity>();
        var scalingActivitiesRequest = new DescribeScalingActivitiesRequest
        {
            AutoScalingGroupName = groupName,
            MaxRecords = 10,
        };

        var response = await _amazonAutoScaling.DescribeScalingActivitiesAsync(scalingActivitiesRequest);
        if (response.Activities != null)
        {
            activities = response.Activities;
        }
        return activities;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DescribeScalingActivities](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeScalingActivities)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::DescribeScalingActivitiesRequest request;
        request.SetAutoScalingGroupName(groupName);

        Aws::Vector<Aws::AutoScaling::Model::Activity> allActivities;
        Aws::String nextToken; // Used for pagination;
        do {
            if (!nextToken.empty()) {
                request.SetNextToken(nextToken);
            }
            Aws::AutoScaling::Model::DescribeScalingActivitiesOutcome outcome =
                    autoScalingClient.DescribeScalingActivities(request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::AutoScaling::Model::Activity> &activities =
                        outcome.GetResult().GetActivities();
                allActivities.insert(allActivities.end(), activities.begin(), activities.end());
                nextToken  = outcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error with AutoScaling::DescribeScalingActivities. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

            }
        } while (!nextToken.empty());

        std::cout << "Found " << allActivities.size() << " activities."
                  << std::endl;
        std::cout << "Activities are ordered with the most recent first."
                  << std::endl;
        for (const Aws::AutoScaling::Model::Activity &activity: allActivities) {
            std::cout << activity.GetDescription() << std::endl;
            std::cout << activity.GetDetails() << std::endl;
        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeScalingActivities)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：描述指定组的扩展活动**  
此示例描述指定自动扩缩组的扩展活动。  

```
aws autoscaling describe-scaling-activities \
    --auto-scaling-group-name my-asg
```
输出：  

```
{
    "Activities": [
        {
            "ActivityId": "f9f2d65b-f1f2-43e7-b46d-d86756459699",
            "Description": "Launching a new EC2 instance: i-0d44425630326060f",
            "AutoScalingGroupName": "my-asg",
            "Cause": "At 2020-10-30T19:35:51Z a user request update of AutoScalingGroup constraints to min: 0, max: 16, desired: 16 changing the desired capacity from 0 to 16.  At 2020-10-30T19:36:07Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 16.",
            "StartTime": "2020-10-30T19:36:09.766Z",
            "EndTime": "2020-10-30T19:36:41Z",
            "StatusCode": "Successful",
            "Progress": 100,
            "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[验证自动扩缩组的扩展活动](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-verify-scaling-activity.html)。  
**示例 2：描述已删除组的扩展活动**  
要在删除自动扩缩组后描述扩展活动，请添加 `--include-deleted-groups` 选项。  

```
aws autoscaling describe-scaling-activities \
    --auto-scaling-group-name my-asg \
    --include-deleted-groups
```
输出：  

```
{
    "Activities": [
        {
            "ActivityId": "e1f5de0e-f93e-1417-34ac-092a76fba220",
            "Description": "Launching a new EC2 instance.  Status Reason: Your Spot request price of 0.001 is lower than the minimum required Spot request fulfillment price of 0.0031. Launching EC2 instance failed.",
            "AutoScalingGroupName": "my-asg",
            "Cause": "At 2021-01-13T20:47:24Z a user request update of AutoScalingGroup constraints to min: 1, max: 5, desired: 3 changing the desired capacity from 0 to 3.  At 2021-01-13T20:47:27Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 3.",
            "StartTime": "2021-01-13T20:47:30.094Z",
            "EndTime": "2021-01-13T20:47:30Z",
            "StatusCode": "Failed",
            "StatusMessage": "Your Spot request price of 0.001 is lower than the minimum required Spot request fulfillment price of 0.0031. Launching EC2 instance failed.",
            "Progress": 100,
            "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}",
            "AutoScalingGroupState": "Deleted",
            "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:283179a2-f3ce-423d-93f6-66bb518232f7:autoScalingGroupName/my-asg"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[排除 Amazon EC2 Auto Scaling 问题](https://docs.aws.amazon.com/autoscaling/ec2/userguide/CHAP_Troubleshooting.html)。  
**示例 3：描述指定数量的扩展活动**  
要返回特定数量的活动，请使用 `--max-items` 选项。  

```
aws autoscaling describe-scaling-activities \
    --max-items 1
```
输出：  

```
{
    "Activities": [
        {
            "ActivityId": "f9f2d65b-f1f2-43e7-b46d-d86756459699",
            "Description": "Launching a new EC2 instance: i-0d44425630326060f",
            "AutoScalingGroupName": "my-asg",
            "Cause": "At 2020-10-30T19:35:51Z a user request update of AutoScalingGroup constraints to min: 0, max: 16, desired: 16 changing the desired capacity from 0 to 16.  At 2020-10-30T19:36:07Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 16.",
            "StartTime": "2020-10-30T19:36:09.766Z",
            "EndTime": "2020-10-30T19:36:41Z",
            "StatusCode": "Successful",
            "Progress": 100,
            "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}"
        }
    ]
}
```
如果输出包含 `NextToken` 字段，可返回更多活动。要获取其他活动，请在后续调用中使用此字段的值和 `--starting-token` 选项，如下所示。  

```
aws autoscaling describe-scaling-activities \
    --starting-token Z3M3LMPEXAMPLE
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[验证自动扩缩组的扩展活动](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-verify-scaling-activity.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeScalingActivities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-scaling-activities.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public static void describeScalingActivities(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DescribeScalingActivitiesRequest scalingActivitiesRequest = DescribeScalingActivitiesRequest.builder()
                    .autoScalingGroupName(groupName)
                    .maxRecords(10)
                    .build();

            DescribeScalingActivitiesResponse response = autoScalingClient
                    .describeScalingActivities(scalingActivitiesRequest);
            List<Activity> activities = response.activities();
            for (Activity activity : activities) {
                System.out.println("The activity Id is " + activity.activityId());
                System.out.println("The activity details are " + activity.details());
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeScalingActivities)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun describeAutoScalingGroups(groupName: String) {
    val groupsReques =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
            maxRecords = 10
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingGroups(groupsReques)
        response.autoScalingGroups?.forEach { group ->
            println("The service to use for the health checks: ${group.healthCheckType}")
        }
    }
}
```
+  有关 API 的详细信息，请参阅适用[DescribeScalingActivities](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function describeScalingActivities($autoScalingGroupName)
    {
        return $this->autoScalingClient->describeScalingActivities([
            'AutoScalingGroupName' => $autoScalingGroupName,
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeScalingActivities)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述指定自动扩缩组过去六周的扩缩活动。**  

```
Get-ASScalingActivity -AutoScalingGroupName my-asg
```
**输出**：  

```
ActivityId           : 063308ae-aa22-4a9b-94f4-9fae4EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:45:16Z a user request explicitly set group desired capacity changing the desired
                       capacity from 1 to 2.  At 2015-11-22T15:45:34Z an instance was started in response to a difference
                       between desired and actual capacity, increasing the capacity from 1 to 2.
Description          : Launching a new EC2 instance: i-26e715fc
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/22/2015 7:46:09 AM
Progress             : 100
StartTime            : 11/22/2015 7:45:35 AM
StatusCode           : Successful
StatusMessage        :

ActivityId           : ce719997-086d-4c73-a2f1-ab703EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:57:53Z a user request created an AutoScalingGroup changing the desired capacity
                        from 0 to 1.  At 2015-11-20T22:57:58Z an instance was started in response to a difference betwe
                       en desired and actual capacity, increasing the capacity from 0 to 1.
Description          : Launching a new EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/20/2015 2:58:32 PM
Progress             : 100
StartTime            : 11/20/2015 2:57:59 PM
StatusCode           : Successful
StatusMessage        :
```
**示例 2：此示例描述指定的扩缩活动。**  

```
Get-ASScalingActivity -ActivityId "063308ae-aa22-4a9b-94f4-9fae4EXAMPLE"
```
**示例 3：此示例描述所有自动扩缩组过去六周的扩缩活动。**  

```
Get-ASScalingActivity
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组过去六周的扩缩活动。**  

```
Get-ASScalingActivity -AutoScalingGroupName my-asg
```
**输出**：  

```
ActivityId           : 063308ae-aa22-4a9b-94f4-9fae4EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:45:16Z a user request explicitly set group desired capacity changing the desired
                       capacity from 1 to 2.  At 2015-11-22T15:45:34Z an instance was started in response to a difference
                       between desired and actual capacity, increasing the capacity from 1 to 2.
Description          : Launching a new EC2 instance: i-26e715fc
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/22/2015 7:46:09 AM
Progress             : 100
StartTime            : 11/22/2015 7:45:35 AM
StatusCode           : Successful
StatusMessage        :

ActivityId           : ce719997-086d-4c73-a2f1-ab703EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:57:53Z a user request created an AutoScalingGroup changing the desired capacity
                        from 0 to 1.  At 2015-11-20T22:57:58Z an instance was started in response to a difference betwe
                       en desired and actual capacity, increasing the capacity from 0 to 1.
Description          : Launching a new EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/20/2015 2:58:32 PM
Progress             : 100
StartTime            : 11/20/2015 2:57:59 PM
StatusCode           : Successful
StatusMessage        :
```
**示例 2：此示例描述指定的扩缩活动。**  

```
Get-ASScalingActivity -ActivityId "063308ae-aa22-4a9b-94f4-9fae4EXAMPLE"
```
**示例 3：此示例描述所有自动扩缩组过去六周的扩缩活动。**  

```
Get-ASScalingActivity
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 describe_scaling_activities(self, group_name: str) -> List[Dict[str, Any]]:
        """
        Gets information about scaling activities for the group. Scaling activities
        are things like instances stopping or starting in response to user requests
        or capacity changes.

        :param group_name: The name of the group to look up.
        :return: A list of dictionaries representing the scaling activities for the
                 group, ordered with the most recent activity first.
        :raises ClientError: If there is an error describing the scaling activities.
        """
        try:
            paginator = self.autoscaling_client.get_paginator(
                "describe_scaling_activities"
            )
            response_iterator = paginator.paginate(AutoScalingGroupName=group_name)
            activities = []
            for response in response_iterator:
                activities.extend(response.get("Activities", []))

            logger.info(
                f"Successfully described scaling activities for group '{group_name}'."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Couldn't describe scaling activities for group '{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."
                )
            raise
        else:
            return activities
```
+  有关 API 的详细信息，请参阅适用[DescribeScalingActivities](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeScalingActivities)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    pub async fn describe_scenario(&self) -> AutoScalingScenarioDescription {
        let group = self
            .autoscaling
            .describe_auto_scaling_groups()
            .auto_scaling_group_names(self.auto_scaling_group_name.clone())
            .send()
            .await
            .map(|s| {
                s.auto_scaling_groups()
                    .iter()
                    .map(|s| {
                        format!(
                            "{}: {}",
                            s.auto_scaling_group_name().unwrap_or("Unknown"),
                            s.status().unwrap_or("Unknown")
                        )
                    })
                    .collect::<Vec<String>>()
            })
            .map_err(|e| {
                ScenarioError::new("Failed to describe auto scaling groups for scenario", &e)
            });

        let instances = self
            .list_instances()
            .await
            .map_err(|e| anyhow!("There was an error listing instances: {e}",));

        // 10. DescribeScalingActivities: list the scaling activities that have occurred for the group so far.
        //   Bonus: use CloudWatch API to get and show some metrics collected for the group.
        //   CW.ListMetrics with Namespace='AWS/AutoScaling' and Dimensions=[{'Name': 'AutoScalingGroupName', 'Value': }]
        //   CW.GetMetricStatistics with Statistics='Sum'. Start and End times must be in UTC!
        let activities = self
            .autoscaling
            .describe_scaling_activities()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .into_paginator()
            .items()
            .send()
            .collect::<Result<Vec<_>, _>>()
            .await
            .map_err(|e| {
                anyhow!(
                    "There was an error retrieving scaling activities: {}",
                    DisplayErrorContext(&e)
                )
            });

        AutoScalingScenarioDescription {
            group,
            instances,
            activities,
        }
    }
```
+  有关 API 的详细信息，请参阅适用[DescribeScalingActivities](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_scaling_activities)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        DATA(lo_output) = ao_asc->describescalingactivities(
          iv_autoscalinggroupname = iv_group_name ).

        ot_output = lo_output->get_activities( ).

        MESSAGE 'Scaling activities retrieved successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DescribeScalingActivities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeScalingProcessTypes` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeScalingProcessTypes_section"></a>

以下代码示例演示如何使用 `DescribeScalingProcessTypes`。

------
#### [ CLI ]

**AWS CLI**  
**描述可用的进程类型**  
此示例描述可用的流程类型。  

```
aws autoscaling describe-scaling-process-types
```
输出：  

```
{
    "Processes": [
        {
            "ProcessName": "AZRebalance"
        },
        {
            "ProcessName": "AddToLoadBalancer"
        },
        {
            "ProcessName": "AlarmNotification"
        },
        {
            "ProcessName": "HealthCheck"
        },
        {
            "ProcessName": "InstanceRefresh"
        },
        {
            "ProcessName": "Launch"
        },
        {
            "ProcessName": "ReplaceUnhealthy"
        },
        {
            "ProcessName": "ScheduledActions"
        },
        {
            "ProcessName": "Terminate"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[暂停和恢复扩展流程](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeScalingProcessTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-scaling-process-types.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的进程类型。**  

```
Get-ASScalingProcessType
```
**输出**：  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的进程类型。**  

```
Get-ASScalingProcessType
```
**输出**：  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeScheduledActions` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeScheduledActions_section"></a>

以下代码示例演示如何使用 `DescribeScheduledActions`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：描述所有计划操作**  
此示例描述所有计划操作。  

```
aws autoscaling describe-scheduled-actions
```
输出：  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
**示例 2：描述指定组的计划操作**  
要描述特定自动扩缩组的计划操作，请使用 `--auto-scaling-group-name` 选项。  

```
aws autoscaling describe-scheduled-actions \
    --auto-scaling-group-name my-asg
```
输出：  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
**示例 3：描述指定的计划操作**  
要描述特定的计划操作，请使用 `--scheduled-action-names` 选项。  

```
aws autoscaling describe-scheduled-actions \
    --scheduled-action-names my-recurring-action
```
输出：  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
**示例 4：描述具有指定开始时间的计划操作**  
要描述在特定时间开始的计划操作，请使用 `--start-time` 选项。  

```
aws autoscaling describe-scheduled-actions \
    --start-time "2023-12-01T04:00:00Z"
```
输出：  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
**示例 5：描述在指定时间结束的计划操作**  
要描述在特定时间结束的计划操作，请使用 `--end-time` 选项。  

```
aws autoscaling describe-scheduled-actions \
    --end-time "2023-12-01T04:00:00Z"
```
输出：  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
**示例 6：描述指定数量的计划操作**  
要返回特定数量的计划操作，请使用 `--max-items` 选项。  

```
aws autoscaling describe-scheduled-actions \
    --auto-scaling-group-name my-asg \
    --max-items 1
```
输出：  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
如果输出包含 `NextToken` 字段，可返回更多计划操作。要获取其他计划操作，请在后续调用中使用此字段的值和 `--starting-token` 选项，如下所示。  

```
aws autoscaling describe-scheduled-actions \
    --auto-scaling-group-name my-asg \
    --starting-token Z3M3LMPEXAMPLE
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeScheduledActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-scheduled-actions.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述指定自动扩缩组的计划扩缩操作。**  

```
Get-ASScheduledAction -AutoScalingGroupName my-asg
```
**输出**：  

```
AutoScalingGroupName : my-asg
DesiredCapacity      : 10
EndTime              : 
MaxSize              : 
MinSize              : 
Recurrence           :
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8a4c5f24-6ec6-4306-a2dd-f7
                       2c3af3a4d6:autoScalingGroupName/my-asg:scheduledActionName/myScheduledAction
ScheduledActionName  : myScheduledAction
StartTime            : 11/30/2015 8:00:00 AM
Time                 : 11/30/2015 8:00:00 AM
```
**示例 2：此示例描述指定的计划扩缩操作。**  

```
Get-ASScheduledAction -ScheduledActionName @("myScheduledScaleOut", "myScheduledScaleIn")
```
**示例 3：此示例描述在指定时间开始的计划扩缩操作。**  

```
Get-ASScheduledAction -StartTime "2015-12-01T08:00:00Z"
```
**示例 4：此示例描述在指定时间结束的计划扩缩操作。**  

```
Get-ASScheduledAction -EndTime "2015-12-30T08:00:00Z"
```
**示例 5：此示例描述所有自动扩缩组的计划扩缩操作。**  

```
Get-ASScheduledAction
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述指定自动扩缩组的计划扩缩操作。**  

```
Get-ASScheduledAction -AutoScalingGroupName my-asg
```
**输出**：  

```
AutoScalingGroupName : my-asg
DesiredCapacity      : 10
EndTime              : 
MaxSize              : 
MinSize              : 
Recurrence           :
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8a4c5f24-6ec6-4306-a2dd-f7
                       2c3af3a4d6:autoScalingGroupName/my-asg:scheduledActionName/myScheduledAction
ScheduledActionName  : myScheduledAction
StartTime            : 11/30/2015 8:00:00 AM
Time                 : 11/30/2015 8:00:00 AM
```
**示例 2：此示例描述指定的计划扩缩操作。**  

```
Get-ASScheduledAction -ScheduledActionName @("myScheduledScaleOut", "myScheduledScaleIn")
```
**示例 3：此示例描述在指定时间开始的计划扩缩操作。**  

```
Get-ASScheduledAction -StartTime "2015-12-01T08:00:00Z"
```
**示例 4：此示例描述在指定时间结束的计划扩缩操作。**  

```
Get-ASScheduledAction -EndTime "2015-12-30T08:00:00Z"
```
**示例 5：此示例描述所有自动扩缩组的计划扩缩操作。**  

```
Get-ASScheduledAction
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeTags` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeTags_section"></a>

以下代码示例演示如何使用 `DescribeTags`。

------
#### [ CLI ]

**AWS CLI**  
**描述所有标签**  
此示例描述所有标签。  

```
aws autoscaling describe-tags
```
输出：  

```
{
    "Tags": [
        {
            "ResourceType": "auto-scaling-group",
            "ResourceId": "my-asg",
            "PropagateAtLaunch": true,
            "Value": "Research",
            "Key": "Dept"
        },
        {
            "ResourceType": "auto-scaling-group",
            "ResourceId": "my-asg",
            "PropagateAtLaunch": true,
            "Value": "WebServer",
            "Key": "Role"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[标记自动扩缩组和实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)。  
**示例 2：描述指定组的标签**  
要描述特定自动扩缩组的标签，请使用 `--filters` 选项。  

```
aws autoscaling describe-tags --filters Name=auto-scaling-group,Values=my-asg
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[标记自动扩缩组和实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)。  
**示例 3：描述指定数量的标签**  
要返回特定数量的标签，请使用 `--max-items` 选项。  

```
aws autoscaling describe-tags \
    --max-items 1
```
如果输出包含 `NextToken` 字段，则可返回更多标签。要获取其他标签，请在后续调用中使用此字段的值和 `--starting-token` 选项，如下所示。  

```
aws autoscaling describe-tags \
    --filters Name=auto-scaling-group,Values=my-asg \
    --starting-token Z3M3LMPEXAMPLE
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[标记自动扩缩组和实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-tags.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例描述键值为“myTag”或“myTag2”的标签。筛选器名称的可能值为 ''、auto-scaling-group 'key'、'value' 和 'propagate-at-launch'。此示例使用的语法需要 PowerShell 版本 3 或更高版本。**  

```
Get-ASTag -Filter @( @{ Name="key"; Values=@("myTag", "myTag2") } )
```
**输出**：  

```
Key               : myTag2
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue2

Key               : myTag
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue
```
**示例 2：在 PowerShell 版本 2 中，必须使用 New-Object 为过滤器参数创建过滤器。**  

```
$keys = New-Object string[] 2
$keys[0] = "myTag"
$keys[1] = "myTag2"
$filter = New-Object Amazon.AutoScaling.Model.Filter
$filter.Name = "key"
$filter.Values = $keys
Get-ASTag -Filter @( $filter )
```
**示例 3：此示例描述所有自动扩缩组的所有标签。**  

```
Get-ASTag
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例描述键值为“myTag”或“myTag2”的标签。筛选器名称的可能值为 ''、auto-scaling-group 'key'、'value' 和 'propagate-at-launch'。此示例使用的语法需要 PowerShell 版本 3 或更高版本。**  

```
Get-ASTag -Filter @( @{ Name="key"; Values=@("myTag", "myTag2") } )
```
**输出**：  

```
Key               : myTag2
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue2

Key               : myTag
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue
```
**示例 2：在 PowerShell 版本 2 中，必须使用 New-Object 为过滤器参数创建过滤器。**  

```
$keys = New-Object string[] 2
$keys[0] = "myTag"
$keys[1] = "myTag2"
$filter = New-Object Amazon.AutoScaling.Model.Filter
$filter.Name = "key"
$filter.Values = $keys
Get-ASTag -Filter @( $filter )
```
**示例 3：此示例描述所有自动扩缩组的所有标签。**  

```
Get-ASTag
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DescribeTerminationPolicyTypes` 与 CLI 配合使用
<a name="example_auto-scaling_DescribeTerminationPolicyTypes_section"></a>

以下代码示例演示如何使用 `DescribeTerminationPolicyTypes`。

------
#### [ CLI ]

**AWS CLI**  
**描述可用的终止策略类型**  
此示例描述可用的终止策略类型。  

```
aws autoscaling describe-termination-policy-types
```
输出：  

```
{
    "TerminationPolicyTypes": [
        "AllocationStrategy",
        "ClosestToNextInstanceHour",
        "Default",
        "NewestInstance",
        "OldestInstance",
        "OldestLaunchConfiguration",
        "OldestLaunchTemplate"
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[控制在横向缩减期间终止哪些自动扩缩实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeTerminationPolicyTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-termination-policy-types.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的终止策略。**  

```
Get-ASTerminationPolicyType
```
**输出**：  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例列出 Auto Scaling 支持的终止策略。**  

```
Get-ASTerminationPolicyType
```
**输出**：  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DetachInstances` 与 CLI 配合使用
<a name="example_auto-scaling_DetachInstances_section"></a>

以下代码示例演示如何使用 `DetachInstances`。

------
#### [ CLI ]

**AWS CLI**  
**将实例与自动扩缩组分离**  
此示例将指定实例与指定的自动扩缩组分离。  

```
aws autoscaling detach-instances \
    --instance-ids i-030017cfa84b20135 \
    --auto-scaling-group-name my-asg \
    --should-decrement-desired-capacity
```
输出：  

```
{
    "Activities": [
        {
            "ActivityId": "5091cb52-547a-47ce-a236-c9ccbc2cb2c9",
            "AutoScalingGroupName": "my-asg",
            "Description": "Detaching EC2 instance: i-030017cfa84b20135",
            "Cause": "At 2020-10-31T17:35:04Z instance i-030017cfa84b20135 was detached in response to a user request, shrinking the capacity from 2 to 1.",
            "StartTime": "2020-04-12T15:02:16.179Z",
            "StatusCode": "InProgress",
            "Progress": 50,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DetachInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/detach-instances.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的实例与指定的自动扩缩组分离，并减少所需容量以使 Auto Scaling 不启动替换实例。**  

```
Dismount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**输出**：  

```
ActivityId           : 06733445-ce94-4039-be1b-b9f1866e276e
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-93633f9b was detached in response to a user request, shrinking
                       the capacity from 2 to 1.
Description          : Detaching EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
**示例 2：此示例将在不减少所需容量的情况下将指定的实例与指定的自动扩缩组分离。Auto Scaling 会启动一个替换实例。**  

```
Dismount-ASInstance -InstanceId i-7bf746a2 -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**输出**：  

```
ActivityId           : f43a3cd4-d38c-4af7-9fe0-d76ec2307b6d
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-7bf746a2 was detached in response to a user request.
Description          : Detaching EC2 instance: i-7bf746a2
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DetachInstances](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的实例与指定的自动扩缩组分离，并减少所需容量以使 Auto Scaling 不启动替换实例。**  

```
Dismount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**输出**：  

```
ActivityId           : 06733445-ce94-4039-be1b-b9f1866e276e
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-93633f9b was detached in response to a user request, shrinking
                       the capacity from 2 to 1.
Description          : Detaching EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
**示例 2：此示例将在不减少所需容量的情况下将指定的实例与指定的自动扩缩组分离。Auto Scaling 会启动一个替换实例。**  

```
Dismount-ASInstance -InstanceId i-7bf746a2 -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**输出**：  

```
ActivityId           : f43a3cd4-d38c-4af7-9fe0-d76ec2307b6d
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-7bf746a2 was detached in response to a user request.
Description          : Detaching EC2 instance: i-7bf746a2
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DetachInstances](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `DetachLoadBalancers` 与 CLI 配合使用
<a name="example_auto-scaling_DetachLoadBalancers_section"></a>

以下代码示例演示如何使用 `DetachLoadBalancers`。

------
#### [ CLI ]

**AWS CLI**  
**将经典负载均衡器与自动扩缩组分离**  
此示例将指定的经典负载均衡器与指定的自动扩缩组分离。  

```
aws autoscaling detach-load-balancers \
    --load-balancer-names my-load-balancer \
    --auto-scaling-group-name my-asg
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[将负载均衡器挂接到自动扩缩组](https://docs.aws.amazon.com/autoscaling/ec2/userguide/attach-load-balancer-asg.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DetachLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/detach-load-balancers.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的负载均衡器与指定的自动扩缩组分离。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的负载均衡器与指定的自动扩缩组分离。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `DisableMetricsCollection`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_DisableMetricsCollection_section"></a>

以下代码示例演示如何使用 `DisableMetricsCollection`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Disable the collection of metric data for an Amazon EC2 Auto Scaling
    /// group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <returns>A Boolean value that indicates the success or failure of
    /// the operation.</returns>
    public async Task<bool> DisableMetricsCollectionAsync(string groupName)
    {
        var request = new DisableMetricsCollectionRequest
        {
            AutoScalingGroupName = groupName,
        };

        var response = await _amazonAutoScaling.DisableMetricsCollectionAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[DisableMetricsCollection](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DisableMetricsCollection)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::DisableMetricsCollectionRequest request;
        request.SetAutoScalingGroupName(groupName);

        Aws::AutoScaling::Model::DisableMetricsCollectionOutcome outcome =
                autoScalingClient.DisableMetricsCollection(request);

        if (outcome.IsSuccess()) {
            std::cout << "Metrics collection has been disabled." << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::DisableMetricsCollection. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DisableMetricsCollection)*中的。

------
#### [ CLI ]

**AWS CLI**  
**禁用自动扩缩组指标收集**  
此示例禁用指定自动扩缩组的 `GroupDesiredCapacity` 指标的收集。  

```
aws autoscaling disable-metrics-collection \
    --auto-scaling-group-name my-asg \
    --metrics GroupDesiredCapacity
```
此命令不生成任何输出。  
有关更多信息，请参阅 *Amazon EC2 Auto Scaling 用户指南中的 Auto Scaling* [组和实例的监控 CloudWatch 指标](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DisableMetricsCollection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/disable-metrics-collection.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public static void disableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DisableMetricsCollectionRequest disableMetricsCollectionRequest = DisableMetricsCollectionRequest.builder()
                    .autoScalingGroupName(groupName)
                    .metrics("GroupMaxSize")
                    .build();

            autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest);
            System.out.println("The disable metrics collection operation was successful");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DisableMetricsCollection)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun disableMetricsCollection(groupName: String) {
    val disableMetricsCollectionRequest =
        DisableMetricsCollectionRequest {
            autoScalingGroupName = groupName
            metrics = listOf("GroupMaxSize")
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest)
        println("The disable metrics collection operation was successful")
    }
}
```
+  有关 API 的详细信息，请参阅适用[DisableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function disableMetricsCollection($autoScalingGroupName)
    {
        return $this->autoScalingClient->disableMetricsCollection([
            'AutoScalingGroupName' => $autoScalingGroupName,
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DisableMetricsCollection)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例禁用对指定自动扩缩组指定指标的监控。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**示例 2：此示例禁用对指定自动扩缩组所有指标的监控。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例禁用对指定自动扩缩组指定指标的监控。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**示例 2：此示例禁用对指定自动扩缩组所有指标的监控。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 disable_metrics(self, group_name: str) -> Dict[str, Any]:
        """
        Stops CloudWatch metric collection for the Auto Scaling group.

        :param group_name: The name of the group.
        :return: A dictionary with the response from disabling the metrics collection.
        :raises ClientError: If there is an error disabling metrics collection.
        """
        try:
            response = self.autoscaling_client.disable_metrics_collection(
                AutoScalingGroupName=group_name
            )
            logger.info(
                f"Successfully disabled metrics collection for group '{group_name}'."
            )
            return response
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Couldn't disable metrics for group '{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."
                )
            raise
```
+  有关 API 的详细信息，请参阅适用[DisableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DisableMetricsCollection)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        // If this fails it's fine, just means there are extra cloudwatch metrics events for the scale-down.
        let _ = self
            .autoscaling
            .disable_metrics_collection()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .send()
            .await;
```
+  有关 API 的详细信息，请参阅适用[DisableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.disable_metrics_collection)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        ao_asc->disablemetricscollection(
          iv_autoscalinggroupname = iv_group_name ).

        MESSAGE 'Metrics collection disabled successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[DisableMetricsCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `EnableMetricsCollection`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_EnableMetricsCollection_section"></a>

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

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <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;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[EnableMetricsCollection](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/EnableMetricsCollection)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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;

        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/EnableMetricsCollection)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：启用自动扩缩组的指标收集**  
此示例启用指定自动扩缩组的数据收集。  

```
aws autoscaling enable-metrics-collection \
    --auto-scaling-group-name my-asg \
    --granularity "1Minute"
```
此命令不生成任何输出。  
有关更多信息，请参阅 *Amazon EC2 Auto Scaling 用户指南中的 Auto Scaling* [组和实例的监控 CloudWatch 指标](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html)。  
**示例 2：收集自动扩缩组指定指标的相关数据**  
要收集特定指标的相关数据，请使用 `--metrics` 选项。  

```
aws autoscaling enable-metrics-collection \
    --auto-scaling-group-name my-asg \
    --metrics GroupDesiredCapacity --granularity "1Minute"
```
此命令不生成任何输出。  
有关更多信息，请参阅 *Amazon EC2 Auto Scaling 用户指南中的 Auto Scaling* [组和实例的监控 CloudWatch 指标](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[EnableMetricsCollection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/enable-metrics-collection.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    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);
        }
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/EnableMetricsCollection)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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")
    }
}
```
+  有关 API 的详细信息，请参阅适用[EnableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function enableMetricsCollection($autoScalingGroupName, $granularity)
    {
        return $this->autoScalingClient->enableMetricsCollection([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'Granularity' => $granularity,
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/EnableMetricsCollection)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例启用对指定自动扩缩组指定指标的监控。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**示例 2：此示例启用对指定自动扩缩组所有指标的监控。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用对指定自动扩缩组指定指标的监控。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**示例 2：此示例启用对指定自动扩缩组所有指标的监控。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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
```
+  有关 API 的详细信息，请参阅适用[EnableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/EnableMetricsCollection)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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;
```
+  有关 API 的详细信息，请参阅适用[EnableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.enable_metrics_collection)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: it_metrics contains list of metrics like 'GroupMinSize', 'GroupMaxSize', etc.
    
    TRY.
        ao_asc->enablemetricscollection(
          iv_autoscalinggroupname = iv_group_name
          it_metrics = it_metrics
          iv_granularity = '1Minute' ).

        MESSAGE 'Metrics collection enabled successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[EnableMetricsCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `EnterStandby` 与 CLI 配合使用
<a name="example_auto-scaling_EnterStandby_section"></a>

以下代码示例演示如何使用 `EnterStandby`。

------
#### [ CLI ]

**AWS CLI**  
**将实例移入备用模式**  
此示例将指定实例置于备用模式。这对于更新当前正在使用的实例或对其进行问题排查非常有用。  

```
aws autoscaling enter-standby \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg \
    --should-decrement-desired-capacity
```
输出：  

```
{
    "Activities": [
        {
            "ActivityId": "ffa056b4-6ed3-41ba-ae7c-249dfae6eba1",
            "AutoScalingGroupName": "my-asg",
            "Description": "Moving EC2 instance to Standby: i-061c63c5eb45f0416",
            "Cause": "At 2020-10-31T20:31:00Z instance i-061c63c5eb45f0416 was moved to standby in response to a user request, shrinking the capacity from 1 to 0.",
            "StartTime": "2020-10-31T20:31:00.949Z",
            "StatusCode": "InProgress",
            "Progress": 50,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 实例生命周期](https://docs.aws.amazon.com/autoscaling/ec2/userguide/detach-instance-asg.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[EnterStandby](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/enter-standby.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定实例置于备用模式并减少所需容量，以使 Auto Scaling 不启动替换实例。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**输出**：  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request,
                       shrinking the capacity from 2 to 1.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
**示例 2：此示例在不减少所需容量的情况下将指定实例置于备用模式。Auto Scaling 会启动一个替换实例。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**输出**：  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [EnterStandby](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定实例置于备用模式并减少所需容量，以使 Auto Scaling 不启动替换实例。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**输出**：  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request,
                       shrinking the capacity from 2 to 1.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
**示例 2：此示例在不减少所需容量的情况下将指定实例置于备用模式。Auto Scaling 会启动一个替换实例。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**输出**：  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [EnterStandby](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `ExecutePolicy` 与 CLI 配合使用
<a name="example_auto-scaling_ExecutePolicy_section"></a>

以下代码示例演示如何使用 `ExecutePolicy`。

------
#### [ CLI ]

**AWS CLI**  
**执行扩缩策略**  
此示例将对指定的自动扩缩组执行名为 `my-step-scale-out-policy` 的扩展策略。  

```
aws autoscaling execute-policy \
    --auto-scaling-group-name my-asg \
    --policy-name  my-step-scale-out-policy \
    --metric-value 95 \
    --breach-threshold 80
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[步进和简单扩展策略](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ExecutePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/execute-policy.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例对指定的自动扩缩组执行指定的策略。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**示例 2：此示例在等待冷却时间结束后，对指定的自动扩缩组执行指定的策略。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [ExecutePolicy](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例对指定的自动扩缩组执行指定的策略。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**示例 2：此示例在等待冷却时间结束后，对指定的自动扩缩组执行指定的策略。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ExecutePolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `ExitStandby` 与 CLI 配合使用
<a name="example_auto-scaling_ExitStandby_section"></a>

以下代码示例演示如何使用 `ExitStandby`。

------
#### [ CLI ]

**AWS CLI**  
**将实例移出备用模式**  
此示例将指定的实例移出备用模式。  

```
aws autoscaling exit-standby \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg
```
输出：  

```
{
    "Activities": [
        {
            "ActivityId": "142928e1-a2dc-453a-9b24-b85ad6735928",
            "AutoScalingGroupName": "my-asg",
            "Description": "Moving EC2 instance out of Standby: i-061c63c5eb45f0416",
            "Cause": "At 2020-10-31T20:32:50Z instance i-061c63c5eb45f0416 was moved out of standby in response to a user request, increasing the capacity from 0 to 1.",
            "StartTime": "2020-10-31T20:32:50.222Z",
            "StatusCode": "PreInService",
            "Progress": 30,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[临时从自动扩缩组中移除实例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-enter-exit-standby.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ExitStandby](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/exit-standby.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的实例移出备用模式。**  

```
Exit-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
**输出**：  

```
ActivityId           : 1833d3e8-e32f-454e-b731-0670ad4c6934
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:51:21Z instance i-95b8484f was moved out of standby in response to a user 
                       request, increasing the capacity from 1 to 2.
Description          : Moving EC2 instance out of Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 30
StartTime            : 11/22/2015 7:51:21 AM
StatusCode           : PreInService
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [ExitStandby](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的实例移出备用模式。**  

```
Exit-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
**输出**：  

```
ActivityId           : 1833d3e8-e32f-454e-b731-0670ad4c6934
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:51:21Z instance i-95b8484f was moved out of standby in response to a user 
                       request, increasing the capacity from 1 to 2.
Description          : Moving EC2 instance out of Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 30
StartTime            : 11/22/2015 7:51:21 AM
StatusCode           : PreInService
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ExitStandby](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `PutLifecycleHook` 与 CLI 配合使用
<a name="example_auto-scaling_PutLifecycleHook_section"></a>

以下代码示例演示如何使用 `PutLifecycleHook`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：创建生命周期挂钩**  
此示例创建一个生命周期挂钩，该挂钩将在任何新启动的实例上调用，超时时间为 4800 秒。这对于在用户数据脚本完成之前保持实例处于等待状态或使用调用 Lambd AWS a 函数非常有用。 EventBridge  

```
aws autoscaling put-lifecycle-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-hook-name my-launch-hook \
    --lifecycle-transition autoscaling:EC2_INSTANCE_LAUNCHING \
    --heartbeat-timeout 4800
```
此命令不生成任何输出。如果已存在同名的生命周期挂钩，则该挂钩将被新的生命周期挂钩覆盖。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 生命周期挂钩](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)。  
**示例 2：发送 Amazon SNS 电子邮件以通知您实例状态转换**  
此示例创建一个包含 Amazon SNS 主题和 IAM 角色的生命周期挂钩，用于在实例启动时接收通知。  

```
aws autoscaling put-lifecycle-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-hook-name my-launch-hook \
    --lifecycle-transition autoscaling:EC2_INSTANCE_LAUNCHING \
    --notification-target-arn arn:aws:sns:us-west-2:123456789012:my-sns-topic \
    --role-arn arn:aws:iam::123456789012:role/my-auto-scaling-role
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 生命周期挂钩](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)。  
**示例 3：向 Amazon SQS 队列发布消息**  
此示例创建一个生命周期挂钩，该挂钩将包含元数据的消息发布到指定的 Amazon SQS 队列。  

```
aws autoscaling put-lifecycle-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-hook-name my-launch-hook \
    --lifecycle-transition autoscaling:EC2_INSTANCE_LAUNCHING \
    --notification-target-arn arn:aws:sqs:us-west-2:123456789012:my-sqs-queue \
    --role-arn arn:aws:iam::123456789012:role/my-notification-role \
    --notification-metadata "SQS message metadata"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 生命周期挂钩](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[PutLifecycleHook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-lifecycle-hook.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的生命周期挂钩添加到指定的自动扩缩组。**  

```
Write-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName "myLifecycleHook" -LifecycleTransition "autoscaling:EC2_INSTANCE_LAUNCHING" -NotificationTargetARN "arn:aws:sns:us-west-2:123456789012:my-sns-topic" -RoleARN "arn:aws:iam::123456789012:role/my-iam-role"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [PutLifecycleHook](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的生命周期挂钩添加到指定的自动扩缩组。**  

```
Write-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName "myLifecycleHook" -LifecycleTransition "autoscaling:EC2_INSTANCE_LAUNCHING" -NotificationTargetARN "arn:aws:sns:us-west-2:123456789012:my-sns-topic" -RoleARN "arn:aws:iam::123456789012:role/my-iam-role"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `PutNotificationConfiguration` 与 CLI 配合使用
<a name="example_auto-scaling_PutNotificationConfiguration_section"></a>

以下代码示例演示如何使用 `PutNotificationConfiguration`。

------
#### [ CLI ]

**AWS CLI**  
**添加通知**  
此示例将指定的通知添加到指定的自动扩缩组。  

```
aws autoscaling put-notification-configuration \
    --auto-scaling-group-name my-asg \
    --topic-arn arn:aws:sns:us-west-2:123456789012:my-sns-topic \
    --notification-type autoscaling:TEST_NOTIFICATION
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[在自动扩缩组扩展时获取 Amazon SNS 通知](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html#as-configure-asg-for-sns)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[PutNotificationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-notification-configuration.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的自动扩缩组配置为在启动 EC2 实例时向指定的 SNS 主题发送通知。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType "autoscaling:EC2_INSTANCE_LAUNCH" -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**示例 2：此示例将指定的自动扩缩组配置为在启动或终止 EC2 实例时向指定的 SNS 主题发送通知。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType @("autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_TERMINATE") -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的自动扩缩组配置为在启动 EC2 实例时向指定的 SNS 主题发送通知。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType "autoscaling:EC2_INSTANCE_LAUNCH" -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**示例 2：此示例将指定的自动扩缩组配置为在启动或终止 EC2 实例时向指定的 SNS 主题发送通知。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType @("autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_TERMINATE") -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `PutScalingPolicy` 与 CLI 配合使用
<a name="example_auto-scaling_PutScalingPolicy_section"></a>

以下代码示例演示如何使用 `PutScalingPolicy`。

------
#### [ CLI ]

**AWS CLI**  
**向自动扩缩组添加目标跟踪扩缩策略**  
以下 `put-scaling-policy` 示例将目标跟踪扩展策略应用到指定的自动扩缩组。输出包含代表您创建的两个 CloudWatch 警报的 ARNs 和名称。如果已存在同名扩缩策略，则该扩展策略将被新扩展策略覆盖。  

```
aws autoscaling put-scaling-policy --auto-scaling-group-name my-asg \
  --policy-name alb1000-target-tracking-scaling-policy \
  --policy-type TargetTrackingScaling \
  --target-tracking-configuration file://config.json
```
`config.json` 的内容：  

```
{
     "TargetValue": 1000.0,
     "PredefinedMetricSpecification": {
          "PredefinedMetricType": "ALBRequestCountPerTarget",
          "ResourceLabel": "app/my-alb/778d41231b141a0f/targetgroup/my-alb-target-group/943f017f100becff"
     }
}
```
输出：  

```
{
     "PolicyARN": "arn:aws:autoscaling:region:account-id:scalingPolicy:228f02c2-c665-4bfd-aaac-8b04080bea3c:autoScalingGroupName/my-asg:policyName/alb1000-target-tracking-scaling-policy",
     "Alarms": [
         {
             "AlarmARN": "arn:aws:cloudwatch:region:account-id:alarm:TargetTracking-my-asg-AlarmHigh-fc0e4183-23ac-497e-9992-691c9980c38e",
             "AlarmName": "TargetTracking-my-asg-AlarmHigh-fc0e4183-23ac-497e-9992-691c9980c38e"
         },
         {
             "AlarmARN": "arn:aws:cloudwatch:region:account-id:alarm:TargetTracking-my-asg-AlarmLow-61a39305-ed0c-47af-bd9e-471a352ee1a2",
             "AlarmName": "TargetTracking-my-asg-AlarmLow-61a39305-ed0c-47af-bd9e-471a352ee1a2"
         }
     ]
 }
```
有关更多示例，请参阅 *Amazon EC2 Auto Scaling 用户指南中的 AWS 命令行界面 (AWS CLI) 扩展*[策略](https://docs.aws.amazon.com/autoscaling/ec2/userguide/examples-scaling-policies.html)示例。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[PutScalingPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-scaling-policy.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定的策略添加到指定的自动扩缩组。指定的调整类型决定了如何解释 ScalingAdjustment 参数。使用 “ChangeInCapacity” 时，正值将按指定的实例数量增加容量，负值则按指定的实例数量减少容量。**  

```
Write-ASScalingPolicy -AutoScalingGroupName my-asg -AdjustmentType "ChangeInCapacity" -PolicyName "myScaleInPolicy" -ScalingAdjustment -1
```
**输出**：  

```
arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef:autoScalingGroupName/my-asg
:policyName/myScaleInPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [PutScalingPolicy](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定的策略添加到指定的自动扩缩组。指定的调整类型决定了如何解释 ScalingAdjustment 参数。使用 “ChangeInCapacity” 时，正值将按指定的实例数量增加容量，负值则按指定的实例数量减少容量。**  

```
Write-ASScalingPolicy -AutoScalingGroupName my-asg -AdjustmentType "ChangeInCapacity" -PolicyName "myScaleInPolicy" -ScalingAdjustment -1
```
**输出**：  

```
arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef:autoScalingGroupName/my-asg
:policyName/myScaleInPolicy
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `PutScheduledUpdateGroupAction` 与 CLI 配合使用
<a name="example_auto-scaling_PutScheduledUpdateGroupAction_section"></a>

以下代码示例演示如何使用 `PutScheduledUpdateGroupAction`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：向自动扩缩组添加计划操作**  
此示例将指定的计划操作添加到指定的自动扩缩组。  

```
aws autoscaling put-scheduled-update-group-action \
    --auto-scaling-group-name my-asg \
    --scheduled-action-name my-scheduled-action \
    --start-time "2023-05-12T08:00:00Z" \
    --min-size 2 \
    --max-size 6 \
    --desired-capacity 4
```
此命令不生成任何输出。如果已存在同名的计划操作，则该计划操作将被新计划操作覆盖。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
**示例 2：指定周期性计划**  
此示例创建一个计划操作，以按计划在每年一月、六月和十二月的第一天 00:30 执行的周期性计划进行扩展。  

```
aws autoscaling put-scheduled-update-group-action \
    --auto-scaling-group-name my-asg \
    --scheduled-action-name my-recurring-action \
    --recurrence "30 0 1 1,6,12 *" \
    --min-size 2 \
    --max-size 6 \
    --desired-capacity 4
```
此命令不生成任何输出。如果已存在同名的计划操作，则该计划操作将被新计划操作覆盖。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[计划扩展](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[PutScheduledUpdateGroupAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-scheduled-update-group-action.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例创建或更新一次性计划操作，以在指定的开始时间更改所需容量。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例创建或更新一次性计划操作，以在指定的开始时间更改所需容量。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `RecordLifecycleActionHeartbeat` 与 CLI 配合使用
<a name="example_auto-scaling_RecordLifecycleActionHeartbeat_section"></a>

以下代码示例演示如何使用 `RecordLifecycleActionHeartbeat`。

------
#### [ CLI ]

**AWS CLI**  
**记录生命周期操作心跳**  
此示例记录生命周期操作心跳，以使实例保持待处理状态。  

```
aws autoscaling record-lifecycle-action-heartbeat \
    --lifecycle-hook-name my-launch-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-action-token bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Amazon EC2 Auto Scaling 生命周期挂钩](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[RecordLifecycleActionHeartbeat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/record-lifecycle-action-heartbeat.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例记录指定生命周期操作的心跳。这会使实例保持待处理状态，直到您完成自定义操作。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例记录指定生命周期操作的心跳。这会使实例保持待处理状态，直到您完成自定义操作。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `ResumeProcesses` 与 CLI 配合使用
<a name="example_auto-scaling_ResumeProcesses_section"></a>

以下代码示例演示如何使用 `ResumeProcesses`。

------
#### [ CLI ]

**AWS CLI**  
**恢复暂停的进程**  
此示例恢复指定自动扩缩组的指定暂停扩展流程。  

```
aws autoscaling resume-processes \
    --auto-scaling-group-name my-asg \
    --scaling-processes AlarmNotification
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[暂停和恢复扩展流程](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ResumeProcesses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/resume-processes.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例恢复指定自动扩缩组的指定 Auto Scaling 进程。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**示例 2：此示例恢复指定自动扩缩组的所有暂停 Auto Scaling 进程。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [ResumeProcesses](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例恢复指定自动扩缩组的指定 Auto Scaling 进程。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**示例 2：此示例恢复指定自动扩缩组的所有暂停 Auto Scaling 进程。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [ResumeProcesses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `SetDesiredCapacity`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_SetDesiredCapacity_section"></a>

以下代码示例演示如何使用 `SetDesiredCapacity`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Set the desired capacity of an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <param name="desiredCapacity">The desired capacity for the Auto
    /// Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> SetDesiredCapacityAsync(
        string groupName,
        int desiredCapacity)
    {
        var capacityRequest = new SetDesiredCapacityRequest
        {
            AutoScalingGroupName = groupName,
            DesiredCapacity = desiredCapacity,
        };

        var response = await _amazonAutoScaling.SetDesiredCapacityAsync(capacityRequest);
        Console.WriteLine($"You have set the DesiredCapacity to {desiredCapacity}.");

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[SetDesiredCapacity](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/SetDesiredCapacity)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::SetDesiredCapacityRequest request;
        request.SetAutoScalingGroupName(groupName);
        request.SetDesiredCapacity(2);

        Aws::AutoScaling::Model::SetDesiredCapacityOutcome outcome =
                autoScalingClient.SetDesiredCapacity(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error with AutoScaling::SetDesiredCapacityRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/SetDesiredCapacity)*中的。

------
#### [ CLI ]

**AWS CLI**  
**为自动扩缩组设置所需容量**  
此示例为指定的自动扩缩组设置所需容量。  

```
aws autoscaling set-desired-capacity \
    --auto-scaling-group-name my-asg \
    --desired-capacity 2 \
    --honor-cooldown
```
如果成功，该命令将返回到提示符。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[SetDesiredCapacity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/set-desired-capacity.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public static void setDesiredCapacity(AutoScalingClient autoScalingClient, String groupName) {
        try {
            SetDesiredCapacityRequest capacityRequest = SetDesiredCapacityRequest.builder()
                    .autoScalingGroupName(groupName)
                    .desiredCapacity(2)
                    .build();

            autoScalingClient.setDesiredCapacity(capacityRequest);
            System.out.println("You have set the DesiredCapacity to 2");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/SetDesiredCapacity)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun setDesiredCapacity(groupName: String) {
    val capacityRequest =
        SetDesiredCapacityRequest {
            autoScalingGroupName = groupName
            desiredCapacity = 2
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.setDesiredCapacity(capacityRequest)
        println("You set the DesiredCapacity to 2")
    }
}
```
+  有关 API 的详细信息，请参阅适用[SetDesiredCapacity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function setDesiredCapacity($autoScalingGroupName, $desiredCapacity)
    {
        return $this->autoScalingClient->setDesiredCapacity([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'DesiredCapacity' => $desiredCapacity,
        ]);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/SetDesiredCapacity)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例设置指定自动扩缩组的大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**示例 2：此示例设置指定自动扩缩组的大小，并等待冷却时间结束后再扩缩到新大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例设置指定自动扩缩组的大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**示例 2：此示例设置指定自动扩缩组的大小，并等待冷却时间结束后再扩缩到新大小。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 set_desired_capacity(self, group_name: str, capacity: int) -> None:
        """
        Sets the desired capacity of the group. Amazon EC2 Auto Scaling tries to keep the
        number of running instances equal to the desired capacity.

        :param group_name: The name of the group to update.
        :param capacity: The desired number of running instances.
        :return: None
        :raises ClientError: If there is an error setting the desired capacity.
        """
        try:
            self.autoscaling_client.set_desired_capacity(
                AutoScalingGroupName=group_name,
                DesiredCapacity=capacity,
                HonorCooldown=False,
            )
            logger.info(
                f"Successfully set desired capacity of {capacity} for Auto Scaling group '{group_name}'."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Failed to set desired capacity for Auto Scaling group '{group_name}'."
            )
            if error_code == "ScalingActivityInProgress":
                logger.error(
                    f"A scaling activity is currently in progress for the Auto Scaling group '{group_name}'. "
                    "Please wait for the activity to complete before attempting to set the desired capacity."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  有关 API 的详细信息，请参阅适用[SetDesiredCapacity](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/SetDesiredCapacity)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    pub async fn scale_desired_capacity(&self, capacity: i32) -> Result<(), ScenarioError> {
        // 7. SetDesiredCapacity: set desired capacity to 2.
        //   Wait for a second instance to launch.
        let update_group = self
            .autoscaling
            .set_desired_capacity()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .desired_capacity(capacity)
            .send()
            .await;
        if let Err(err) = update_group {
            return Err(ScenarioError::new(
                format!("Failed to update group to desired capacity ({capacity}))").as_str(),
                &err,
            ));
        }
        Ok(())
    }
```
+  有关 API 的详细信息，请参阅适用[SetDesiredCapacity](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.set_desired_capacity)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: iv_capacity = 2
    
    TRY.
        ao_asc->setdesiredcapacity(
          iv_autoscalinggroupname = iv_group_name
          iv_desiredcapacity = iv_capacity
          iv_honorcooldown = abap_false ).

        MESSAGE 'Desired capacity set successfully' TYPE 'I'.

      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[SetDesiredCapacity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `SetInstanceHealth` 与 CLI 配合使用
<a name="example_auto-scaling_SetInstanceHealth_section"></a>

以下代码示例演示如何使用 `SetInstanceHealth`。

------
#### [ CLI ]

**AWS CLI**  
**设置实例的运行状况**  
此示例将指定实例的运行状况设置为 `Unhealthy`。  

```
aws autoscaling set-instance-health \
    --instance-id i-061c63c5eb45f0416 \
    --health-status Unhealthy
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[SetInstanceHealth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/set-instance-health.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将指定实例的状态设置为“运行状况不佳”，使其停止服务。Auto Scaling 会终止并替换该实例。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**示例 2：此示例将指定实例的状态设置为“运行状况正常”，使其保持服务状态。未遵守自动扩缩组的任何运行状况检查宽限期。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [SetInstanceHealth](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例将指定实例的状态设置为“运行状况不佳”，使其停止服务。Auto Scaling 会终止并替换该实例。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**示例 2：此示例将指定实例的状态设置为“运行状况正常”，使其保持服务状态。未遵守自动扩缩组的任何运行状况检查宽限期。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [SetInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `SetInstanceProtection` 与 CLI 配合使用
<a name="example_auto-scaling_SetInstanceProtection_section"></a>

以下代码示例演示如何使用 `SetInstanceProtection`。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：启用实例的实例保护设置**  
此示例启用对指定实例的实例保护。  

```
aws autoscaling set-instance-protection \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg --protected-from-scale-in
```
此命令不生成任何输出。  
**示例 2：禁用实例的实例保护设置**  
此示例禁用对指定实例的实例保护。  

```
aws autoscaling set-instance-protection \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg \
    --no-protected-from-scale-in
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[SetInstanceProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/set-instance-protection.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例启用指定实例的实例保护。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $true
```
**示例 2：此示例禁用指定实例的实例保护。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [SetInstanceProtection](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例启用指定实例的实例保护。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $true
```
**示例 2：此示例禁用指定实例的实例保护。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $false
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [SetInstanceProtection](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# 将 `SuspendProcesses` 与 CLI 配合使用
<a name="example_auto-scaling_SuspendProcesses_section"></a>

以下代码示例演示如何使用 `SuspendProcesses`。

------
#### [ CLI ]

**AWS CLI**  
**暂停 Auto Scaling 进程**  
此示例暂停指定自动扩缩组的指定扩展流程。  

```
aws autoscaling suspend-processes \
    --auto-scaling-group-name my-asg \
    --scaling-processes AlarmNotification
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[暂停和恢复扩展流程](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[SuspendProcesses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/suspend-processes.html)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例暂停了指定自动扩缩组的指定 Auto Scaling 进程。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**示例 2：此示例暂停了指定自动扩缩组的所有 Auto Scaling 进程。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [SuspendProcesses](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例暂停了指定自动扩缩组的指定 Auto Scaling 进程。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**示例 2：此示例暂停了指定自动扩缩组的所有 Auto Scaling 进程。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [SuspendProcesses](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `TerminateInstanceInAutoScalingGroup`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_TerminateInstanceInAutoScalingGroup_section"></a>

以下代码示例演示如何使用 `TerminateInstanceInAutoScalingGroup`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [构建和管理弹性服务](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Terminate all instances in the Auto Scaling group in preparation for
    /// deleting the group.
    /// </summary>
    /// <param name="instanceId">The instance Id of the instance to terminate.</param>
    /// <returns>A Boolean value that indicates the success or failure of
    /// the operation.</returns>
    public async Task<bool> TerminateInstanceInAutoScalingGroupAsync(
        string instanceId)
    {
        var request = new TerminateInstanceInAutoScalingGroupRequest
        {
            InstanceId = instanceId,
            ShouldDecrementDesiredCapacity = false,
        };

        var response = await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(request);

        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You have terminated the instance: {instanceId}");
            return true;
        }

        Console.WriteLine($"Could not terminate {instanceId}");
        return false;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::TerminateInstanceInAutoScalingGroupRequest request;
        request.SetInstanceId(instanceIDs[instanceNumber - 1]);
        request.SetShouldDecrementDesiredCapacity(false);

        Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupOutcome outcome =
                autoScalingClient.TerminateInstanceInAutoScalingGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "Waiting for EC2 instance with ID '"
                      << instanceIDs[instanceNumber - 1] << "' to terminate..."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::TerminateInstanceInAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)*中的。

------
#### [ CLI ]

**AWS CLI**  
**终止自动扩缩组中的实例**  
此示例在不更新指定自动扩缩组大小的情况下终止该组中的指定实例。Amazon EC2 Auto Scaling 会在指定实例终止后启动替代实例。  

```
aws autoscaling terminate-instance-in-auto-scaling-group \
    --instance-id i-061c63c5eb45f0416 \
    --no-should-decrement-desired-capacity
```
输出：  

```
{
    "Activities": [
        {
            "ActivityId": "8c35d601-793c-400c-fcd0-f64a27530df7",
            "AutoScalingGroupName": "my-asg",
            "Description": "Terminating EC2 instance: i-061c63c5eb45f0416",
            "Cause": "",
            "StartTime": "2020-10-31T20:34:25.680Z",
            "StatusCode": "InProgress",
            "Progress": 0,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[TerminateInstanceInAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/terminate-instance-in-auto-scaling-group.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId) {
        try {
            TerminateInstanceInAutoScalingGroupRequest request = TerminateInstanceInAutoScalingGroupRequest.builder()
                    .instanceId(instanceId)
                    .shouldDecrementDesiredCapacity(false)
                    .build();

            autoScalingClient.terminateInstanceInAutoScalingGroup(request);
            System.out.println("You have terminated instance " + instanceId);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun terminateInstanceInAutoScalingGroup(instanceIdVal: String) {
    val request =
        TerminateInstanceInAutoScalingGroupRequest {
            instanceId = instanceIdVal
            shouldDecrementDesiredCapacity = false
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.terminateInstanceInAutoScalingGroup(request)
        println("You have terminated instance $instanceIdVal")
    }
}
```
+  有关 API 的详细信息，请参阅适用[TerminateInstanceInAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function terminateInstanceInAutoScalingGroup(
        $instanceId,
        $shouldDecrementDesiredCapacity = true,
        $attempts = 0
    ) {
        try {
            return $this->autoScalingClient->terminateInstanceInAutoScalingGroup([
                'InstanceId' => $instanceId,
                'ShouldDecrementDesiredCapacity' => $shouldDecrementDesiredCapacity,
            ]);
        } catch (AutoScalingException $exception) {
            if ($exception->getAwsErrorCode() == "ScalingActivityInProgress" && $attempts < 5) {
                error_log("Cannot terminate an instance while it is still pending. Waiting then trying again.");
                sleep(5 * (1 + $attempts));
                return $this->terminateInstanceInAutoScalingGroup(
                    $instanceId,
                    $shouldDecrementDesiredCapacity,
                    ++$attempts
                );
            } else {
                throw $exception;
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例终止了指定的实例，并减少其自动扩缩组的所需容量，以使 Auto Scaling 不启动替换实例。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $true
```
**输出**：  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request, shrinking the capacity from 2 to 1.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
**示例 2：此示例在不减少指定实例自动扩缩组所需容量的情况下终止该实例。Auto Scaling 会启动一个替换实例。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $false
```
**输出**：  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例终止了指定的实例，并减少其自动扩缩组的所需容量，以使 Auto Scaling 不启动替换实例。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $true
```
**输出**：  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request, shrinking the capacity from 2 to 1.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
**示例 2：此示例在不减少指定实例自动扩缩组所需容量的情况下终止该实例。Auto Scaling 会启动一个替换实例。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $false
```
**输出**：  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 terminate_instance(
        self, instance_id: str, decrease_capacity: bool
    ) -> Dict[str, Any]:
        """
        Stops an instance.

        :param instance_id: The ID of the instance to stop.
        :param decrease_capacity: Specifies whether to decrease the desired capacity
                                  of the group. When passing True for this parameter,
                                  you can stop an instance without having a replacement
                                  instance start when the desired capacity threshold is
                                  crossed.
        :return: A dictionary containing details of the scaling activity that occurs
                 in response to this action.
        :raises ClientError: If there is an error terminating the instance.
        """
        try:
            response = self.autoscaling_client.terminate_instance_in_auto_scaling_group(
                InstanceId=instance_id, ShouldDecrementDesiredCapacity=decrease_capacity
            )
            logger.info(f"Successfully terminated instance {instance_id}.")
            return response["Activity"]

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to terminate instance {instance_id}.")
            if error_code == "ScalingActivityInProgress":
                logger.error(
                    "A scaling activity is currently in progress for the Auto Scaling group "
                    f"associated with instance '{instance_id}'. "
                    "Please wait for the activity to complete before attempting to terminate the instance."
                )
            elif error_code == "ResourceInUse":
                logger.error(
                    f"The instance '{instance_id}' or an associated resource is currently in use "
                    "and cannot be terminated. "
                    "Ensure the instance is not involved in any ongoing processes and try again."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  有关 API 的详细信息，请参阅适用[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    pub async fn terminate_some_instance(&self) -> Result<(), ScenarioError> {
        // Retrieve a list of instances in the auto scaling group.
        let auto_scaling_group = self.get_group().await?;
        let instances = auto_scaling_group.instances();
        // Or use other logic to find an instance to terminate.
        let instance = instances.first();
        if let Some(instance) = instance {
            let instance_id = if let Some(instance_id) = instance.instance_id() {
                instance_id
            } else {
                return Err(ScenarioError::with("Missing instance id"));
            };
            let termination = self
                .ec2
                .terminate_instances()
                .instance_ids(instance_id)
                .send()
                .await;
            if let Err(err) = termination {
                Err(ScenarioError::new(
                    "There was a problem terminating an instance",
                    &err,
                ))
            } else {
                Ok(())
            }
        } else {
            Err(ScenarioError::with("There was no instance to terminate"))
        }
    }

    async fn get_group(&self) -> Result<AutoScalingGroup, ScenarioError> {
        let describe_auto_scaling_groups = self
            .autoscaling
            .describe_auto_scaling_groups()
            .auto_scaling_group_names(self.auto_scaling_group_name.clone())
            .send()
            .await;

        if let Err(err) = describe_auto_scaling_groups {
            return Err(ScenarioError::new(
                format!(
                    "Failed to get status of autoscaling group {}",
                    self.auto_scaling_group_name.clone()
                )
                .as_str(),
                &err,
            ));
        }

        let describe_auto_scaling_groups_output = describe_auto_scaling_groups.unwrap();
        let auto_scaling_groups = describe_auto_scaling_groups_output.auto_scaling_groups();
        let auto_scaling_group = auto_scaling_groups.first();

        if auto_scaling_group.is_none() {
            return Err(ScenarioError::with(format!(
                "Could not find autoscaling group {}",
                self.auto_scaling_group_name.clone()
            )));
        }

        Ok(auto_scaling_group.unwrap().clone())
    }
```
+  有关 API 的详细信息，请参阅适用[TerminateInstanceInAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.terminate_instance_in_auto_scaling_group)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: iv_instance_id = 'i-1234567890abcdef0'
    " Example: iv_decrease_capacity = abap_true
    
    TRY.
        DATA(lo_output) = ao_asc->terminateinstinautoscgroup(
          iv_instanceid = iv_instance_id
          iv_shoulddecrementdesiredcap = iv_decrease_capacity ).

        oo_output = lo_output->get_activity( ).

        MESSAGE 'Instance terminated successfully' TYPE 'I'.

      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。

# `UpdateAutoScalingGroup`与 AWS SDK 或 CLI 配合使用
<a name="example_auto-scaling_UpdateAutoScalingGroup_section"></a>

以下代码示例演示如何使用 `UpdateAutoScalingGroup`。

操作示例是大型程序的代码摘录，必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文：
+  [了解基本功能](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [构建和管理弹性服务](example_cross_ResilientService_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK (v4)**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /// <summary>
    /// Update the capacity of an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <param name="launchTemplateName">The name of the EC2 launch template.</param>
    /// <param name="maxSize">The maximum number of instances that can be
    /// created for the Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> UpdateAutoScalingGroupAsync(
        string groupName,
        string launchTemplateName,
        int maxSize)
    {
        var templateSpecification = new LaunchTemplateSpecification
        {
            LaunchTemplateName = launchTemplateName,
        };

        var groupRequest = new UpdateAutoScalingGroupRequest
        {
            MaxSize = maxSize,
            AutoScalingGroupName = groupName,
            LaunchTemplate = templateSpecification,
        };

        var response = await _amazonAutoScaling.UpdateAutoScalingGroupAsync(groupRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You successfully updated the Auto Scaling group {groupName}.");
            return true;
        }
        else
        {
            return false;
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/UpdateAutoScalingGroup)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
        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::UpdateAutoScalingGroupRequest request;
        request.SetAutoScalingGroupName(groupName);
        request.SetMaxSize(3);

        Aws::AutoScaling::Model::UpdateAutoScalingGroupOutcome outcome =
                autoScalingClient.UpdateAutoScalingGroup(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error with AutoScaling::UpdateAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 AWS SDK API 参考[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/UpdateAutoScalingGroup)*中的。

------
#### [ CLI ]

**AWS CLI**  
**示例 1：更新自动扩缩组的大小限制**  
该示例更新指定的自动扩缩组，该组的最小大小为 1，最大大小为 10。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --min-size 2 \
    --max-size 10
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[设置自动扩缩组的容量限制](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-capacity-limits.html)。  
**示例 2：添加 Elastic Load Balancing 运行状况检查并指定要使用的可用区和子网**  
此示例更新指定的自动扩缩组以添加 Elastic Load Balancing 运行状况检查。此命令还`--vpc-zone-identifier`使用多个可用区 IDs 中的子网列表更新的值。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --health-check-type ELB \
    --health-check-grace-period 600 \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的 [Elastic Load Balancing 和 Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)。  
**示例 3：更新置放群组和终止策略**  
此示例更新要使用的置放群组和终止策略。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --placement-group my-placement-group \
    --termination-policies "OldestInstance"
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[自动扩缩组](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)。  
**示例 4：使用最新版本的启动模板**  
此示例将指定的自动扩缩组更新为使用最新版本的指定启动模板。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest'
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[启动模板](https://docs.aws.amazon.com/autoscaling/ec2/userguide/LaunchTemplates.html)。  
**示例 5：使用特定版本的启动模板**  
此示例将指定的自动扩缩组更新为使用特定版本的启动模板，而不是最新或默认版本。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='2'
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[启动模板](https://docs.aws.amazon.com/autoscaling/ec2/userguide/LaunchTemplates.html)。  
**示例 6：定义混合实例策略并启用容量再平衡**  
此示例将指定的自动扩缩组更新为使用混合实例策略并启用容量再平衡。此结构允许您指定具有竞价和按需容量的组，并针对不同的架构使用不同的启动模板。  

```
aws autoscaling update-auto-scaling-group \
    --cli-input-json file://~/config.json
```
`config.json` 的内容：  

```
{
    "AutoScalingGroupName": "my-asg",
    "CapacityRebalance": true,
    "MixedInstancesPolicy": {
        "LaunchTemplate": {
            "LaunchTemplateSpecification": {
                "LaunchTemplateName": "my-launch-template-for-x86",
                "Version": "$Latest"
            },
            "Overrides": [
                {
                    "InstanceType": "c6g.large",
                    "LaunchTemplateSpecification": {
                        "LaunchTemplateName": "my-launch-template-for-arm",
                        "Version": "$Latest"
                    }
                },
                {
                    "InstanceType": "c5.large"
                },
                {
                    "InstanceType": "c5a.large"
                }
            ]
        },
        "InstancesDistribution": {
            "OnDemandPercentageAboveBaseCapacity": 50,
            "SpotAllocationStrategy": "capacity-optimized"
        }
    }
}
```
此命令不生成任何输出。  
有关更多信息，请参阅《Amazon EC2 Auto Scaling 用户指南》**中的[具有多个实例类型和购买选项的自动扩缩组](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-purchase-options.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[UpdateAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/update-auto-scaling-group.html)*中的。

------
#### [ Java ]

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName,
            String launchTemplateName) {
        try {
            AutoScalingWaiter waiter = autoScalingClient.waiter();
            LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder()
                    .launchTemplateName(launchTemplateName)
                    .build();

            UpdateAutoScalingGroupRequest groupRequest = UpdateAutoScalingGroupRequest.builder()
                    .maxSize(3)
                    .autoScalingGroupName(groupName)
                    .launchTemplate(templateSpecification)
                    .build();

            autoScalingClient.updateAutoScalingGroup(groupRequest);
            DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter
                    .waitUntilGroupInService(groupsRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("You successfully updated the auto scaling group  " + groupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/UpdateAutoScalingGroup)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun updateAutoScalingGroup(
    groupName: String,
    launchTemplateNameVal: String,
    serviceLinkedRoleARNVal: String,
) {
    val templateSpecification =
        LaunchTemplateSpecification {
            launchTemplateName = launchTemplateNameVal
        }

    val groupRequest =
        UpdateAutoScalingGroupRequest {
            maxSize = 3
            serviceLinkedRoleArn = serviceLinkedRoleARNVal
            autoScalingGroupName = groupName
            launchTemplate = templateSpecification
        }

    val groupsRequestWaiter =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.updateAutoScalingGroup(groupRequest)
        autoScalingClient.waitUntilGroupExists(groupsRequestWaiter)
        println("You successfully updated the Auto Scaling group  $groupName")
    }
}
```
+  有关 API 的详细信息，请参阅适用[UpdateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    public function updateAutoScalingGroup($autoScalingGroupName, $args)
    {
        if (array_key_exists('MaxSize', $args)) {
            $maxSize = ['MaxSize' => $args['MaxSize']];
        } else {
            $maxSize = [];
        }
        if (array_key_exists('MinSize', $args)) {
            $minSize = ['MinSize' => $args['MinSize']];
        } else {
            $minSize = [];
        }
        $parameters = ['AutoScalingGroupName' => $autoScalingGroupName];
        $parameters = array_merge($parameters, $minSize, $maxSize);
        return $this->autoScalingClient->updateAutoScalingGroup($parameters);
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)*中的。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例更新指定自动扩缩组的最小和最大大小。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**示例 2：此示例更新指定自动扩缩组的默认冷却时间。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**示例 3：此示例更新指定自动扩缩组的可用区。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**示例 4：此示例更新指定的自动扩缩组以使用 Elastic Load Balancing 运行状况检查。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：此示例更新指定自动扩缩组的最小和最大大小。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**示例 2：此示例更新指定自动扩缩组的默认冷却时间。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**示例 3：此示例更新指定自动扩缩组的可用区。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**示例 4：此示例更新指定的自动扩缩组以使用 Elastic Load Balancing 运行状况检查。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
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 update_group(self, group_name: str, **kwargs: Any) -> None:
        """
        Updates an Auto Scaling group.

        :param group_name: The name of the group to update.
        :param kwargs: Keyword arguments to pass through to the service.
        :return: None
        :raises ClientError: If there is an error updating the Auto Scaling group.
        """
        try:
            self.autoscaling_client.update_auto_scaling_group(
                AutoScalingGroupName=group_name, **kwargs
            )
            logger.info(f"Successfully updated Auto Scaling group {group_name}.")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to update Auto Scaling group {group_name}.")
            if error_code == "ResourceInUse":
                logger.error(
                    "The Auto Scaling group '%s' is currently in use and cannot be modified. Please try again later.",
                    group_name,
                )
            elif error_code == "ScalingActivityInProgress":
                logger.error(
                    f"A scaling activity is currently in progress for the Auto Scaling group '{group_name}'."
                    "Please wait for the activity to complete before attempting to update the group."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  有关 API 的详细信息，请参阅适用[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)中查找完整示例，了解如何进行设置和运行。

```
async fn update_group(client: &Client, name: &str, size: i32) -> Result<(), Error> {
    client
        .update_auto_scaling_group()
        .auto_scaling_group_name(name)
        .max_size(size)
        .send()
        .await?;

    println!("Updated AutoScaling group");

    Ok(())
}
```
+  有关 API 的详细信息，请参阅适用[UpdateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.update_auto_scaling_group)于 *Rust 的AWS SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: iv_max_size = 5
    
    TRY.
        ao_asc->updateautoscalinggroup(
          iv_autoscalinggroupname = iv_group_name
          iv_maxsize = iv_max_size
          iv_minsize = iv_min_size ).

        MESSAGE 'Auto Scaling group updated successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[UpdateAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。