从yaml获取列表并将其解析为jinja2并将其输出到yaml中

时间:2018-12-26 22:07:12

标签: string list yaml jinja2

花了大约4个小时在这里搜寻,试图找到相关的东西。我知道这里的解决方案将替代“ | list | join('\',\'')“,但是就我的生活而言,找不到类似的手册页。即使是指向更好的手册页的指针,也将不胜感激。 我想要的输出是:  vlans:[“ 1”,“ 3”,“ 5”,“ 7”,“ 9”,“ 17”]

我有一个很大的YAML文件,其中包含一个值得主机列表的位置的属性/变量。我首先尝试使用JINJA2将文件拆分为许多主机特定的文件。当为vlans变量运行时,我得到:       vlan:“ 1”,“ 3”,“ 5”,“ 7”,“ 9”,“ 17”
因此,整个vlans变量被视为单个字符串,而不是字符串列表。如果我从JINJA2代码中删除“ | list | join('\',\'')”,那么我的目标YAML文件中将得到以下输出:       vlans:“ [u'1',u'3',u'5',u'7',u'9',u'17']”

我在join语句上尝试了多种变体,似乎无法达到正确的目标。非常感谢您的帮助。

结构如下:

mg_uplinks:

  - { left_border_node: somehostname, left_border_intf: someinterface, 
      right_border_node: somehostname, right_border_intf: someinterface, 
      border_ae_intf: someinterface, border_esi: "some value", border_lacp_sys_id: "some value",
      mg_node: somehostname, left_mg_intf: someinterface, right_mg_intf: someinterface, mg_ae_intf: someinterface,
      link_speed: 10g,
      vlans: ["1", "3", "5", "7", "9", "17"]
      
  - { left_border_node: someotherhostname, left_border_intf: someinterface, 
      right_border_node: someotherhostname, right_border_intf: someinterface, 
      border_ae_intf: someinterface, border_esi: "some value", border_lacp_sys_id: "some value",
      mg_node: someotherhostname, left_mg_intf: someinterface, right_mg_intf: someinterface, mg_ae_intf: someinterface,
      link_speed: 10g,
      vlans: [all]      }
  

然后我将使用此jinja2代码解析此信息。

mg_uplinks:
{% for link in mg_uplinks %}
{% if inventory_hostname == link['left_border_node'] %}
  - { local_phys_intf: "{{ link['left_border_intf'] }}", 
      border_ae_intf: "{{ link['border_ae_intf'] }}", 
      border_esi: "{{ link['border_esi'] }}", 
      border_lacp_sys_id: "{{ link['border_lacp_sys_id'] }}", 
      mg_node: "{{ link['mg_node'] }}", 
      remote_phys_intf: "{{ link['left_mg_intf'] }}", 
      remote_ae_intf: "{{ link['mg_ae_intf'] }}", 
      link_speed: "{{ link['link_speed'] }}",
      vlans: "{{ link['vlans'] | list | join ('\',\'') }}"  }

{% endif %}
{% if inventory_hostname == link['right_border_node'] %}
  - { local_phys_intf: "{{ link['right_border_intf'] }}",
      border_ae_intf: "{{ link['border_ae_intf'] }}",
      border_esi: "{{ link['border_esi'] }}",
      border_lacp_sys_id: "{{ link['border_lacp_sys_id'] }}",
      mg_node: "{{ link['mg_node'] }}",
      remote_phys_intf: "{{ link['right_mg_intf'] }}",
      remote_ae_intf: "{{ link['mg_ae_intf'] }}",
      link_speed: "{{ link['link_speed'] }}", 
      vlans: "{{ link['vlans'] | list | join ('\',\'') }}"  }

{% endif %}
{% endfor %}

1 个答案:

答案 0 :(得分:0)

找到了它,并认为我会发布答案。不需要[''],我想要的过滤器是| to_yaml。

  intf_vlans: {{ intf.intf_vlans | to_yaml }},