jinja2中缺少变量,Ansible没有输出
我有一本Ansible的剧本,它收集了思科交换机的事实jinja2中缺少变量,Ansible没有输出,ansible,jinja2,Ansible,Jinja2,我有一本Ansible的剧本,它收集了思科交换机的事实 --- - hosts: switches gather_facts: False connection: network_cli vars: backup_root: ./configs cli: host: "{{ inventory_hostname }}" tasks: - name: ensure device folder is created
---
- 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\u net\u stacked\u models'未定义
我试过在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只需将我们在inventory中设置的默认变量传递给jinja2