本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
Auto Scaling 用 AWS SDKs
您可以使用 AWS Management Console、、和建立「Auto Scaling」 AWS CLI群組 AWS CloudFormation。 AWS SDK
下列程式碼範例說明如何使用您慣用支援的程式設計語言建立、更新、描述和刪除 Auto Scaling 群組 AWS SDKs。
使用建立「Auto Scaling」群組 AWS SDK
下列程式碼範例會示範如何使用CreateAutoScalingGroup
。
- .NET
-
- AWS SDK for .NET
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <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 }; var response = await _amazonAutoScaling.CreateAutoScalingGroupAsync(request); Console.WriteLine($"{groupName} Auto Scaling Group created"); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
-
如需詳API細資訊,請參閱AWS SDK for .NET API參考CreateAutoScalingGroup中的。
-
- C++
-
- SDK對於 C ++
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig); Aws::AutoScaling::Model::CreateAutoScalingGroupRequest request; request.SetAutoScalingGroupName(groupName); Aws::Vector<Aws::String> availabilityGroupZones; availabilityGroupZones.push_back( availabilityZones[availabilityZoneChoice - 1].GetZoneName()); request.SetAvailabilityZones(availabilityGroupZones); request.SetMaxSize(1); request.SetMinSize(1); Aws::AutoScaling::Model::LaunchTemplateSpecification launchTemplateSpecification; launchTemplateSpecification.SetLaunchTemplateName(templateName); request.SetLaunchTemplate(launchTemplateSpecification); Aws::AutoScaling::Model::CreateAutoScalingGroupOutcome outcome = autoScalingClient.CreateAutoScalingGroup(request); if (outcome.IsSuccess()) { std::cout << "Created Auto Scaling group '" << groupName << "'..." << std::endl; } else if (outcome.GetError().GetErrorType() == Aws::AutoScaling::AutoScalingErrors::ALREADY_EXISTS_FAULT) { std::cout << "Auto Scaling group '" << groupName << "' already exists." << std::endl; } else { std::cerr << "Error with AutoScaling::CreateAutoScalingGroup. " << outcome.GetError().GetMessage() << std::endl; }
-
如需詳API細資訊,請參閱AWS SDK for C++ API參考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-templateLaunchTemplateId=lt-1234567890abcde12
\ --min-size1
\ --max-size5
\ --vpc-zone-identifier"subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon Auto Scaling 使用者指南中的 EC2 Auto Scaling 群組。
範例 2:連接 Application Load Balancer、Network Load Balancer 或閘道 Load Balancer
此範例指定負載平衡器支援預期流量ARN的目標群組。健康狀態檢查類型會指定
ELB
當「Elastic Load Balancing」將執行個體回報為狀態不良時,Auto Scaling 群組會取代它。此命令也會定義健全狀況檢查寬限期 (600
秒)。寬限期有助於防止新啟動的執行個體過早終止。aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --launch-templateLaunchTemplateId=lt-1234567890abcde12
\ --target-group-arnsarn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/943f017f100becff
\ --health-check-typeELB
\ --health-check-grace-period600
\ --min-size1
\ --max-size5
\ --vpc-zone-identifier"subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon EC2 Auto Scaling 使用者指南中的 Elastic Load Balancing 和 Amazon EC2 Auto Scaling。
範例 3:指定置放群組並使用最新版本的啟動範本
此範例會將執行個體啟動至單一可用區域內的置放群組。這對於具有HPC工作負載的低延遲群組很有用。此範例也會指定群組的最小大小、最大大小和所需容量。
aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --launch-template LaunchTemplateId=lt-1
2345
67890abcde12,Version='$Latest' \ --min-size 1 \ --max-size 5 \ --desired-capacity3
\ --placement-groupmy-placement-group
\ --vpc-zone-identifier"subnet-6194ea3b"
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon Linux 執行個體EC2使用者指南中的放置群組。
範例 4:若要指定單一執行個體 Auto Scaling 群組,並使用特定版本的啟動範本
此範例會建立 Auto Scaling 群組,其中設定了最小和最大容量,
1
以強制執行一個執行個體。該命令還指定了指定現有 ID 的啟動模板ENI的 v1。當您使用指定 eth0 現有的啟動範本時,必須ENI為與網路介面相符的 Auto Scaling 群組指定可用區域,而不必在要求中指定子網路 ID。aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name
my-asg-single-instance
\ --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='1
' \ --min-size1
\ --max-size 1 \ --availability-zonesus-west-2a
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon Auto Scaling 使用者指南中的 EC2 Auto Scaling 群組。
範例 5:指定不同的終止原則
此範例會使用啟動設定建立 Auto Scaling 群組,並將終止原則設定為先終止最舊的執行個體。此指令也會將標籤套用至群組及其執行個體,索引鍵
Role
和值為WebServer
。aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --launch-configuration-namemy-lc
\ --min-size1
\ --max-size5
\ --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 終止政策。
範例 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 生命週期掛鉤。
範例 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 生命週期掛鉤。
範例 8:指定自訂終止原則
此範例會建立一個 Auto Scaling 群組,該群組指定自訂 Lambda 函數終止政策,告知 Amazon EC2 Auto Scaling 哪些執行個體可以安全地在中大規模終止。
aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name
my-asg-single-instance
\ --launch-templateLaunchTemplateName=my-template-for-auto-scaling
\ --min-size1
\ --max-size5
\ --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 建立自訂終止政策。
-
如需詳API細資訊,請參閱AWS CLI 指令參考CreateAutoScalingGroup
中的。
-
- Java
-
- SDK對於爪哇 2.x
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.autoscaling.AutoScalingClient; import software.amazon.awssdk.services.autoscaling.model.AutoScalingException; import software.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest; import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse; import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification; import software.amazon.awssdk.services.autoscaling.waiters.AutoScalingWaiter; /** * Before running this SDK for Java (v2) code example, set up your development * environment, including your credentials. * * For more information, see the following documentation: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateAutoScalingGroup { public static void main(String[] args) { final String usage = """ Usage: <groupName> <launchTemplateName> <serviceLinkedRoleARN> <vpcZoneId> Where: groupName - The name of the Auto Scaling group. launchTemplateName - The name of the launch template.\s vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created. """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String groupName = args[0]; String launchTemplateName = args[1]; String vpcZoneId = args[2]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() .region(Region.US_EAST_1) .build(); createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId); autoScalingClient.close(); } public static void createAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName, String launchTemplateName, String vpcZoneId) { try { AutoScalingWaiter waiter = autoScalingClient.waiter(); LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder() .launchTemplateName(launchTemplateName) .build(); CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder() .autoScalingGroupName(groupName) .availabilityZones("us-east-1a") .launchTemplate(templateSpecification) .maxSize(1) .minSize(1) .vpcZoneIdentifier(vpcZoneId) .build(); autoScalingClient.createAutoScalingGroup(request); DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder() .autoScalingGroupNames(groupName) .build(); WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter .waitUntilGroupExists(groupsRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Auto Scaling Group created"); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
-
如需詳API細資訊,請參閱AWS SDK for Java 2.x API參考CreateAutoScalingGroup中的。
-
- Kotlin
-
- SDK對於科特林
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 suspend fun createAutoScalingGroup( groupName: String, launchTemplateNameVal: String, serviceLinkedRoleARNVal: String, vpcZoneIdVal: String, ) { val templateSpecification = LaunchTemplateSpecification { launchTemplateName = launchTemplateNameVal } val request = CreateAutoScalingGroupRequest { autoScalingGroupName = groupName availabilityZones = listOf("us-east-1a") launchTemplate = templateSpecification maxSize = 1 minSize = 1 vpcZoneIdentifier = vpcZoneIdVal serviceLinkedRoleArn = serviceLinkedRoleARNVal } // This object is required for the waiter call. val groupsRequestWaiter = DescribeAutoScalingGroupsRequest { autoScalingGroupNames = listOf(groupName) } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.createAutoScalingGroup(request) autoScalingClient.waitUntilGroupExists(groupsRequestWaiter) println("$groupName was created!") } }
-
有API關詳細資訊,請參閱CreateAutoScalingGroup
中AWS SDK的以取得 Kotlin API 的參考資料
-
- PHP
-
- 適用於 PHP 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function createAutoScalingGroup( $autoScalingGroupName, $availabilityZones, $minSize, $maxSize, $launchTemplateId ) { return $this->autoScalingClient->createAutoScalingGroup([ 'AutoScalingGroupName' => $autoScalingGroupName, 'AvailabilityZones' => $availabilityZones, 'MinSize' => $minSize, 'MaxSize' => $maxSize, 'LaunchTemplate' => [ 'LaunchTemplateId' => $launchTemplateId, ], ]); }
-
如需詳API細資訊,請參閱AWS SDK for PHP API參考CreateAutoScalingGroup中的。
-
- PowerShell
-
- 適用的工具 PowerShell
-
範例 1:此範例會建立具有指定名稱和屬性的「Auto Scaling」群組。預設所需容量為最小大小。因此,此 Auto Scaling 群組會啟動兩個執行個體,在指定的兩個可用區域中各一個執行個體。
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
-
如需詳API細資訊,請參閱AWS Tools for PowerShell 指令程CreateAutoScalingGroup式參考中的。
-
- Python
-
- SDK對於 Python(肉毒桿菌 3)
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 class AutoScalingWrapper: """Encapsulates Amazon EC2 Auto Scaling actions.""" def __init__(self, autoscaling_client): """ :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client. """ self.autoscaling_client = autoscaling_client def create_group( self, group_name, group_zones, launch_template_name, min_size, max_size ): """ 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. """ 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, ) except ClientError as err: logger.error( "Couldn't create group %s. Here's why: %s: %s", group_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
如需API詳細資訊,請參閱CreateAutoScalingGroup中AWS SDK的〈〉中的〈〉API。
-
- Rust
-
- SDK對於銹
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 async fn create_group(client: &Client, name: &str, id: &str) -> Result<(), Error> { client .create_auto_scaling_group() .auto_scaling_group_name(name) .instance_id(id) .min_size(1) .max_size(5) .send() .await?; println!("Created AutoScaling group"); Ok(()) }
-
如需詳API細資訊,請參閱CreateAutoScalingGroup
中AWS SDK的以取得 Rust API 參考
-
如需建立混合執行個體群組時可使用的範例,請參閱下列資源。
使用更新 Auto Scaling 群組 AWS SDK
下列程式碼範例會示範如何使用UpdateAutoScalingGroup
。
- .NET
-
- AWS SDK for .NET
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <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中的。
-
- C++
-
- SDK對於 C ++
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig); Aws::AutoScaling::Model::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++ API參考UpdateAutoScalingGroup中的。
-
- CLI
-
- AWS CLI
-
範例 1:更新「Auto Scaling」群組的大小限制
此範例會更新指定的「Auto Scaling」群組,其大小下限為 2 且大小上限為 10。
aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --min-size2
\ --max-size10
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon Auto Scaling 使用者指南中的為您的 EC2 Auto Scaling 群組設定容量限制。
範例 2:新增 Elastic Load Balancing 健全狀況檢查,並指定要使用的可用區域和子網路
此範例會更新指定的 Auto Scaling 群組,以新增 Elastic Load Balancing 健康狀態檢查。此命令也會
--vpc-zone-identifier
使用多個可用區域IDs中子網路清單來更新的值。aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --health-check-typeELB
\ --health-check-grace-period600
\ --vpc-zone-identifier"subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon EC2 Auto Scaling 使用者指南中的 Elastic Load Balancing 和 Amazon EC2 Auto Scaling。
範例 3:若要更新置放群組和終止原則
此範例會更新要使用的置放群組和終止原則。
aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --placement-groupmy-placement-group
\ --termination-policies"OldestInstance"
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon Auto Scaling 使用者指南中的 EC2 Auto Scaling 群組。
範例 4:若要使用最新版本的啟動範本
此範例會將指定的 Auto Scaling 群組更新為使用指定啟動範本的最新版本。
aws autoscaling update-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest'此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon EC2 自動擴展使用者指南中的啟動範本。
範例 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 自動擴展使用者指南中的啟動範本。
範例 6:定義混合執行個體政策並啟用容量重新平衡
此範例將指定的 Auto Scaling 群組更新為使用混合執行個體原則,並啟用容量重新平衡。此結構可讓您指定具有 Spot 和隨需容量的群組,並針對不同架構使用不同的啟動範本。
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 Auto Scaling 使用者指南中的具有多個執行個體類型的 EC2 Auto Scaling 群組和購買選項。
-
如需詳API細資訊,請參閱AWS CLI 指令參考UpdateAutoScalingGroup
中的。
-
- Java
-
- SDK對於爪哇 2.x
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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中的。
-
- Kotlin
-
- SDK對於科特林
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 suspend fun updateAutoScalingGroup( groupName: String, launchTemplateNameVal: String, serviceLinkedRoleARNVal: String, ) { val templateSpecification = LaunchTemplateSpecification { launchTemplateName = launchTemplateNameVal } val groupRequest = UpdateAutoScalingGroupRequest { maxSize = 3 serviceLinkedRoleArn = serviceLinkedRoleARNVal autoScalingGroupName = groupName launchTemplate = templateSpecification } val groupsRequestWaiter = DescribeAutoScalingGroupsRequest { autoScalingGroupNames = listOf(groupName) } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.updateAutoScalingGroup(groupRequest) autoScalingClient.waitUntilGroupExists(groupsRequestWaiter) println("You successfully updated the Auto Scaling group $groupName") } }
-
有API關詳細資訊,請參閱UpdateAutoScalingGroup
中AWS SDK的以取得 Kotlin API 的參考資料
-
- PHP
-
- 適用於 PHP 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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中的。
-
- PowerShell
-
- 適用的工具 PowerShell
-
範例 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 指令程UpdateAutoScalingGroup式參考中的。
-
- Python
-
- SDK對於 Python(肉毒桿菌 3)
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 class AutoScalingWrapper: """Encapsulates Amazon EC2 Auto Scaling actions.""" def __init__(self, autoscaling_client): """ :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client. """ self.autoscaling_client = autoscaling_client def update_group(self, group_name, **kwargs): """ 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. """ try: self.autoscaling_client.update_auto_scaling_group( AutoScalingGroupName=group_name, **kwargs ) except ClientError as err: logger.error( "Couldn't update group %s. Here's why: %s: %s", group_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
-
如需API詳細資訊,請參閱UpdateAutoScalingGroup中AWS SDK的〈〉中的〈〉API。
-
- Rust
-
- SDK對於銹
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 async fn update_group(client: &Client, name: &str, size: i32) -> Result<(), Error> { client .update_auto_scaling_group() .auto_scaling_group_name(name) .max_size(size) .send() .await?; println!("Updated AutoScaling group"); Ok(()) }
-
如需詳API細資訊,請參閱UpdateAutoScalingGroup
中AWS SDK的以取得 Rust API 參考
-
使用描述「Auto Scaling」群組 AWS SDK
下列程式碼範例會示範如何使用DescribeAutoScalingGroups
。
- .NET
-
- AWS SDK for .NET
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /// <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>(); groups!.ForEach(group => { if (group.AutoScalingGroupName == groupName) { group.Instances.ForEach(instance => { instanceIds.Add(instance.InstanceId); }); } }); var scalingGroupsRequest = new DescribeAutoScalingInstancesRequest { MaxRecords = 10, InstanceIds = instanceIds, }; var response = await _amazonAutoScaling.DescribeAutoScalingInstancesAsync(scalingGroupsRequest); var instanceDetails = response.AutoScalingInstances; return instanceDetails; }
-
如需詳API細資訊,請參閱AWS SDK for .NET API參考DescribeAutoScalingGroups中的。
-
- C++
-
- SDK對於 C ++
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig); Aws::AutoScaling::Model::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++ API參考DescribeAutoScalingGroups中的。
-
- CLI
-
- AWS CLI
-
範例 1:描述指定的「Auto Scaling」群組
此範例說明指定的「Auto Scaling」群組。
aws autoscaling describe-auto-scaling-groups \ --auto-scaling-group-name
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-name"group1"
"group2"
"group3"
"group4"
如需範例輸出,請參閱範例 1。
範例 3:描述指定區域中的「Auto Scaling」群組
此範例說明指定區域中的「Auto Scaling 例」群組,最多 75 個群組。
aws autoscaling describe-auto-scaling-groups \ --max-items
75
\ --regionus-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:說明使用啟動設定的「自動調整比例」群組
此範例使用
--query
選項來描述使用啟動設定的「自動調整比例」群組。aws autoscaling describe-auto-scaling-groups \ --query '
AutoScalingGroups[?LaunchConfigurationName!=`null`]
'輸出:
[ { "AutoScalingGroupName": "my-asg", "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480f03:autoScalingGroupName/my-asg", "LaunchConfigurationName": "my-lc", "MinSize": 0, "MaxSize": 1, "DesiredCapacity": 1, "DefaultCooldown": 300, "AvailabilityZones": [ "us-west-2a", "us-west-2b", "us-west-2c" ], "LoadBalancerNames": [], "TargetGroupARNs": [], "HealthCheckType": "EC2", "HealthCheckGracePeriod": 0, "Instances": [ { "InstanceId": "i-088c57934a6449037", "InstanceType": "t2.micro", "AvailabilityZone": "us-west-2c", "HealthStatus": "Healthy", "LifecycleState": "InService", "LaunchConfigurationName": "my-lc", "ProtectedFromScaleIn": false } ], "CreatedTime": "2023-10-28T02:39:22.152Z", "SuspendedProcesses": [], "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782", "EnabledMetrics": [], "Tags": [], "TerminationPolicies": [ "Default" ], "NewInstancesProtectedFromScaleIn": false, "ServiceLinkedRoleARN":"arn", "TrafficSources": [] } ]
若要取得更多資訊,請參閱《指AWS 令行介面使用指南》中的〈篩選 AWS CLI輸出〉
-
如需詳API細資訊,請參閱AWS CLI 指令參考DescribeAutoScalingGroups
中的。
-
- Java
-
- SDK對於爪哇 2.x
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 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中的。
-
- Kotlin
-
- SDK對於科特林
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 suspend fun getAutoScalingGroups(groupName: String) { val scalingGroupsRequest = DescribeAutoScalingGroupsRequest { autoScalingGroupNames = listOf(groupName) } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> val response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest) response.autoScalingGroups?.forEach { group -> println("The group name is ${group.autoScalingGroupName}") println("The group ARN is ${group.autoScalingGroupArn}") group.instances?.forEach { instance -> println("The instance id is ${instance.instanceId}") println("The lifecycle state is " + instance.lifecycleState) } } } }
-
有API關詳細資訊,請參閱DescribeAutoScalingGroups
中AWS SDK的以取得 Kotlin API 的參考資料
-
- PHP
-
- 適用於 PHP 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function describeAutoScalingGroups($autoScalingGroupNames) { return $this->autoScalingClient->describeAutoScalingGroups([ 'AutoScalingGroupNames' => $autoScalingGroupNames ]); }
-
如需詳API細資訊,請參閱AWS SDK for PHP API參考DescribeAutoScalingGroups中的。
-
- PowerShell
-
- 適用的工具 PowerShell
-
範例 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:此範例說明指定的兩個「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:此範例以 10 個批次描述所有「Auto Scaling 例」群組。
$nextToken = $null do { Get-ASAutoScalingGroup -NextToken $nextToken -MaxRecord 10 $nextToken = $AWSHistory.LastServiceResponse.NextToken } while ($nextToken -ne $null)
範例 7:此範例說明指定 LaunchTemplate 的「Auto Scaling」群組。此範例假設「執行個體購買選項」設定為「堅持啟動範本」。如果將此選項設為「合併購買選項和執行個體類型」,則 LaunchTemplate 可以使用「MixedInstancesPolicy。 LaunchTemplate「屬性。
(Get-ASAutoScalingGroup -AutoScalingGroupName my-ag-1).LaunchTemplate
輸出:
LaunchTemplateId LaunchTemplateName Version ---------------- ------------------ ------- lt-06095fd619cb40371 test-launch-template $Default
-
如需詳API細資訊,請參閱AWS Tools for PowerShell 指令程DescribeAutoScalingGroups式參考中的。
-
- Python
-
- SDK對於 Python(肉毒桿菌 3)
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 class AutoScalingWrapper: """Encapsulates Amazon EC2 Auto Scaling actions.""" def __init__(self, autoscaling_client): """ :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client. """ self.autoscaling_client = autoscaling_client def describe_group(self, group_name): """ Gets information about an Auto Scaling group. :param group_name: The name of the group to look up. :return: Information about the group, if found. """ try: response = self.autoscaling_client.describe_auto_scaling_groups( AutoScalingGroupNames=[group_name] ) except ClientError as err: logger.error( "Couldn't describe group %s. Here's why: %s: %s", group_name, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: groups = response.get("AutoScalingGroups", []) return groups[0] if len(groups) > 0 else None
-
如需API詳細資訊,請參閱DescribeAutoScalingGroups中AWS SDK的〈〉中的〈〉API。
-
- Rust
-
- SDK對於銹
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 async fn list_groups(client: &Client) -> Result<(), Error> { let resp = client.describe_auto_scaling_groups().send().await?; println!("Groups:"); let groups = resp.auto_scaling_groups(); for group in groups { println!( "Name: {}", group.auto_scaling_group_name().unwrap_or("Unknown") ); println!( "Arn: {}", group.auto_scaling_group_arn().unwrap_or("unknown"), ); println!("Zones: {:?}", group.availability_zones(),); println!(); } println!("Found {} group(s)", groups.len()); Ok(()) }
-
如需詳API細資訊,請參閱DescribeAutoScalingGroups
中AWS SDK的以取得 Rust API 參考
-
使用刪除「Auto Scaling」群組 AWS SDK
下列程式碼範例會示範如何使用DeleteAutoScalingGroup
。
- .NET
-
- AWS SDK for .NET
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 將 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; }
-
如需詳API細資訊,請參閱AWS SDK for .NET API參考DeleteAutoScalingGroup中的。
-
- C++
-
- SDK對於 C ++
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig); Aws::AutoScaling::Model::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++ API參考DeleteAutoScalingGroup中的。
-
- CLI
-
- AWS CLI
-
範例 1:若要刪除指定的「Auto Scaling」群組
此範例會刪除指定的「Auto Scaling」群組。
aws autoscaling delete-auto-scaling-group \ --auto-scaling-group-name
my-asg
此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon Auto Scaling 使用者指南中的刪除 EC2 Auto Scaling 基礎設施。
範例 2:強制刪除指定的「Auto Scaling」群組
若要刪除 Auto Scaling 群組而不等待群組中的執行個體終止,請使用
--force-delete
選項。aws autoscaling delete-auto-scaling-group \ --auto-scaling-group-name
my-asg
\ --force-delete此命令不會產生輸出。
如需詳細資訊,請參閱 Amazon Auto Scaling 使用者指南中的刪除 EC2 Auto Scaling 基礎設施。
-
如需詳API細資訊,請參閱AWS CLI 指令參考DeleteAutoScalingGroup
中的。
-
- Java
-
- SDK對於爪哇 2.x
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.autoscaling.AutoScalingClient; import software.amazon.awssdk.services.autoscaling.model.AutoScalingException; import software.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest; /** * Before running this SDK for Java (v2) code example, set up your development * environment, including your credentials. * * For more information, see the following documentation: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteAutoScalingGroup { public static void main(String[] args) { final String usage = """ Usage: <groupName> Where: groupName - The name of the Auto Scaling group. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String groupName = args[0]; AutoScalingClient autoScalingClient = AutoScalingClient.builder() .region(Region.US_EAST_1) .build(); deleteAutoScalingGroup(autoScalingClient, groupName); autoScalingClient.close(); } public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) { try { DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder() .autoScalingGroupName(groupName) .forceDelete(true) .build(); autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest); System.out.println("You successfully deleted " + groupName); } catch (AutoScalingException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
-
如需詳API細資訊,請參閱AWS SDK for Java 2.x API參考DeleteAutoScalingGroup中的。
-
- Kotlin
-
- SDK對於科特林
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 suspend fun deleteSpecificAutoScalingGroup(groupName: String) { val deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest { autoScalingGroupName = groupName forceDelete = true } AutoScalingClient { region = "us-east-1" }.use { autoScalingClient -> autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest) println("You successfully deleted $groupName") } }
-
有API關詳細資訊,請參閱DeleteAutoScalingGroup
中AWS SDK的以取得 Kotlin API 的參考資料
-
- PHP
-
- 適用於 PHP 的 SDK
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function deleteAutoScalingGroup($autoScalingGroupName) { return $this->autoScalingClient->deleteAutoScalingGroup([ 'AutoScalingGroupName' => $autoScalingGroupName, 'ForceDelete' => true, ]); }
-
如需詳API細資訊,請參閱AWS SDK for PHP API參考DeleteAutoScalingGroup中的。
-
- PowerShell
-
- 適用的工具 PowerShell
-
範例 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:如果您指定「力」參數,則在進行作業之前,系統不會提示您進行確認。
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force
範例 3:此範例會刪除指定的 Auto Scaling 群組,並終止其包含的任何執行中執行個體。
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
-
如需詳API細資訊,請參閱AWS Tools for PowerShell 指令程DeleteAutoScalingGroup式參考中的。
-
- Python
-
- SDK對於 Python(肉毒桿菌 3)
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 將 Auto Scaling 群組的最小大小更新為零,終止群組中的所有執行個體,然後刪除該群組。
class AutoScaler: """ Encapsulates Amazon EC2 Auto Scaling and EC2 management actions. """ def __init__( self, resource_prefix, inst_type, ami_param, autoscaling_client, ec2_client, ssm_client, iam_client, ): """ :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 self.launch_template_name = f"{resource_prefix}-template" self.group_name = f"{resource_prefix}-group" self.instance_policy_name = f"{resource_prefix}-pol" self.instance_role_name = f"{resource_prefix}-role" self.instance_profile_name = f"{resource_prefix}-prof" 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" self.key_pair_name = f"{resource_prefix}-key-pair" def _try_terminate_instance(self, inst_id): stopping = False log.info(f"Stopping {inst_id}.") while not stopping: try: self.autoscaling_client.terminate_instance_in_auto_scaling_group( InstanceId=inst_id, ShouldDecrementDesiredCapacity=True ) stopping = True except ClientError as err: if err.response["Error"]["Code"] == "ScalingActivityInProgress": log.info("Scaling activity in progress for %s. Waiting...", inst_id) time.sleep(10) else: raise AutoScalerError(f"Couldn't stop instance {inst_id}: {err}.") def _try_delete_group(self): """ Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress, the function waits and retries until the group is successfully deleted. """ stopped = False while not stopped: try: self.autoscaling_client.delete_auto_scaling_group( AutoScalingGroupName=self.group_name ) stopped = True log.info("Deleted EC2 Auto Scaling group %s.", self.group_name) except ClientError as err: if ( err.response["Error"]["Code"] == "ResourceInUse" or err.response["Error"]["Code"] == "ScalingActivityInProgress" ): log.info( "Some instances are still running. Waiting for them to stop..." ) time.sleep(10) else: raise AutoScalerError( f"Couldn't delete group {self.group_name}: {err}." ) def delete_group(self): """ Terminates all instances in the group, deletes the EC2 Auto Scaling group. """ try: response = self.autoscaling_client.describe_auto_scaling_groups( AutoScalingGroupNames=[self.group_name] ) groups = response.get("AutoScalingGroups", []) if len(groups) > 0: self.autoscaling_client.update_auto_scaling_group( AutoScalingGroupName=self.group_name, MinSize=0 ) instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]] for inst_id in instance_ids: self._try_terminate_instance(inst_id) self._try_delete_group() else: log.info("No groups found named %s, nothing to do.", self.group_name) except ClientError as err: raise AutoScalerError(f"Couldn't delete group {self.group_name}: {err}.")
-
如需API詳細資訊,請參閱DeleteAutoScalingGroup中AWS SDK的〈〉中的〈〉API。
-
- Rust
-
- SDK對於銹
-
注意
還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 async fn delete_group(client: &Client, name: &str, force: bool) -> Result<(), Error> { client .delete_auto_scaling_group() .auto_scaling_group_name(name) .set_force_delete(if force { Some(true) } else { None }) .send() .await?; println!("Deleted Auto Scaling group"); Ok(()) }
-
如需詳API細資訊,請參閱DeleteAutoScalingGroup
中AWS SDK的以取得 Rust API 參考
-
可用性範例
找不到所需的內容嗎? 請使用本頁面底部的提供意見回饋連結申請新版程式碼範例。