2017-02-21 14 views
0

我想列出所有EC2標籤。在其他AWS賬戶上可以使用,但在另一個賬戶上則不適用。嘗試使用Python列出EC2標籤,但獲取錯誤:「errorMessage」:「'NoneType'對象不可迭代」

import boto3 

def lambda_handler(event, context): 


ec2 = boto3.resource('ec2', region_name='eu-west-1') 
ec2_list = ec2.instances.all() 

for instance in ec2_list: 
    for tag in instance.tags: 
     print tag 

我得到以下錯誤:

{ 
"stackTrace": [ 
[ 
    "/var/task/lambda_function.py", 
    10, 
    "lambda_handler", 
    "for tag in instance.tags:" 
] 
], 
"errorType": "TypeError", 
"errorMessage": "'NoneType' object is not iterable" 
} 

有點困惑如何解決這個因爲一切都處於同樣的方式設置,因爲它是另一個帳戶。任何幫助,將不勝感激。

+1

看起來'instance.tags'是'None'。其中一個實例是否可能沒有標籤? –

回答

0

這是行不通的嗎?你應該檢查實例是否有任何標籤。

import boto3 

def lambda_handler(event, context): 
    ec2 = boto3.resource('ec2', region_name='eu-west-1') 
    ec2_list = ec2.instances.all() 

    for instance in ec2_list: 
     if instance.tags: 
      for tag in instance.tags: 
       print tag 
     else: 
      print "no tags" 
+0

工作!非常感謝!有一個沒有任何標籤的實例。 – JBgorilla

相關問題