

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# SDK を使用した Auto Scaling のアクション AWS SDKs
<a name="service_code_examples_actions"></a>

次のコード例は、 AWS SDKs を使用して個々の Auto Scaling アクションを実行する方法を示しています。それぞれの例には、GitHub へのリンクがあり、そこにはコードの設定と実行に関する説明が記載されています。

これらは Auto Scaling API を呼び出すもので、大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは [SDK を使用した Auto Scaling のシナリオ AWS SDKs](service_code_examples_scenarios.md) のコンテキスト内で確認できます。

 以下の例には、最も一般的に使用されるアクションのみ含まれています。詳細な一覧については、「[Amazon EC2 Auto Scaling API リファレンス](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)

# CLI で `AttachInstances` を使用する
<a name="example_auto-scaling_AttachInstances_section"></a>

次のサンプルコードは、`AttachInstances` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループにインスタンスをアタッチするには**  
この例では、指定されたインスタンスを、指定された Auto Scaling グループにアタッチします。  

```
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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスを、指定した Auto Scaling グループにアタッチします。Auto Scaling は、Auto Scaling グループの希望する容量を自動的に増やします。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[AttachInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスを、指定した Auto Scaling グループにアタッチします。Auto Scaling は、Auto Scaling グループの希望する容量を自動的に増やします。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `AttachLoadBalancerTargetGroups`で を使用する
<a name="example_auto-scaling_AttachLoadBalancerTargetGroups_section"></a>

次のサンプルコードは、`AttachLoadBalancerTargetGroups` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [レジリエントなサービスの構築と管理](example_cross_ResilientService_section.md) 

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

**SDK for .NET**  
 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 の詳細については、「*AWS SDK for .NET API リファレンス*」の「[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)」を参照してください。

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

**AWS CLI**  
**ターゲットグループを Auto Scaling グループにアタッチするには**  
この例では、指定されたターゲットグループを、指定された Auto Scaling グループにアタッチします。  

```
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 ユーザーガイド」の「[Elastic Load Balancing を使用して 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 ]

**SDK for 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 の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/AttachLoadBalancerTargetGroupsCommand)」を参照してください。

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

**SDK for Python (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 の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `AttachLoadBalancers` を使用する
<a name="example_auto-scaling_AttachLoadBalancers_section"></a>

次のサンプルコードは、`AttachLoadBalancers` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループに Classic Load Balancer をアタッチするには**  
この例では、指定された Classic Load Balancer を、指定された Auto Scaling グループにアタッチします。  

```
aws autoscaling attach-load-balancers \
    --load-balancer-names my-load-balancer \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Elastic Load Balancing を使用して 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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定したロードバランサーを、指定した Auto Scaling グループにアタッチします。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定したロードバランサーを、指定した Auto Scaling グループにアタッチします。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `CompleteLifecycleAction` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定したライフサイクルアクションを完了します。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定したライフサイクルアクションを完了します。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `CreateAutoScalingGroup`で を使用する
<a name="example_auto-scaling_CreateAutoScalingGroup_section"></a>

次のサンプルコードは、`CreateAutoScalingGroup` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [レジリエントなサービスの構築と管理](example_cross_ResilientService_section.md) 

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

**SDK for .NET (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;
        }
    }
```
+  詳細については、「*AWS SDK for .NET 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;

        }
```
+  詳細については、「[AWS SDK for C\$1\$1 API リファレンス](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/CreateAutoScalingGroup)」の「*CreateAutoScalingGroup*」を参照してください。

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

**AWS CLI**  
**例 1: Auto Scaling グループを作成するには**  
次の `create-auto-scaling-group` の例では、リージョン内の複数のアベイラビリティーゾーンのサブネット内に Auto Scaling グループを作成します。インスタンスは、指定された起動テンプレートのデフォルトバージョンで起動されます。終了ポリシーやヘルスチェック構成など、他のほとんどの構成にはデフォルトが使用されることに注意してください。  

```
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 ユーザーガイド*」の「[Auto Scaling groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)」を参照してください。  
**例 2: Application Load Balancer、Network Load Balancer、または Gateway Load Balancer をアタッチする方法**  
この例では、予想されるトラフィックをサポートするロードバランサーのターゲットグループの ARN を指定します。ヘルスチェックタイプは、Elastic Load Balancing がインスタンスを異常として報告したときに、Auto Scaling グループがそのインスタンスを置き換えるよう `ELB` を指定します。このコマンドは、ヘルスチェックの猶予期間 (`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 を使用して 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"
```
このコマンドでは何も出力されません。  
詳細については、「*Linux インスタンス用 Amazon EC2 ユーザーガイド*」の「[プレイスメントグループ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html)」を参照してください。  
**例 4: 単一のインスタンスの Auto Scaling グループを指定し、特定のバージョンの起動テンプレートを使用する方法**  
この例では、単一のインスタンスが強制的に実行されるように、最小容量と最大容量を `1` に設定した Auto Scaling グループを作成します。このコマンドは、既存の ENI の ID が指定されている起動テンプレートの v1 も指定します。eth0 の既存の ENI を指定する起動テンプレートを使用する際は、リクエストにサブネット ID を指定せずに、ネットワークインターフェイスと一致する Auto Scaling グループのアベイラビリティーゾーンを指定する必要があります。  

```
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 ユーザーガイド*」の「[Auto Scaling groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)」を参照してください。  
**例 5: 別の終了ポリシーを指定する方法**  
この例では、起動構成を使用して Auto Scaling グループを作成し、最も古いインスタンスを最初に終了するように終了ポリシーを構成します。またこのコマンドは、`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: 起動ライフサイクルフックを指定する方法**  
この例では、インスタンス起動時のカスタムアクションをサポートするライフサイクルフックで Auto Scaling グループを設定します。  

```
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: 終了ライフサイクルフックを指定する方法**  
次の例では、インスタンス終了時のカスタムアクションをサポートするライフサイクルフックで Auto Scaling グループを設定します。  

```
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: カスタム終了ポリシーを指定する方法**  
この例では、スケールイン時にどのインスタンスを安全に終了できるかを Amazon EC2 Auto Scaling に指示するカスタム Lambda 関数終了ポリシーを指定する 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 ]

