跳至内容

如何解决在使用 PowerShell 以编程方式启动多个 Amazon EC2 实例时出现的“RequestLimitExceeded”错误?

2 分钟阅读
0

当我使用 PowerShell 启动多个 Amazon Elastic Compute Cloud (Amazon EC2) 实例时,我收到“RequestLimitExceeded”错误。

解决方法

您用于启动 EC2 实例的脚本必须遵守 API 请求速率配额API 资源速率配额。如果您超过这些配额,则会收到“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 = 15
     }
  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!"
}

注意:AMI_ID 替换为您的亚马逊机器映像 (AMI) ID,将 Subnet_ID 替换为您的子网 ID,将 m5a.large 替换为您的实例类型。此外,将 10 替换为要启动的最小实例数,将 15 替换为要启动的最大实例数。

如果您的请求速率不可预测,请在脚本中加入重试逻辑。

脚本示例:

# 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 = 40
            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)

注意:AMI_ID 替换为您的 AMI ID,将 Subnet_ID 替换为您的子网 ID,将 m5a.large 替换为您的实例类型。此外,将 40 替换为要启动的最小实例数,将 50 替换为要启动的最大实例数。

相关信息

Request throttling for the Amazon EC2 API(Amazon EC2 API 的请求节流)

Retry behavior(重试行为)

AWS 官方已更新 5 个月前
1评论

This article was reviewed and updated on 2026-03-09.

专家

已回复 14 天前