UPDATE:博托實例.__字典__ [ '標籤'] [ '名稱']輸出問題
我做了什麼,是下面的建議,不過,我仍然得到一個KeyError異常: '名稱'在輸出中,即使輸出是正確的。
這是輸出:
us-west-1 EC2Connection:
ec2.us-west-1.amazonaws.com
Showing all of your current instances
Proxy-44-1000-Enrollments
Proxy-45-1000-Enrollments
Proxy-48-1000-Enrollments
Proxy-49-1000-Enrollments
Proxy-59-1000-Enrollments
Proxy-67-1000-Enrollments
Traceback (most recent call last): File "/Users/xxxxx/xxxx/boto/instanceid.py",
line 43, in <module> print "\t%s" % (instance.tags['Name']) if instance.state ==
'running' else instance.state KeyError: 'Name'
最初的問題:
我試圖從他們的 「名稱」 標籤沿傾倒出的實例ID的列表AWS使用boto。我在網上找到了一個可以附加到實例對象的方法,名爲__dict__
,這似乎工作正常,但是,我只想在使用此方法時拉出「name」標記,但我一直收到錯誤「Key Error : '名稱' 「
基本上,此代碼的工作:
# Creating connection object to EC2
conn = boto.connect_ec2()
regions = boto.ec2.regions()
# the 5 element in the array is "us-west-1" and setting the object to connect
us = regions[5]
print us.name
conn_us = us.connect()
print conn_us
filters = {'key-name' : 'misc-key'}
all_inst = conn_us.get_all_instances(filters=filters)
print "Showing all of your current instances"
for res in all_inst:
# each reservation have a instance:
for instance in res.instances:
print "\t%s: \t%s" % (instance.id, instance.__dict__['tags'])
輸出是hoky壽:
us-west-1
EC2Connection:ec2.us-west-1.amazonaws.com
Showing all of your current instances
i-xxxxxxxx: {u'Name': u'Proxy-xx-1000-Enrollments'}
i-xxxxxxxx: {u'Name': u'Proxy-xx-1000-Enrollments'}
i-xxxxxxxx: {u'Name': u'Proxy-xx-1000-Enrollments'}
i-xxxxxxxx: {u'Name': u'Proxy-xx-1000-Enrollments'}
i-xxxxxxxx: {u'Name': u'Proxy-xx-1000-Enrollments'}
當我做出改變的__dict__
方法來 」拉「 出」名稱「,它工作(或似乎工作,但拋出錯誤:
下面是代碼的變化:
print "\t%s: \t%s" % (instance.id, instance.__dict__['tags']['Name'])
這裏是輸出:
us-west-1
EC2Connection:ec2.us-west-1.amazonaws.com
Showing all of your current instances
i-xxxxxxxx: Proxy-xx-1000-Enrollments
i-xxxxxxxx: Proxy-xx-1000-Enrollments
i-xxxxxxxx: Proxy-xx-1000-Enrollments
i-xxxxxxxx: Proxy-xx-1000-Enrollments
i-xxxxxxxx: Proxy-xx-1000-Enrollments
i-xxxxxxxx: Proxy-xx-1000-Enrollments
Traceback (most recent call last):
File "/Users/xxxxxx/xxx.xxx/boto/instanceid.py", line 43, in <module>
print "\t%s: \t%s" % (instance.id, instance.__dict__['tags']["Name"])
KeyError: 'Name'
我喜歡這個輸出,WITHOUT錯誤 - 誰能告訴我,我做錯了什麼這裏?
謝謝
感謝您的回答,真的很感激它。然而,當我使用你的語法時,我仍然在運行更新代碼時得到「KeyError」: – 2012-01-31 20:04:37
'us-west-1 EC2Connection:ec2.us-west-1.amazonaws.com 顯示所有當前實例 \t代理44-1000-許可登記 \t代理45-1000-許可登記 \t代理48-1000-許可登記 \t代理49-1000-許可登記 \t代理59-1000-許可登記 \t的Proxy- 67-1000-Enrollments \t Proxy-70-1000-Enrollments \t Proxy-71-1000-Enrollments \t Proxy-73-1000-Enrollments Traceback(最近一次調用最後一次): 文件「/Users/xxxxx/xxxx/boto/instanceid.py」,第43行,在中 print「\ t%s」%(instance .tags ['Name'])if instance.state =='running'else instance.state KeyError:'Name'' –
2012-01-31 20:05:02