CreateAutoScalingGroup 搭配 AWS SDK或 使用 CLI - Amazon EC2 Auto Scaling

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateAutoScalingGroup 搭配 AWS SDK或 使用 CLI

下列程式碼範例示範如何使用 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; }
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; }
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 Auto Scaling 使用者指南》中的 Auto Scaling 群組 EC2 Auto Scaling

範例 2:連接 Application Load Balancer、Network Load Balancer 或 Gateway Load Balancer

此範例指定支援預期流量ARN之負載平衡器的目標群組的 。運作狀態檢查類型會指定 ,ELB以便在 Elastic Load Balancing 將執行個體回報為運作狀態不佳時,Auto Scaling 群組會予以取代。命令也會定義600秒的運作狀態檢查寬限期。寬限期有助於防止新啟動的執行個體提早終止。

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-template LaunchTemplateId=lt-1234567890abcde12 \ --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/943f017f100becff \ --health-check-type ELB \ --health-check-grace-period 600 \ --min-size 1 \ --max-size 5 \ --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"

此命令不會產生輸出。

如需詳細資訊,請參閱《Amazon EC2 Auto Scaling 使用者指南》中的 Elastic Load Balancing 和 Amazon Auto Scaling。 EC2 Auto Scaling

範例 3:指定置放群組並使用最新版本的啟動範本

此範例會在單一可用區域內的置放群組中啟動執行個體。這對於具有HPC工作負載的低延遲群組很有用。此範例也會指定群組的大小下限、大小上限和所需容量。

aws autoscaling create-auto-scaling-group \ --auto-scaling-group-name my-asg \ --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest' \ --min-size 1 \ --max-size 5 \ --desired-capacity 3 \ --placement-group my-placement-group \ --vpc-zone-identifier "subnet-6194ea3b"

此命令不會產生輸出。

如需詳細資訊,請參閱《Amazon Linux 執行個體EC2使用者指南》中的置放群組

範例 4:指定單一執行個體 Auto Scaling 群組並使用啟動範本的特定版本

此範例會建立容量下限和上限設為 的 Auto Scaling 群組1,以強制執行一個執行個體將執行。命令也會指定啟動範本的 v1,其中ENI指定現有 的 ID。當您使用指定 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-size 1 \ --max-size 1 \ --availability-zones us-west-2a

此命令不會產生輸出。

如需詳細資訊,請參閱《Amazon Auto Scaling 使用者指南》中的 Auto Scaling 群組 EC2 Auto Scaling

範例 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 Auto Scaling 終止政策 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 Auto Scaling 生命週期關聯 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 Auto Scaling 生命週期關聯 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-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 建立自訂終止政策

Java
SDK 適用於 Java 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); } } }
Kotlin
SDK 適用於 Kotlin
注意

還有更多功能 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!") } }
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, ], ]); }
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")
Python
SDK for Python (Boto3)
注意

還有更多功能 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class AutoScalingWrapper: """Encapsulates Amazon EC2 Auto Scaling actions.""" def __init__(self, autoscaling_client): """ :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client. """ self.autoscaling_client = autoscaling_client def 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
Rust
SDK for Rust
注意

還有更多功能 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(()) }

如需開發人員指南和程式碼範例的完整清單 AWS SDK,請參閱 將此服務與 搭配使用 AWS SDK。本主題也包含入門的相關資訊,以及先前SDK版本的詳細資訊。