问题描述
在将变量复制到文件时遇到问题。
我运行多个命令和set_fact。然后,我尝试将信息复制到一个csv文件中。
示例:
---
- name: Get Tunnel1 ip
ios_command:
commands:
- show run int tunnel 1 | in ip add
register: results_tunnel1
- set_fact:
tunnel1: "{{ results_tunnel1.stdout[0].split(' ') }}"
- name: Get Tunnel2 ip
ios_command:
commands:
- show run int tunnel 2 | in ip add
register: results_tunnel2
- set_fact:
tunnel2: "{{ results_tunnel2.stdout[0].split(' ') }}"
- name: Get Tunnel3 ip
ios_command:
commands:
- show run int tunnel 3 | in ip add
register: results_tunnel3
- set_fact:
tunnel3: "{{ results_tunnel3.stdout[0].split(' ') }}"
- name: save output to file per host
copy: content="{{ inventory_hostname }};{{ tunnel1[2] }};{{ tunnel2[2] }};{{ tunnel3[2] }}" dest="//home/output/ip_info.csv"
在测试机上,我使用的其中一个不会输出要保存的IP地址,因此变量显示为“”
当它尝试输出信息时,出现错误:
"msg": "The task includes an option with an undefined variable. The error was: list object has no element
我猜我需要告诉它什么都不打印或说是否为空保存为“空”
只是不确定我将如何实现。
解决方法
您可以使用Jinja的default
过滤器来处理未定义的变量。
给出剧本:
- hosts: all
gather_facts: no
tasks:
- debug:
msg: "{{ inventory_hostname }};{{ tunnel1[2] | default('') }};{{ tunnel2[2] | default('') }};{{ tunnel3[2] | default('') }}"
这将产生结果:
PLAY [all] ********************************************************************************************************
TASK [debug] ******************************************************************************************************
ok: [localhost] => {
"msg": "localhost;;;"
}
PLAY RECAP ********************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
虽然我们设置了一些值:
- hosts: all
gather_facts: no
tasks:
- debug:
msg: "{{ inventory_hostname }};{{ tunnel1[2] | default('') }};{{ tunnel2[2] | default('') }};{{ tunnel3[2] | default('') }}"
vars:
tunnel1:
- foo
- bar
- baz
tunnel2:
- brown
- fox
- jumps
tunnel3:
- over
- lazy
- dog
它产生了回顾:
PLAY [all] ********************************************************************************************************
TASK [debug] ******************************************************************************************************
ok: [localhost] => {
"msg": "localhost;baz;jumps;dog"
}
PLAY RECAP ********************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0