使用AWS re:Post即您表示您同意 AWS re:Post 使用条款

如何避免在使用 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 官方已更新 2 年前