Parsing/extracting 来自 OrderedDict 在 Salt 中使用 Jinja

Parsing/extracting from OrderedDict using Jinja in Salt

我在解析 salt 命令的结果时 运行 遇到了一个相当奇怪的问题。我是运行的命令是

{% set hostname = salt['publish.publish']('roles:*{}*'.format(role), 'grains.item', 'fqdn', 'grain') %}

输出如下:

OrderedDict([('1.server.com', OrderedDict([('fqdn', '1.server.com')])), ('0.server.com', OrderedDict([('fqdn', '0.server.com')]))])

现在我的理解是,当我对上面的结果执行 items() 并在下面添加一行时,它应该可以工作

{% for hostname, fqdn in salt['publish.publish']('roles:*{}*'.format(role), 'grains.item', 'fqdn', 'grain').items() %}

但是当我在上面的行中使用 items() 时,我开始 运行 出错:

failed: Jinja variable 'None' has no attribute 'items'

我尝试了其他几种方法(执行 items().items() 或将结果存储在变量中,然后 运行 进行循环)从 OrderedDict 中获取列表,但是none 的方法似乎有所帮助。

要么我对 Python 了解不够,要么发生了一些奇怪的事情。只需添加一个支票即可完成上述工作。所以工作块看起来像(当然是部分代码):

{% set hostname = salt['publish.publish']('roles:*{}*'.format(role), 'grains.item', 'fqdn', 'grain') %}
{% if hostname is not none %}
{% for host, site in hostname.items() %}

我的理解是 if 检查只是为了检查以防万一 hostname 为空。但看起来即使有数据 - 是否需要检查。还是好奇想知道其中的奥秘!