使用boto3检索RDS标记会产生索引错误。

时间:2016-08-11 20:01:48

标签: 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: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

我也尝试通过指定范围来使用for循环,它似乎也没有用。

for i in range(0,10):
   print rdstags['TagList'][i]['Key']

感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

您应首先迭代标记列表,然后将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 "......"

答案 1 :(得分:0)

我使用功能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