2016-08-11 57 views
1

我想使用boto3檢索標籤,但我經常遇到ListIndex超出範圍錯誤。使用boto3檢索RDS標籤會產生索引錯誤。

我的代碼:

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 i in range(0,10): 
    print rdstags['TagList'][i]['Key'] 

任何幫助表示讚賞。謝謝!

回答

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 "......"