Search code examples
pythonjinja2salt-projectordereddictionary

Parsing/extracting from OrderedDict using Jinja in Salt


I am running into a rather weird issue while parsing results of a salt command. The command I am running is

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

And output looks below:

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

Now my understanding is when I do items() on above result with a line below, it should work

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

But the moment I use items() in above line I start running into an error:

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

I tried a couple of other ways (Doing items().items() or storing result in a variable and then running for loop over) to get the list out of OrderedDict but none of ways seem to help.


Solution

  • Either I don't know Python enough or there is something weird going on. Simply adding a check has made the above work. So working block looks like (Partial code of course):

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

    My understanding is if check was only meant for checking just in case hostname is empty. But looks like even if there is data - an if check is needed. Still curious to know the mystery!