0

我尝试使用 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阅读文档我没有看到 'Name' 和 'CustomJson' 之间的区别,除了 CustomJson 是一个 JSON 对象。我必须改造它吗?

提前谢谢

4

2 回答 2

1

KeyError偶尔会收到一个,因为CustomStack响应中的元素是可选的。如果为堆栈指定了自定义堆栈,它将被返回。否则,CustomStack钥匙根本不存在。您应该执行以下操作:

if 'CustomStack' in stack:
    # do your thing
于 2015-10-08T15:35:47.197 回答
0

与我公司的一位开发人员进行了快速交谈。获得了一些基本介绍,以便在编码和 python 等方面变得更好(必须放松我的一些管理思维)。

不要迭代 max_elements,最好在“stack in stacks”之上迭代。

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。

于 2015-10-08T10:41:58.783 回答