使用 SDK for PHP Auto Scaling 示例 - AWS SDK for PHP

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

使用 SDK for PHP Auto Scaling 示例

下列程式碼範例說明如何透過 AWS SDK for PHP 搭配 Auto Scaling 使用來執行動作及實作常見案例。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境和跨服務範例中查看內容中的動作。

Scenarios (案例) 是向您展示如何呼叫相同服務中的多個函數來完成特定任務的程式碼範例。

每個範例都包含一個連結 GitHub,您可以在其中找到如何在內容中設定和執行程式碼的指示。

開始使用

下列程式碼範例顯示如何開始使用「Auto Scaling」。

適用於 PHP 的開發套件
注意

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

public function helloService() { $autoScalingClient = new AutoScalingClient([ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]); $groups = $autoScalingClient->describeAutoScalingGroups([]); var_dump($groups); }

動作

下列程式碼範例會示範如何使用CreateAutoScalingGroup

適用於 PHP 的開發套件
注意

還有更多關於 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, ], ]); }

下列程式碼範例會示範如何使用DeleteAutoScalingGroup

適用於 PHP 的開發套件
注意

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

public function deleteAutoScalingGroup($autoScalingGroupName) { return $this->autoScalingClient->deleteAutoScalingGroup([ 'AutoScalingGroupName' => $autoScalingGroupName, 'ForceDelete' => true, ]); }

下列程式碼範例會示範如何使用DescribeAutoScalingGroups

適用於 PHP 的開發套件
注意

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

public function describeAutoScalingGroups($autoScalingGroupNames) { return $this->autoScalingClient->describeAutoScalingGroups([ 'AutoScalingGroupNames' => $autoScalingGroupNames ]); }

下列程式碼範例會示範如何使用DescribeAutoScalingInstances

適用於 PHP 的開發套件
注意

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

public function describeAutoScalingInstances($instanceIds) { return $this->autoScalingClient->describeAutoScalingInstances([ 'InstanceIds' => $instanceIds ]); }

下列程式碼範例會示範如何使用DescribeScalingActivities

適用於 PHP 的開發套件
注意

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

public function describeScalingActivities($autoScalingGroupName) { return $this->autoScalingClient->describeScalingActivities([ 'AutoScalingGroupName' => $autoScalingGroupName, ]); }

下列程式碼範例會示範如何使用DisableMetricsCollection

適用於 PHP 的開發套件
注意

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

public function disableMetricsCollection($autoScalingGroupName) { return $this->autoScalingClient->disableMetricsCollection([ 'AutoScalingGroupName' => $autoScalingGroupName, ]); }

下列程式碼範例會示範如何使用EnableMetricsCollection

適用於 PHP 的開發套件
注意

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

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

下列程式碼範例會示範如何使用SetDesiredCapacity

適用於 PHP 的開發套件
注意

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

public function setDesiredCapacity($autoScalingGroupName, $desiredCapacity) { return $this->autoScalingClient->setDesiredCapacity([ 'AutoScalingGroupName' => $autoScalingGroupName, 'DesiredCapacity' => $desiredCapacity, ]); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考SetDesiredCapacity中的。

下列程式碼範例會示範如何使用TerminateInstanceInAutoScalingGroup

適用於 PHP 的開發套件
注意

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

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; } } }

下列程式碼範例會示範如何使用UpdateAutoScalingGroup

適用於 PHP 的開發套件
注意

還有更多關於 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); }

案例

以下程式碼範例顯示做法:

  • 使用啟動範本和可用區域建立 Amazon EC2 Auto Scaling 群組,並取得執行中執行個體的相關資訊。

  • 啟用 Amazon CloudWatch 指標收集。

  • 更新群組所需的容量,並等待執行個體啟動。

  • 終止群組中的執行個體。

  • 列出因應使用者要求和容量變更而發生的調整活動。

  • 取得 CloudWatch 指標的統計資料,然後清理資源。

適用於 PHP 的開發套件
注意

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

