Python 使用boto3检索RDS标记时出现索引错误。

Python 使用boto3检索RDS标记时出现索引错误。,python,amazon-web-services,boto3,aws-rds,Python,Amazon Web Services,Boto3,Aws Rds,我试图使用boto3检索标签,但我经常遇到ListIndex超出范围错误 我的代码: rds = boto3.client('rds',region_name='us-east-1') rdsinstances = rds.describe_db_instances() for rdsins in rdsinstances['DBInstances']: rdsname = rdsins['DBInstanceIdentifier'] arn = "arn:aws

我试图使用boto3检索标签,但我经常遇到ListIndex超出范围错误

我的代码:

rds = boto3.client('rds',region_name='us-east-1')
rdsinstances = rds.describe_db_instances()
for rdsins in rdsinstances['DBInstances']:
        rdsname = rdsins['DBInstanceIdentifier']
        arn = "arn:aws:rds:%s:%s:db:%s"%(reg,account_id,rdsname)
        rdstags = rds.list_tags_for_resource(ResourceName=arn)            
        if 'MyTag' in rdstags['TagList'][0]['Key']:
            print "Tags exist and the value is:%s"%rdstags['TagList'][0]['Value']
我的错误是:

Traceback (most recent call last):
  File "rdstags.py", line 49, in <module>
    if 'MyTag' in rdstags['TagList'][0]['Key']:
IndexError: list index out of range

感谢您的帮助。谢谢

您应该首先迭代标记列表,并将
MyTag
与每个项目分别进行比较: 诸如此类:

 if 'MyTag' in [tag['Key'] for tag in rdstags['TagList']]:
     print "Tags exist and.........."
或者更好:

for tag in rdstags['TagList']:
    if tag['Key'] == 'MyTag':
        print "......"

我使用函数have_tag在Boto3的所有模块中查找标记

client = boto3.client('rds')
instances = client.describe_db_instances()['DBInstances']
if instances:
    for i in instances:
        arn = i['DBInstanceArn']
        # arn:aws:rds:ap-southeast-1::db:mydbrafalmarguzewicz
        tags = client.list_tags_for_resource(ResourceName=arn)['TagList']
        print(have_tag('MyTag'))
        print(tags)
功能搜索标签:

def have_tag(self, dictionary: dict, tag_key: str):
    """Search tag key
    """
    tags = (tag_key.capitalize(), tag_key.lower())
    if dictionary is not None:
        dict_with_owner_key = [tag for tag in dictionary if tag["Key"] in tags]
        if dict_with_owner_key:
            return dict_with_owner_key[0]['Value']
    return None

或者更好:
[tag['Value']用于标记['TagList']中的标记,如果标记['Key']=='MyKey][0]
def have_tag(self, dictionary: dict, tag_key: str):
    """Search tag key
    """
    tags = (tag_key.capitalize(), tag_key.lower())
    if dictionary is not None:
        dict_with_owner_key = [tag for tag in dictionary if tag["Key"] in tags]
        if dict_with_owner_key:
            return dict_with_owner_key[0]['Value']
    return None