[英]How to identify disabled regions in AWS?
AWS會定期添加新區域。 默認情況下,每個AWS賬戶均啟用“舊”區域,而默認情況下則禁用新區域1 。
我正在嘗試使用以下Python(偽)代碼掃描所有可用區域中的特定資源:
regions = boto3_session.get_available_regions('rds')
for region in regions:
boto_rds_client = boto3_session.client('rds', region_name=region)
r_paginator = boto_rds_client.get_paginator('describe_db_instances')
for rdses in r_paginator.paginate():
for rds in rdses['DBInstances']:
do_stuff(rds)
但是,此操作失敗,並帶有神秘含義An error occurred (InvalidClientTokenId) when calling the DescribeDBInstances operation: The security token included in the request is invalid
訪問“新”區域時An error occurred (InvalidClientTokenId) when calling the DescribeDBInstances operation: The security token included in the request is invalid
。
其他服務因其他錯誤而失敗:例如,Lambda失敗,因An error occurred (UnrecognizedClientException) when calling the ListFunctions operation: The security token included in the request is invalid
如何確定區域是否啟用? 似乎沒有API調用來執行此操作...
我發現該API的一種極端情況是可以(濫用)來標識啟用的區域:ec2:DescribeRegions API調用(可能還嘗試了其他方法)在禁用區域中表現出略有不同的故障模式:
呼叫成功,或者您知道該區域已啟用
呼叫失敗,並顯示UnauthorizedOperation
錯誤。 這表明您沒有IAM權限,但是已啟用該區域
調用失敗,並顯示AuthFailure
。 這表明該地區已被禁用
以下代碼成功過濾了我的測試案例中的區域:
def get_enabled_regions(boto3_session: boto3.Session, service: str) -> typing.Set[str]:
regions = boto3_session.get_available_regions(service)
enabled_regions = set()
for region in regions:
ec2_client = boto3_session.client('ec2', region_name=region)
try:
ec2_client.describe_regions()
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "AuthFailure":
print(f"region {region} seems disabled, skipping")
continue # Account is disabled
elif e.response['Error']['Code'] == "UnauthorizedOperation":
print(f"region {region} seems enabled (but not sure)")
pass # Access denied is good: we have access to the region, just not to the ec2:DescribeRegions call
else:
raise
enabled_regions.add(region)
return enabled_regions
我在這個問題上做了更多的工作,發現了一種較少依賴邊緣情況的方式:使用sts:GetCallerIdentity
調用。
與ec2:DescribeRegions
相比,它具有多個優點,因為該API始終處於啟用狀態(不受IAM限制)。 您可以為某個區域禁用STS,但是即使那樣,GetCallerIdentity仍然可以工作(僅禁用發出臨時憑據1 )。
def get_enabled_regions(boto3_session: boto3.Session, service: str) -> typing.Set[str]:
regions = boto3_session.get_available_regions(service)
enabled_regions = set()
for region in regions:
sts_client = boto3_session.client('sts', region_name=region)
try:
sts_client.get_caller_identity()
enabled_regions.add(region)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "InvalidClientTokenId":
# error code received when region is disabled
print(f"region {region} is disabled")
pass
else:
raise
return enabled_regions
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.