namespace AutoScaling; use Aws\AutoScaling\AutoScalingClient; use Aws\CloudWatch\CloudWatchClient; use Aws\Ec2\Ec2Client; use AwsUtilities\AWSServiceClass; use AwsUtilities\RunnableExample; class GettingStartedWithAutoScaling implements RunnableExample { protected Ec2Client $ec2Client; protected AutoScalingClient $autoScalingClient; protected AutoScalingService $autoScalingService; protected CloudWatchClient $cloudWatchClient; protected string $templateName; protected string $autoScalingGroupName; protected array $role; public function runExample() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon EC2 Auto Scaling getting started demo using PHP!\n"); echo("--------------------------------------\n"); $clientArgs = [ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]; $uniqid = uniqid(); $this->autoScalingClient = new AutoScalingClient($clientArgs); $this->autoScalingService = new AutoScalingService($this->autoScalingClient); $this->cloudWatchClient = new CloudWatchClient($clientArgs); AWSServiceClass::$waitTime = 5; AWSServiceClass::$maxWaitAttempts = 20; /** * Step 0: Create an EC2 launch template that you'll use to create an Auto Scaling group. */ $this->ec2Client = new EC2Client($clientArgs); $this->templateName = "example_launch_template_$uniqid"; $instanceType = "t1.micro"; $amiId = "ami-0ca285d4c2cda3300"; $launchTemplate = $this->ec2Client->createLaunchTemplate( [ 'LaunchTemplateName' => $this->templateName, 'LaunchTemplateData' => [ 'InstanceType' => $instanceType, 'ImageId' => $amiId, ] ] ); /** * Step 1: CreateAutoScalingGroup: pass it the launch template you created in step 0. */ $availabilityZones[] = $this->ec2Client->describeAvailabilityZones([])['AvailabilityZones'][1]['ZoneName']; $this->autoScalingGroupName = "demoAutoScalingGroupName_$uniqid"; $minSize = 1; $maxSize = 1; $launchTemplateId = $launchTemplate['LaunchTemplate']['LaunchTemplateId']; $this->autoScalingService->createAutoScalingGroup( $this->autoScalingGroupName, $availabilityZones, $minSize, $maxSize, $launchTemplateId ); $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]); $autoScalingGroup = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]); /** * Step 2: DescribeAutoScalingInstances: show that one instance has launched. */ $instanceIds = [$autoScalingGroup['AutoScalingGroups'][0]['Instances'][0]['InstanceId']]; $instances = $this->autoScalingService->describeAutoScalingInstances($instanceIds); echo "The Auto Scaling group {$this->autoScalingGroupName} was created successfully.\n"; echo count($instances['AutoScalingInstances']) . " instances were created for the group.\n"; echo $autoScalingGroup['AutoScalingGroups'][0]['MaxSize'] . " is the max number of instances for the group.\n"; /** * Step 3: EnableMetricsCollection: enable all metrics or a subset. */ $this->autoScalingService->enableMetricsCollection($this->autoScalingGroupName, "1Minute"); /** * Step 4: UpdateAutoScalingGroup: update max size to 3. */ echo "Updating the max number of instances to 3.\n"; $this->autoScalingService->updateAutoScalingGroup($this->autoScalingGroupName, ['MaxSize' => 3]); /** * Step 5: DescribeAutoScalingGroups: show the current state of the group. */ $autoScalingGroup = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]); echo $autoScalingGroup['AutoScalingGroups'][0]['MaxSize']; echo " is the updated max number of instances for the group.\n"; $limits = $this->autoScalingService->describeAccountLimits(); echo "Here are your account limits:\n"; echo "MaxNumberOfAutoScalingGroups: {$limits['MaxNumberOfAutoScalingGroups']}\n"; echo "MaxNumberOfLaunchConfigurations: {$limits['MaxNumberOfLaunchConfigurations']}\n"; echo "NumberOfAutoScalingGroups: {$limits['NumberOfAutoScalingGroups']}\n"; echo "NumberOfLaunchConfigurations: {$limits['NumberOfLaunchConfigurations']}\n"; /** * Step 6: SetDesiredCapacity: set desired capacity to 2. */ $this->autoScalingService->setDesiredCapacity($this->autoScalingGroupName, 2); sleep(10); // Wait for the group to start processing the request. $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]); /** * Step 7: DescribeAutoScalingInstances: show that two instances are launched. */ $autoScalingGroups = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]); foreach ($autoScalingGroups['AutoScalingGroups'] as $autoScalingGroup) { echo "There is a group named: {$autoScalingGroup['AutoScalingGroupName']}"; echo "with an ARN of {$autoScalingGroup['AutoScalingGroupARN']}.\n"; foreach ($autoScalingGroup['Instances'] as $instance) { echo "{$autoScalingGroup['AutoScalingGroupName']} has an instance with id of: "; echo "{$instance['InstanceId']} and a lifecycle state of: {$instance['LifecycleState']}.\n"; } } /** * Step 8: TerminateInstanceInAutoScalingGroup: terminate one of the instances in the group. */ $this->autoScalingService->terminateInstanceInAutoScalingGroup($instance['InstanceId'], false); do { sleep(10); $instances = $this->autoScalingService->describeAutoScalingInstances([$instance['InstanceId']]); } while (count($instances['AutoScalingInstances']) > 0); do { sleep(10); $autoScalingGroups = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]); $instances = $autoScalingGroups['AutoScalingGroups'][0]['Instances']; } while (count($instances) < 2); $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]); foreach ($autoScalingGroups['AutoScalingGroups'] as $autoScalingGroup) { echo "There is a group named: {$autoScalingGroup['AutoScalingGroupName']}"; echo "with an ARN of {$autoScalingGroup['AutoScalingGroupARN']}.\n"; foreach ($autoScalingGroup['Instances'] as $instance) { echo "{$autoScalingGroup['AutoScalingGroupName']} has an instance with id of: "; echo "{$instance['InstanceId']} and a lifecycle state of: {$instance['LifecycleState']}.\n"; } } /** * Step 9: DescribeScalingActivities: list the scaling activities that have occurred for the group so far. */ $activities = $this->autoScalingService->describeScalingActivities($autoScalingGroup['AutoScalingGroupName']); echo "We found " . count($activities['Activities']) . " activities.\n"; foreach ($activities['Activities'] as $activity) { echo "{$activity['ActivityId']} - {$activity['StartTime']} - {$activity['Description']}\n"; } /** * Step 10: Use the Amazon CloudWatch API to get and show some metrics collected for the group. */ $metricsNamespace = 'AWS/AutoScaling'; $metricsDimensions = [ [ 'Name' => 'AutoScalingGroupName', 'Value' => $autoScalingGroup['AutoScalingGroupName'], ], ]; $metrics = $this->cloudWatchClient->listMetrics( [ 'Dimensions' => $metricsDimensions, 'Namespace' => $metricsNamespace, ] ); foreach ($metrics['Metrics'] as $metric) { $timespan = 5; if ($metric['MetricName'] != 'GroupTotalCapacity' && $metric['MetricName'] != 'GroupMaxSize') { continue; } echo "Over the last $timespan minutes, {$metric['MetricName']} recorded:\n"; $stats = $this->cloudWatchClient->getMetricStatistics( [ 'Dimensions' => $metricsDimensions, 'EndTime' => time(), 'StartTime' => time() - (5 * 60), 'MetricName' => $metric['MetricName'], 'Namespace' => $metricsNamespace, 'Period' => 60, 'Statistics' => ['Sum'], ] ); foreach ($stats['Datapoints'] as $stat) { echo "{$stat['Timestamp']}: {$stat['Sum']}\n"; } } return $instances; } public function cleanUp() { /** * Step 11: DisableMetricsCollection: disable all metrics. */ $this->autoScalingService->disableMetricsCollection($this->autoScalingGroupName); /** * Step 12: DeleteAutoScalingGroup: to delete the group you must stop all instances. * - UpdateAutoScalingGroup with MinSize=0 * - TerminateInstanceInAutoScalingGroup for each instance, * specify ShouldDecrementDesiredCapacity=True. Wait for instances to stop. * - Now you can delete the group. */ $this->autoScalingService->updateAutoScalingGroup($this->autoScalingGroupName, ['MinSize' => 0]); $this->autoScalingService->terminateAllInstancesInAutoScalingGroup($this->autoScalingGroupName); $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]); $this->autoScalingService->deleteAutoScalingGroup($this->autoScalingGroupName); /** * Step 13: Delete launch template. */ $this->ec2Client->deleteLaunchTemplate( [ 'LaunchTemplateName' => $this->templateName, ] ); } public function helloService() { $autoScalingClient = new AutoScalingClient([ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]); $groups = $autoScalingClient->describeAutoScalingGroups([]); var_dump($groups); } }