**SDK for Java 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);
        }
    }
}
```
+  詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

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

**SDK for Kotlin**  
 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 の詳細については、「AWS SDK for Kotlin API リファレンス」の「[CreateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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,
            ],
        ]);
    }
```
+  詳細については、*AWS SDK for PHP API リファレンス*の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定した名前と属性で Auto Scaling グループを作成します。デフォルトの希望する容量は最小サイズになります。したがって、この Auto Scaling グループは、指定した 2 つのアベイラビリティーゾーンのそれぞれに 1 つずつ、合計 2 つのインスタンスを起動します。**  

```
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した名前と属性で Auto Scaling グループを作成します。デフォルトの希望する容量は最小サイズになります。したがって、この Auto Scaling グループは、指定した 2 つのアベイラビリティーゾーンのそれぞれに 1 つずつ、合計 2 つのインスタンスを起動します。**  

```
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、「AWS SDK for Rust API リファレンス」の「[CreateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.create_auto_scaling_group)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `CreateLaunchConfiguration` を使用する
<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: セキュリティグループ、キーペア、ブートストラップスクリプトを使用して起動設定を作成するには**  
この例では、セキュリティグループ、キーペア、ユーザーデータに含まれるブートストラップスクリプトを使用して起動設定を作成します。  

```
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 詳細モニタリングを有効にして起動構成を作成し、EC2 メトリクスを 1 分間隔で CloudWatch に送信します。  

```
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 ユーザーガイド*」の「[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 リファレンス*」の「[EBS](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_Ebs.html)」を参照してください。  
JSON 形式のパラメータ値を引用するための構文については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の「 [CLI AWS の文字列での引用符の使用](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html)」を参照してください。  
**例 8: インスタンスストアボリュームのブロックデバイスマッピングを使用して起動構成を作成する方法**  
この例では、デバイス名「`/dev/sdc`」のインスタンスストアボリュームとして `ephemeral1` で起動構成を作成します。  

```
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"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling API リファレンス*」の「[BlockDeviceMapping](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_BlockDeviceMapping.html)」を参照してください。  
JSON 形式のパラメータ値を引用するための構文については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の「 [CLI AWS の文字列での引用符の使用](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":""}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling API リファレンス*」の「[BlockDeviceMapping](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_BlockDeviceMapping.html)」を参照してください。  
JSON 形式のパラメータ値を引用するための構文については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の「 [CLI AWS の文字列での引用符の使用](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 ]

**Tools for PowerShell V4**  
**例 1: この例では、「my-lc」という名前の起動設定を作成します。この起動設定を使用する Auto Scaling グループによって起動された EC2 インスタンスは、指定されたインスタンスタイプ、AMI、セキュリティグループ、および IAM ロールを使用します。**  

```
New-ASLaunchConfiguration -LaunchConfigurationName my-lc -InstanceType "m3.medium" -ImageId "ami-12345678" -SecurityGroup "sg-12345678" -IamInstanceProfile "myIamRole"
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、「my-lc」という名前の起動設定を作成します。この起動設定を使用する Auto Scaling グループによって起動された EC2 インスタンスは、指定されたインスタンスタイプ、AMI、セキュリティグループ、および IAM ロールを使用します。**  

```
New-ASLaunchConfiguration -LaunchConfigurationName my-lc -InstanceType "m3.medium" -ImageId "ami-12345678" -SecurityGroup "sg-12345678" -IamInstanceProfile "myIamRole"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `CreateOrUpdateTags` を使用する
<a name="example_auto-scaling_CreateOrUpdateTags_section"></a>

次のサンプルコードは、`CreateOrUpdateTags` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループのタグを作成または変更するには**  
この例では、指定された Auto Scaling グループに 2 つのタグを追加します。  

```
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 ユーザーガイド*」の「[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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに単一のタグを追加します。タグキーは「myTag」で、タグ値は「myTagValue」です。Auto Scaling は、このタグを 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 コマンドレットリファレンス (V4)*」の「[CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに単一のタグを追加します。タグキーは「myTag」で、タグ値は「myTagValue」です。Auto Scaling は、このタグを 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 コマンドレットリファレンス (V5)*の「[CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `DeleteAutoScalingGroup`で を使用する
<a name="example_auto-scaling_DeleteAutoScalingGroup_section"></a>

次のサンプルコードは、`DeleteAutoScalingGroup` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [レジリエントなサービスの構築と管理](example_cross_ResilientService_section.md) 

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

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。
Auto Scaling グループの最小サイズをゼロに更新し、グループ内のすべてのインスタンスを終了して、グループを削除します。  

```
    /// <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;
    }
```
+  詳細については、「*AWS SDK for .NET 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 の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

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

**AWS CLI**  
**例 1: 指定された Auto Scaling グループを削除するには**  
この例では、指定された Auto Scaling グループを削除します。  

```
aws autoscaling delete-auto-scaling-group \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling インフラストラクチャを削除する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-process-shutdown.html)」を参照してください。  
**例 2: 指定された Auto Scaling グループを強制的に削除する方法**  
グループ内のインスタンスが終了するのを待たずに Auto Scaling グループを削除するには、`--force-delete` オプションを使用します。  

```
aws autoscaling delete-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --force-delete
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[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 ]

**SDK for Java 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);
        }
    }
}
```
+  詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

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

**SDK for Kotlin**  
 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 の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeleteAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに実行中のインスタンスがない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
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: この例では、指定した Auto Scaling グループを削除し、そのグループに含まれる実行中のインスタンスをすべて終了します。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに実行中のインスタンスがない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
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: この例では、指定した Auto Scaling グループを削除し、そのグループに含まれる実行中のインスタンスをすべて終了します。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。
Auto Scaling グループの最小サイズをゼロに更新し、グループ内のすべてのインスタンスを終了して、グループを削除します。  

```
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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、「AWS SDK for Rust API リファレンス」の「[DeleteAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.delete_auto_scaling_group)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DeleteLaunchConfiguration` を使用する
<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 ユーザーガイド*」の「[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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した起動設定が Auto Scaling グループにアタッチされていない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V4)*」の「[DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した起動設定が Auto Scaling グループにアタッチされていない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V5)* の「[DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DeleteLifecycleHook` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したライフサイクルフックを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V4)*」の「[DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したライフサイクルフックを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V5)* の「[DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DeleteNotificationConfiguration` を使用する
<a name="example_auto-scaling_DeleteNotificationConfiguration_section"></a>

次のサンプルコードは、`DeleteNotificationConfiguration` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling 通知を削除するには**  
この例では、指定された 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 ]

**Tools for 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 コマンドレットリファレンス (V4)*」の「[DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 コマンドレットリファレンス (V5)* の「[DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DeletePolicy` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V4)* の「[DeletePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V5)* の「[DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DeleteScheduledAction` を使用する
<a name="example_auto-scaling_DeleteScheduledAction_section"></a>

次のサンプルコードは、`DeleteScheduledAction` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループからスケジュールされたアクションを削除するには**  
この例では、指定された Auto Scaling グループから指定されたスケジュール済みの通知を削除します。  

```
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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したスケジュールされたアクションを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V4)*」の「[DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したスケジュールされたアクションを削除します。操作を続行する前に確認画面が表示されます。**  

```
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 コマンドレットリファレンス (V5)* の「[DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DeleteTags` を使用する
<a name="example_auto-scaling_DeleteTags_section"></a>

次のサンプルコードは、`DeleteTags` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループからタグを削除するには**  
この例では、指定された Auto Scaling グループから指定されたタグを削除します。  

```
aws autoscaling delete-tags \
    --tags ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Dept,Value=Research
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループから指定したタグを削除します。操作を続行する前に確認画面が表示されます。この例で使用される構文には、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 = 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 コマンドレットリファレンス (V4)*」の「[DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループから指定したタグを削除します。操作を続行する前に確認画面が表示されます。この例で使用される構文には、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 = 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 コマンドレットリファレンス (V5)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeAccountLimits` を使用する
<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 Service Quotas](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 ]

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウントの Auto Scaling リソース制限について説明します。**  

