描述跨 AWS 区域的 RDS 快照

Describe RDS Snapshots across AWS Regions

我正在尝试获取快照并在区域字典中描述来自 db_instances 的快照:

regions = {'us-east-1':'us-east-2', 'us-west-1':'us-west-2'}

区域中的数据库实例:

us-east-1 = testeast1
us-west-1 = testwest1

使用此函数调用数据库实例,我可以 return 该区域中的所有数据库实例:

def rds_instances():
   inst = []
   for rg in regions.key():
      res = boto3.client('rds', region_name=rg) 
      srcs = res.describe_db_instances()
      for src in srcs['DBInstances']: 
         if src['DBInstanceStatus']  == 'available': 
            rds_db = src['DBInstanceIdentifier']
            inst.append(rds_db)
   return inst

从区域获取快照:

def get_kms(): 
   snapshots = []
   for rg in regions:
      src = boto3.client('rds', region_name=rg) 
      instances = rds_instances()
      for instance in instances: 
         src_rds = src.describe_db_instances(DBInstanceIdentifier=instance) 
         if src_rds['DBInstances'][0]['DBInstanceStatus']  == 'available': 
            src_snap = src.describe_db_snapshots(DBInstanceIdentifier=instance, SnapshotType='automated')['DBSnapshots'] 
            for snap in src_snap:
               kms_id = snap['KmsKeyId']
               snapshots.append(kms_id)
   return snapshots 

问题:当我尝试从每个区域获取 rds 快照时,我 运行 遇到了一个问题,它会查找 rds 实例并检查 rds 实例在错误的区域然后 return 出现错误:

DBInstanceNotFoundFault: An error occurred (DBInstanceNotFound) when calling the DescribeDBInstances operation: DBInstance testwest1 not found.

如果rds实例不在该地区,如何修改代码通过,避免报错??

我在 运行 describe kms key command 时也遇到同样的错误。同样的错误 运行 将此命令用于目标区域:

   for region in regions:
      kms_client = boto3.client('kms', region_name=region)
      keys = kms_client.describe_key(KeyId=alias_name)

解决方案 我通过使用一个简单的 try/except 来捕获错误并通过,从而解决了这个问题。应该早点考虑这个!

      for instance in instances: 
         try:
            src_rds = src.describe_db_instances(DBInstanceIdentifier=instance) 
         except ClientError:
            pass

我通过使用一个简单的 try/except 来捕获错误并通过。

解决了这个问题。
      for instance in instances: 
         try:
            src_rds = src.describe_db_instances(DBInstanceIdentifier=instance) 
         except ClientError:
            pass