在使用 PowerShell 以编程方式启动多个 Amazon EC2 实例时,如何避免 RequestLimitExceeded 错误?
上次更新时间:2020 年 9 月 24 日
当我尝试启动多个 Amazon Elastic Compute Cloud (Amazon EC2) 实例时,有时会收到 RequestLimitExceeded 错误。如何防止收到此错误?
解决方法
Amazon EC2 API 的 RequestLimitExceeded 错误通常表示请求速率限制或资源速率限制 API 限制。您可以使用重试逻辑和指数回退策略的组合来解决此问题。
启动 Amazon EC2 实例是一种变异调用,并受请求速率和资源速率限制的约束。您用于启动实例的脚本必须适合令牌存储桶的重新填充率。
使用这些延迟调用或重试策略之一,以避免 RequestLimitExceeded 错误。
注意:适用于 .NET 的 AWS 开发工具包具有默认启用的内置重试机制。要自定义超时,请参阅重试次数和超时。
下面的示例包括您的请求的延迟调用机制,该机制允许请求存储桶填充:
# 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)