當我使用 PowerShell 以程式設計的方式啟動多個 Amazon EC2 執行個體時,如何避免 RequestLimitExceeded 錯誤?

2 分的閱讀內容
0

當我使用 PowerShell 啟動多個 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體時,有時候會收到 RequestLimitExceeded 錯誤。

解決方案

Amazon EC2 API 的 RequestLimitExceeded 錯誤通常表示請求率限制資源率限制 API 限流。您可以使用重試邏輯和指數退避策略的組合以解決此問題。

啟動 Amazon EC2 執行個體是一項轉換呼叫,並受到請求率和資源率限制的約束。您用於啟動執行個體的指令碼必須適應記號儲存區的重新填充率。

使用下列其中一個延遲調用或重試策略,以避免 RequestLimitExceeded 錯誤。

注意事項: 適用於 .NET 的 AWS SDK 具有預設開啟的內建重試機制。若要自訂逾時,請參閱重試和逾時

下列範例包含要求的延遲調用機制。延遲調用允許要求儲存貯體填滿:

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

# Example Code to launch 50 EC2 instances of type 'm5a.large'.
try {    
  $params = @{
    ImageId = '<AMI_ID>'
    InstanceType = 'm5a.large'
    AssociatePublicIp = $false
    SubnetId = '<Subnet_ID>'
    MinCount = 10
    MaxCount = 10
     }
  for ($i=0;$i<=5;$i++){
    $instance = New-EC2Instance @params
    Start-Sleep 5000 #Sleep for 5 seconds to allow Request bucket to refill at the rate of 2 requests per second
    }
} catch {
    Write-Error "An Exception Occurred!"
}

下列範例包含指令碼中的重試邏輯:

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

#Example Code to launch 50 EC2 instances of type 'm5a.large'.
$Stoploop = $false
[int] $Retrycount = "0"
do {
    try {
        $params = @{
            ImageId = '<AMI_ID>'
            InstanceType = 'm5a.large'
            AssociatePublicIp = $false
            SubnetId = '<Subnet_ID>'
            MinCount = 50
            MaxCount = 50
        }
    $instance = New-EC2Instance @params
    $Stoploop = $true
    } catch {
        if ($Retrycount -gt 3) {
            Write - Host "Could not complete request after 3 retries."
            $Stoploop = $true
        } else {
           Write-Host "Could not complete request retrying in 5 seconds."
           Start-Sleep -Seconds 25
           #25 seconds of sleep allows for 50 request tokens to be refilled at the rate of 2/sec
           $Retrycount = $Retrycount + 1
           }
        }
    } While($Stoploop -eq $false)

相關資訊

要求適用於 Amazon EC2 API 的限流

重試行為

AWS 官方
AWS 官方已更新 1 年前