4

我正在尝试使用 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']

任何帮助表示赞赏。谢谢!

4

2 回答 2

1

您应该首先遍历标签列表并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 "......"
于 2016-08-11T21:16:11.350 回答
1

我使用函数 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
于 2018-09-26T11:54:47.817 回答