我尝试使用python和boto3从我的OpsWorks堆栈中获取自定义json。获取名称是好的,但如果我想获得CustomJson - KeyError。不知道为什么。
import boto3
import traceback
client = boto3.client('opsworks')
response = client.describe_stacks()
max_elements = len(response['Stacks'])
for i in range(max_elements):
stack_Name = response['Stacks'][i]['Name'] # works
try:
stack_CustomJson = response['Stacks'][i]['CustomJson'] # KeyError
except:
traceback.print_exc()
这是控制台输出:
$ python3 get_custom_json.py
Traceback (most recent call last):
File "get_custom_json.py", line 27, in get_opsworks_details
stack_CustomJson = response['Stacks'][i]['CustomJson']
KeyError: 'CustomJson'
从http://boto3.readthedocs.org/en/latest/reference/services/opsworks.html#OpsWorks.Client.describe_stacks阅读文档我没有看到“姓名”与“#39;”之间的区别。和' CustomJson'除了CustomJson是一个JSON对象。我必须改造吗?
提前谢谢
答案 0 :(得分:1)
您偶尔会收到ref
因为响应中的KeyError
元素是可选的。如果为堆栈指定了自定义堆栈,则会返回该堆栈。否则,CustomStack
密钥将根本不存在。你应该做点什么:
CustomStack
答案 1 :(得分:0)
与我公司的开发人员进行了快速聊天。得到了一些基本的介绍,以便在编码和python等方面做得更好(必须放松我的一些管理员思想)。
不要对max_elements进行迭代,最好在堆栈中重复堆叠'。
for stack in response['Stacks']:
print(stack['CustomJson'])
现在它可以工作 - 我将从OpsWorks堆栈中获取自定义json。但仍有KeyError。
Traceback (most recent call last):
File "get_custom_json.py", line 22, in <module>
get_opsworks_details()
File "get_custom_json.py", line 18, in get_opsworks_details
print(stack['CustomJson'])
KeyError: 'CustomJson'
我会检查是否可以再次找他,看看为什么会发生这种情况。
[编辑]盲点 - 如果堆栈没有自定义json,则会发生KeyError。