[英]Missing variable in jinja2, no output with Ansible
我有一个 Ansible playbook,它从 Cisco 交换机收集事实。
---
- hosts: switches
gather_facts: False
connection: network_cli
vars:
backup_root: ./configs
cli:
host: "{{ inventory_hostname }}"
tasks:
- name: ensure device folder is created
file:
path: "{{ backup_root }}/{{ inventory_hostname }}"
state: directory
- name: Gather all facts
cisco.ios.ios_facts:
gather_subset: all
- name: Serial Number
debug: var=ansible_net_serialnum
- name: Model
debug: var=ansible_net_model
- name: Hostname
debug: var=ansible_net_hostname
- name: Version
debug: var=ansible_net_version
- name: CDP
debug: var=ansible_net_neighbors
- name: Config file
debug: var=ansible_net_config
- name: Stack SW Model Numbs
debug: var=ansible_net_stacked_models
- name: Stack SW Model Numbs
debug: var=ansible_net_stacked_serialnums
- name: Get VLAN Info
cisco.ios.ios_command:
commands: show vlan brief
register: show_vlan
- name: get timestamp
command: date +%Y%m%d
register: timestamp
- name: Generate configuration files
template:
src=roles/discovery/templates/ios_switches.j2
dest="{{ backup_root }}/{{ inventory_hostname }}/{{ inventory_hostname }}.txt" `
这是 jinja 文件。
Hostname: {{ ansible_net_hostname }}
Model: {{ansible_net_model}}
Serial Number: {{ansible_net_serialnum}}
IOS Version: {{ansible_net_version}}
IOS Image: {{ansible_net_image}}
Switch Stack Models:
{{ansible_net_stacked_models | to_nice_yaml(indent=2)}}
Switch Stack Serials:
{{ansible_net_stacked_serialnums | to_nice_yaml(indent=2)}}
CDP Neighbors:
{{ansible_net_neighbors | to_nice_yaml(indent=2)}}
Configuration:
{{ansible_net_config}}
VLAN:
{{show_vlan.stdout[0] | to_nice_yaml(indent=2)}}
这一切正常,直到它遇到无法堆叠的交换机(例如机箱或 VSS)。 当我运行剧本时,我得到以下信息-
msg: 'AnsibleUndefinedVariable: ''ansible_net_stacked_models'' is undefined
我试过在 Jinja2 中使用if
,如下所示
...
Switch Stack Models:
{% if ansible_net_stacked_models is not defined %}
NOT A STACKABLE SWITCH
{% else %}
{{ansible_net_stacked_models | to_nice_yaml(indent=2)}}
{% endif %}
但是它在 Jinja 渲染中失败并且不产生任何输出。
有没有办法忽略 jinja 中缺失的变量,或者有更好的方法来做到这一点?
如果未定义,您可以为变量设置默认值
{{ ansible_net_stacked_models|default("NOT A STACKABLE SWITCH", true) | to_nice_yaml(indent=2) }}
来发现错误是阻止 Ansible 甚至调用 jinja 文件。 我又挖了一些,发现我可以将变量设置为库存中的默认值。
[switch:vars]
ansible_net_stacked_models='NOT A STACKABLE SWITCH'
在运行 playbook 时,如果设备具有有效信息,它将覆盖我们在清单中定义的默认变量。 如果设备没有有效信息,Ansible 将简单地将我们在清单中设置的默认变量传递给 jinja2。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.