```
Get-ASAccountLimit
```
**出力:**  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウントの Auto Scaling リソース制限について説明します。**  

```
Get-ASAccountLimit
```
**出力:**  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5*)」の「[DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeAdjustmentTypes` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされている調整タイプを記述します。**  

```
Get-ASAdjustmentType
```
**出力:**  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされている調整タイプを記述します。**  

```
Get-ASAdjustmentType
```
**出力:**  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `DescribeAutoScalingGroups`で を使用する
<a name="example_auto-scaling_DescribeAutoScalingGroups_section"></a>

次のサンプルコードは、`DescribeAutoScalingGroups` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [レジリエントなサービスの構築と管理](example_cross_ResilientService_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET 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 の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。**

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

**AWS CLI**  
**例 1: 指定された Auto Scaling グループを記述するには**  
この例では、指定された Auto Scaling グループを記述します。  

```
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 個の Auto Scaling グループを記述する方法**  
この例では、指定された複数の Auto Scaling グループを記述します。最大 100 個のグループ名を指定できます。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 100 \
    --auto-scaling-group-names "group1" "group2" "group3" "group4"
```
出力例については、例 1 を参照してください。  
**例 3: 指定されたリージョンの Auto Scaling グループを記述する方法**  
この例では、指定されたリージョンの Auto Scaling グループを最大 75 グループまで記述します。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 75 \
    --region us-east-1
```
出力例については、例 1 を参照してください。  
**例 4: 指定された数の Auto Scaling グループを記述する方法**  
特定の数の Auto Scaling グループを返すには、`--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: 起動構成を使用している Auto Scaling グループを記述する方法**  
この例では、 `--query` オプションを使用して、起動構成を使用する Auto Scaling グループを記述します。  

```
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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、AWS SDK for Kotlin API リファレンスの「[DescribeAutoScalingGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、AWS SDK for PHP API リファレンスの「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。**

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

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling グループの名前を一覧表示します。**  

```
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: この例では、指定した Auto Scaling グループを記述します。**  

```
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: この例では、指定した 2 つの Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**例 5: この例では、すべての Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup
```
**例 6: この例では、指定した 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 コマンドレットリファレンス (V4)*」の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling グループの名前を一覧表示します。**  

```
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: この例では、指定した Auto Scaling グループを記述します。**  

```
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: この例では、指定した 2 つの Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**例 5: この例では、すべての Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup
```
**例 6: この例では、指定した 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 コマンドレットリファレンス (V5)*」の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_groups)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `DescribeAutoScalingInstances`で を使用する
<a name="example_auto-scaling_DescribeAutoScalingInstances_section"></a>

次のサンプルコードは、`DescribeAutoScalingInstances` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET 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 の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

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

**AWS CLI**  
**例 1: 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: 1 つまたは複数のインスタンスを記述する方法**  
この例では、`--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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeAutoScalingInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例は、Auto Scaling インスタンスの ID を一覧表示します。**  

```
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: この例では、指定した 2 つの Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance -InstanceId @("i-12345678", "i-87654321")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**例 5: この例では、すべての Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例は、Auto Scaling インスタンスの ID を一覧表示します。**  

```
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: この例では、指定した 2 つの Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance -InstanceId @("i-12345678", "i-87654321")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**例 5: この例では、すべての Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeAutoScalingInstances](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_instances)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeAutoScalingNotificationTypes` を使用する
<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 ユーザーガイド*』の「[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 ]

**Tools for 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 コマンドレットリファレンス (V4)*」の「[DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 コマンドレットリファレンス (V5)* の「[DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeLaunchConfigurations` を使用する
<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 ]

**Tools for 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: この例では、指定した 2 つの起動設定を記述します。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName @("my-lc-1", "my-lc-2")
```
**例 4: この例では、すべての起動設定を記述します。**  

```
Get-ASLaunchConfiguration
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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: この例では、指定した 2 つの起動設定を記述します。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName @("my-lc-1", "my-lc-2")
```
**例 4: この例では、すべての起動設定を記述します。**  

```
Get-ASLaunchConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeLifecycleHookTypes` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例は、Auto Scaling でサポートされているライフサイクルフックの種類を一覧表示します。**  

```
Get-ASLifecycleHookType
```
**出力:**  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例は、Auto Scaling でサポートされているライフサイクルフックの種類を一覧表示します。**  

```
Get-ASLifecycleHookType
```
**出力:**  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeLifecycleHooks` を使用する
<a name="example_auto-scaling_DescribeLifecycleHooks_section"></a>

次のサンプルコードは、`DescribeLifecycleHooks` を使用する方法を説明しています。

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

**AWS CLI**  
**ライフサイクルフックを記述するには**  
指定された Auto Scaling グループのライフサイクルフックを記述します。  

```
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 ]

**Tools for 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: この例では、指定した Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**例 3: この例では、すべての Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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: この例では、指定した Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**例 3: この例では、すべての Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeLoadBalancers` を使用する
<a name="example_auto-scaling_DescribeLoadBalancers_section"></a>

次のサンプルコードは、`DescribeLoadBalancers` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループの Classic Load Balancer を記述するには**  
指定された Auto Scaling グループの Classic Load Balancer を記述します。  

```
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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのロードバランサーを記述します。**  

```
Get-ASLoadBalancer -AutoScalingGroupName my-asg
```
**出力:**  

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのロードバランサーを記述します。**  

```
Get-ASLoadBalancer -AutoScalingGroupName my-asg
```
**出力:**  

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeMetricCollectionTypes` を使用する
<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 ユーザーガイド*」の「[Auto Scaling group metrics](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 ]

**Tools for 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 コマンドレットリファレンス (V4)*」の「[DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 コマンドレットリファレンス (V5)* の「[DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeNotificationConfigurations` を使用する
<a name="example_auto-scaling_DescribeNotificationConfigurations_section"></a>

次のサンプルコードは、`DescribeNotificationConfigurations` を使用する方法を説明しています。

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

**AWS CLI**  
**例 1: 指定したグループの通知設定を記述するには**  
この例では、指定された Auto Scaling グループの通知構成を記述します。  

```
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 ユーザーガイド*』の「[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 ユーザーガイド*』の「[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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
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: この例では、すべての Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
Get-ASNotificationConfiguration
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
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: この例では、すべての Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
Get-ASNotificationConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribePolicies` を使用する
<a name="example_auto-scaling_DescribePolicies_section"></a>

次のサンプルコードは、`DescribePolicies` を使用する方法を説明しています。

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

**AWS CLI**  
**例 1: 指定した Auto Scaling グループのスケーリングポリシーを記述するには**  
この例では、指定された Auto Scaling グループのスケーリングポリシーを記述します。  

```
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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのすべてのポリシーを記述します。**  

```
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: この例では、指定した Auto Scaling グループの指定したポリシーを記述します。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**例 3: この例では、すべての Auto Scaling グループのすべてのポリシーを記述します。**  

```
Get-ASPolicy
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribePolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのすべてのポリシーを記述します。**  

```
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: この例では、指定した Auto Scaling グループの指定したポリシーを記述します。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**例 3: この例では、すべての Auto Scaling グループのすべてのポリシーを記述します。**  

```
Get-ASPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribePolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `DescribeScalingActivities`で を使用する
<a name="example_auto-scaling_DescribeScalingActivities_section"></a>

次のサンプルコードは、`DescribeScalingActivities` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET 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 の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

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

**AWS CLI**  
**例 1: 指定されたグループのスケーリングアクティビティを記述するには**  
この例では、指定された Auto Scaling グループのスケーリングアクティビティを記述します。  

```
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 ユーザーガイド*」の「[Verify a scaling activity for an Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-verify-scaling-activity.html)」を参照してください。  
**例 2: 削除されたグループのスケーリングアクティビティを記述する方法**  
Auto Scaling グループが削除された後にスケーリングアクティビティを説明するには、`--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 ユーザーガイド*」の「[Verify a scaling activity for an Auto Scaling group](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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeScalingActivities](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: こので例は、指定した Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
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: この例では、すべての Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: こので例は、指定した Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
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: この例では、すべての Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeScalingActivities](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_scaling_activities)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeScalingActivities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeScalingProcessTypes` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされているプロセスタイプを一覧表示します。**  

```
Get-ASScalingProcessType
```
**出力:**  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされているプロセスタイプを一覧表示します。**  

```
Get-ASScalingProcessType
```
**出力:**  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeScheduledActions` を使用する
<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 ユーザーガイド」の「[Scheduled scaling (スケジュールされたスケーリング)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
**例 2: 指定されたグループのスケジュール済みのアクションを記述する方法**  
特定の Auto Scaling グループのスケジュール済みのアクションを説明するには、 `--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 ユーザーガイド」の「[Scheduled 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 ユーザーガイド」の「[Scheduled 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 ユーザーガイド」の「[Scheduled 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 ユーザーガイド」の「[Scheduled 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 ユーザーガイド」の「[Scheduled 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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのスケジュールされたスケーリングアクティビティを記述します。**  

```
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: この例では、すべての Auto Scaling グループのスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのスケジュールされたスケーリングアクティビティを記述します。**  

```
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: この例では、すべての Auto Scaling グループのスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeTags` を使用する
<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 ユーザーガイド*」の「[Auto Scaling グループとインスタンスのタグ付け](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)」を参照してください。  
**例 2: 指定されたグループのタグを記述する方法**  
特定の Auto Scaling グループのタグを説明するには、`--filters` オプションを使用します。  

```
aws autoscaling describe-tags --filters Name=auto-scaling-group,Values=my-asg
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[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 ユーザーガイド*」の「[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 ]

**Tools for 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: この例では、すべての Auto Scaling グループのすべてのタグを記述します。**  

```
Get-ASTag
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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: この例では、すべての Auto Scaling グループのすべてのタグを記述します。**  

```
Get-ASTag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DescribeTerminationPolicyTypes` を使用する
<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 ユーザーガイド*」の「[スケールイン時にどの 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 ]

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされている終了ポリシーを一覧表示します。**  

```
Get-ASTerminationPolicyType
```
**出力:**  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされている終了ポリシーを一覧表示します。**  

```
Get-ASTerminationPolicyType
```
**出力:**  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DetachInstances` を使用する
<a name="example_auto-scaling_DetachInstances_section"></a>

次のサンプルコードは、`DetachInstances` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループからインスタンスをデタッチするには**  
この例では、指定されたインスタンスを指定された Auto Scaling グループからデタッチします。  

```
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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループから指定したインスタンスをデタッチし、希望する容量を減らして、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 グループからデタッチします。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 コマンドレットリファレンス (V4)*」の「[DetachInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループから指定したインスタンスをデタッチし、希望する容量を減らして、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 グループからデタッチします。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 コマンドレットリファレンス (V5)* の「[DetachInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `DetachLoadBalancers` を使用する
<a name="example_auto-scaling_DetachLoadBalancers_section"></a>

次のサンプルコードは、`DetachLoadBalancers` を使用する方法を説明しています。

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

**AWS CLI**  
**Classic Load Balancer を Auto Scaling グループからデタッチするには**  
この例では、指定された Classic Load Balancer を指定された Auto Scaling グループからデタッチします。  

```
aws autoscaling detach-load-balancers \
    --load-balancer-names my-load-balancer \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループから指定したロードバランサーをデタッチします。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループから指定したロードバランサーをデタッチします。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `DisableMetricsCollection`で を使用する
<a name="example_auto-scaling_DisableMetricsCollection_section"></a>

次のサンプルコードは、`DisableMetricsCollection` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET 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 の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

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

**AWS CLI**  
**Auto Scaling グループのメトリクス収集を無効にするには**  
この例では、指定された Auto Scaling グループの `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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DisableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、*AWS SDK for Rust API リファレンス*の「[DisableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.disable_metrics_collection)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DisableMetricsCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `EnableMetricsCollection`で を使用する
<a name="example_auto-scaling_EnableMetricsCollection_section"></a>

次のサンプルコードは、`EnableMetricsCollection` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET 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 の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

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

**AWS CLI**  
**例 1: Auto Scaling グループのメトリクス収集を有効にするには**  
この例では、指定された Auto Scaling グループのデータの収集を有効にします。  

```
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: Auto Scaling グループの指定されたメトリックスのデータを収集する方法**  
特定のメトリックスのデータを収集するには、`--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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、*AWS SDK for Kotlin API リファレンス*の「[EnableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、「*AWS SDK for PHP API リファレンス*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、*AWS SDK for Rust API リファレンス*の「[EnableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.enable_metrics_collection)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[EnableMetricsCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `EnterStandby` を使用する
<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 ]

**Tools for 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 コマンドレットリファレンス (V4)*」の「[EnterStandby](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 コマンドレットリファレンス (V5)* の「[EnterStandby](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `ExecutePolicy` を使用する
<a name="example_auto-scaling_ExecutePolicy_section"></a>

次のサンプルコードは、`ExecutePolicy` を使用する方法を説明しています。

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

**AWS CLI**  
**スケーリングポリシーを実行するには**  
この例では、指定された Auto Scaling グループに「`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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**例 2: この例では、クールダウン期間が完了するまで待機した後、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[ExecutePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**例 2: この例では、クールダウン期間が完了するまで待機した後、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ExecutePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `ExitStandby` を使用する
<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 ユーザーガイド*」の「[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 ]

**Tools for 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 コマンドレットリファレンス (V4)*」の「[ExitStandby](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 コマンドレットリファレンス (V5)* の「[ExitStandby](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `PutLifecycleHook` を使用する
<a name="example_auto-scaling_PutLifecycleHook_section"></a>

次のサンプルコードは、`PutLifecycleHook` を使用する方法を説明しています。

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

**AWS CLI**  
**例 1: ライフサイクルフックを作成するには**  
この例では、新しく起動した任意のインスタンスで呼び出すライフサイクルフックを作成します。タイムアウトは 4800 秒です。これは、ユーザーデータスクリプトが完了するまでインスタンスを待機状態に保つ場合や、EventBridge を使用して AWS Lambda 関数を呼び出す場合に便利です。  

```
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 の E メールメッセージを送信してインスタンスの状態遷移を通知する方法**  
この例では、インスタンスの起動時に通知を受信するために使用する 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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定したライフサイクルフックを、指定した Auto Scaling グループに追加します。**  

```
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 コマンドレットリファレンス (V4)*」の「[PutLifecycleHook](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定したライフサイクルフックを、指定した Auto Scaling グループに追加します。**  

```
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 コマンドレットリファレンス (V5)* の「[PutLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `PutNotificationConfiguration` を使用する
<a name="example_auto-scaling_PutNotificationConfiguration_section"></a>

次のサンプルコードは、`PutNotificationConfiguration` を使用する方法を説明しています。

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

**AWS CLI**  
**通知を追加するには**  
この例では、指定された Auto Scaling グループに指定された通知を追加します。  

```
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 ユーザーガイド*』の「[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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループが、EC2 インスタンスの起動時に指定した SNS トピックに通知を送信するように設定します。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType "autoscaling:EC2_INSTANCE_LAUNCH" -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**例 2: この例では、指定した Auto Scaling グループが、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 コマンドレットリファレンス (V4)*」の「[PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループが、EC2 インスタンスの起動時に指定した SNS トピックに通知を送信するように設定します。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType "autoscaling:EC2_INSTANCE_LAUNCH" -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**例 2: この例では、指定した Auto Scaling グループが、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 コマンドレットリファレンス (V5)* の「[PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `PutScalingPolicy` を使用する
<a name="example_auto-scaling_PutScalingPolicy_section"></a>

次のサンプルコードは、`PutScalingPolicy` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling グループにターゲット追跡スケーリングポリシーを追加するには**  
次の `put-scaling-policy` 例では、指定された Auto Scaling グループにターゲットトラッキングスケーリングポリシーを適用します。出力には、自動的に作成された 2 つの CloudWatch アラームの ARN と名前が含まれます。同じ名前のスケーリングポリシーが既に存在する場合は、新しいスケーリングポリシーで上書きされます。  

```
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)」を参照してください。 *Amazon EC2 Auto Scaling *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutScalingPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-scaling-policy.html)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに指定したポリシーを追加します。指定した調整タイプによって、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 コマンドレットリファレンス (V4)*」の「[PutScalingPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに指定したポリシーを追加します。指定した調整タイプによって、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 コマンドレットリファレンス (V5)* の「[PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `PutScheduledUpdateGroupAction` を使用する
<a name="example_auto-scaling_PutScheduledUpdateGroupAction_section"></a>

次のサンプルコードは、`PutScheduledUpdateGroupAction` を使用する方法を説明しています。

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

**AWS CLI**  
**例 1: スケジュールされたアクションを Auto Scaling グループに追加するには**  
この例では、指定された Auto Scaling グループから指定されたスケジュール済みの通知を追加します。  

```
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: 定期的なスケジュールを指定する方法**  
この例では、毎年 1 月、6 月、12 月の 1 日の 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 ]

**Tools for PowerShell V4**  
**例 1: この例では、1 回限りのスケジュールされたアクションを作成または更新して、指定した開始時刻に希望する容量を変更します。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、1 回限りのスケジュールされたアクションを作成または更新して、指定した開始時刻に希望する容量を変更します。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `RecordLifecycleActionHeartbeat` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定したライフサイクルアクションのハートビートを記録します。これにより、カスタムアクションが完了するまでインスタンスは保留中の状態になります。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定したライフサイクルアクションのハートビートを記録します。これにより、カスタムアクションが完了するまでインスタンスは保留中の状態になります。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `ResumeProcesses` を使用する
<a name="example_auto-scaling_ResumeProcesses_section"></a>

次のサンプルコードは、`ResumeProcesses` を使用する方法を説明しています。

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

**AWS CLI**  
**中断されたプロセスを再開するには**  
この例では、指定された Auto Scaling グループの指定された一時停止スケーリングプロセスを再開します。  

```
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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループの中断されたすべての Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[ResumeProcesses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループの中断されたすべての Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResumeProcesses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `SetDesiredCapacity`で を使用する
<a name="example_auto-scaling_SetDesiredCapacity_section"></a>

次のサンプルコードは、`SetDesiredCapacity` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET 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 の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

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

**AWS CLI**  
**Auto Scaling グループの希望する容量を設定するには**  
この例では、指定された Auto Scaling グループの希望する容量を設定します。  

```
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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、*AWS SDK for Kotlin API リファレンス*の「[SetDesiredCapacity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、「*AWS SDK for PHP API リファレンス*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのサイズを設定します。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**例 2: この例では、指定した Auto Scaling グループのサイズを設定し、クールダウン期間が完了するまで待ってから、新しいサイズにスケールします。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのサイズを設定します。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**例 2: この例では、指定した Auto Scaling グループのサイズを設定し、クールダウン期間が完了するまで待ってから、新しいサイズにスケールします。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、*AWS SDK for Rust API リファレンス*の「[SetDesiredCapacity](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.set_desired_capacity)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[SetDesiredCapacity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `SetInstanceHealth` を使用する
<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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスのステータスを「Unhealthy」に設定し、使用を中止します。Auto Scaling はインスタンスを終了して置き換えます。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**例 2: この例では、指定したインスタンスのステータスを「Healthy」に設定し、そのまま稼働させます。Auto Scaling グループのヘルスチェック猶予期間は無視されます。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[SetInstanceHealth](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスのステータスを「Unhealthy」に設定し、使用を中止します。Auto Scaling はインスタンスを終了して置き換えます。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**例 2: この例では、指定したインスタンスのステータスを「Healthy」に設定し、そのまま稼働させます。Auto Scaling グループのヘルスチェック猶予期間は無視されます。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SetInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `SetInstanceProtection` を使用する
<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 ]

**Tools for 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 コマンドレットリファレンス (V4)*」の「[SetInstanceProtection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for 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 コマンドレットリファレンス (V5)* の「[SetInstanceProtection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# CLI で `SuspendProcesses` を使用する
<a name="example_auto-scaling_SuspendProcesses_section"></a>

次のサンプルコードは、`SuspendProcesses` を使用する方法を説明しています。

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

**AWS CLI**  
**Auto Scaling プロセスを中断するには**  
この例では、指定された 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 ]

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループのすべての Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[SuspendProcesses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループのすべての Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SuspendProcesses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `TerminateInstanceInAutoScalingGroup`で を使用する
<a name="example_auto-scaling_TerminateInstanceInAutoScalingGroup_section"></a>

次のサンプルコードは、`TerminateInstanceInAutoScalingGroup` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [レジリエントなサービスの構築と管理](example_cross_ResilientService_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET 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 の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

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

**AWS CLI**  
**Auto Scaling グループのインスタンスを終了するには**  
この例では、グループのサイズを更新せずに、指定された Auto Scaling グループの指定されたインスタンスを終了します。指定されたインスタンスが終了した後、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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、「AWS SDK for Kotlin API リファレンス」**の「[TerminateInstanceInAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、「*AWS SDK for PHP API リファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスを終了し、Auto Scaling グループの希望する容量を減らして、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 グループの希望する容量を減らすことなく、指定したインスタンスを終了します。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 コマンドレットリファレンス (V4)*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスを終了し、Auto Scaling グループの希望する容量を減らして、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 グループの希望する容量を減らすことなく、指定したインスタンスを終了します。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 コマンドレットリファレンス (V5)*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、「AWS SDK for Rust API リファレンス」**の「[TerminateInstanceInAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.terminate_instance_in_auto_scaling_group)」を参照してください。

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。

# AWS SDK または CLI `UpdateAutoScalingGroup`で を使用する
<a name="example_auto-scaling_UpdateAutoScalingGroup_section"></a>

次のサンプルコードは、`UpdateAutoScalingGroup` を使用する方法を説明しています。

アクション例は、より大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。次のコード例で、このアクションのコンテキストを確認できます。
+  [基本を学ぶ](example_auto-scaling_Scenario_GroupsAndInstances_section.md) 
+  [レジリエントなサービスの構築と管理](example_cross_ResilientService_section.md) 

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

**SDK for .NET (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 の詳細については、「*AWS SDK for .NET  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 の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。

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

**AWS CLI**  
**例 1: Auto Scaling グループのサイズ制限を更新するには**  
この例では、最小サイズが 2、最大サイズが 10 で、指定された Auto Scaling グループを更新します。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --min-size 2 \
    --max-size 10
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Auto Scaling グループにキャパシティの制限を設定する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-capacity-limits.html)」を参照してください。**  
**例 2: Elastic Load Balancing ヘルスチェックを追加し、使用するアベイラビリティーゾーンとサブネットを指定する方法**  
この例では、指定された Auto Scaling グループを更新して、Elastic Load Balancing のヘルスチェックを追加します。またこのコマンドは、複数のアベイラビリティーゾーンのサブネット ID のリストを使用して、`--vpc-zone-identifier` の値も更新します。  

```
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 を使用して 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 ユーザーガイド*」の「[Auto Scaling groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)」を参照してください。  
**例 4: 起動テンプレートの最新バージョンを使用する方法**  
この例では、最新の起動テンプレートバージョンを使用するように、指定された Auto Scaling グループを更新します。  

```
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: 特定のバージョンの起動テンプレートを使用する方法**  
この例では、最新バージョンやデフォルトバージョンではなく、指定された起動テンプレートのバージョンを使用するように、指定された Auto Scaling グループを更新します。  

```
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: 混合インスタンスポリシーを定義し、容量のリバランスを有効にする方法**  
この例では、指定された Auto Scaling グループを更新して、混合インスタンスポリシーを使用し、容量のリバランスを有効にします。この構造により、スポット容量とオンデマンド容量でグループを指定し、アーキテクチャごとに異なる起動テンプレートを使用できます。  

```
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 ユーザーガイド」の「[複数のインスタンスタイプと購入オプションを使用する 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 ]

**SDK for Java 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 ]

**SDK for Kotlin**  
 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 の詳細については、「AWS SDK for Kotlin API リファレンス」の「[UpdateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

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

**SDK for PHP**  
 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 の詳細については、*AWS SDK for PHP API リファレンス*の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。

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

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの最小サイズと最大サイズを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**例 2: この例では、指定した Auto Scaling グループのデフォルトのクールダウン期間を更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**例 3: この例では、指定した Auto Scaling グループのアベイラビリティーゾーンを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**例 4: この例では、指定した Auto Scaling グループを更新して、Elastic Load Balancing のヘルスチェックを使用します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの最小サイズと最大サイズを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**例 2: この例では、指定した Auto Scaling グループのデフォルトのクールダウン期間を更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**例 3: この例では、指定した Auto Scaling グループのアベイラビリティーゾーンを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**例 4: この例では、指定した Auto Scaling グループを更新して、Elastic Load Balancing のヘルスチェックを使用します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

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

**SDK for Python (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 の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。

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

**SDK for Rust**  
 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 の詳細については、AWS SDK for Rust API リファレンスの「[UpdateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.update_auto_scaling_group)」を参照してください。**

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

**SDK for SAP ABAP**  
 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 の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------

 AWS SDK 開発者ガイドとコード例の完全なリストについては、「」を参照してください[AWS SDK でのこのサービスの使用](sdk-general-information-section.md)。このトピックには、使用開始方法に関する情報と、以前の SDK バージョンの詳細も含まれています。