如何使用 Ansible jinja2 if else 语句获得所需的输出
How to get desired output using Ansible jinja2 if else statement
下面是任务:
- name: primary slot on active
debug: msg={{slotid.stdout_lines}}
register: slotidoutput
输出1:
TASK [primary slot on active] *************************************************************************
ok: [1.1.1.1] => {
"msg": [
[
"Primary Slot ID 1"
]
]
}
有些设备没有主插槽 ID,因此此时输出将类似于:
输出2:
TASK [primary slot on active] ***********************************************************************
ok: [2.2.2.2] => {
"msg": []
}
所以我正在制作 jinja2 模板
{% if 'Primary Slot ID' in slotidoutput %}
{{slotidoutput.msg[0][0]}}
{% else %}
Single Slot
{% endif %}
即使我 运行 在具有输出 1
的多槽设备上,我也总是获得“单槽”的价值
Single Slot
设备 1.1.1.1 的所需打印值为:
Primary Slot ID 1
设备 2.2.2.2 的所需打印值为:
Single Slot
我确定我在 jinja if else 语句中犯了一些错误。有人可以检查一下并告诉我吗?
要使模板正常工作,我们需要解决的条件很少。
- 有时
slotid.stdout_lines
是嵌套列表
- 在某些情况下它是一个空列表
[]
- 使用
in
的条件检查将对列表项执行精确匹配,并对字符串执行搜索匹配
此外,调试输出中的 register
似乎没有必要,因为它拥有与 slotid.stdout_lines
.
相同的数据结构
所以下面的任务和模板应该解决上述问题:
任务:
# Flatten nested list to single level
- set_fact:
slotidout: "{{ slotid.stdout_lines|flatten }}"
# Using random name for template
- template:
src: testtemplate.j2
dest: /tmp/testtemplate
模板testtemplate.j2
:
{% if slotidout[0] is defined %}
{% if "Primary" in slotidout[0] %}
{{ slotidout[0] }}
{% endif %}
{% else %}
Single slot
{% endif %}
这应该根据条件创建具有适当值的文件。您可以根据您的要求调整条件。
下面是任务:
- name: primary slot on active
debug: msg={{slotid.stdout_lines}}
register: slotidoutput
输出1:
TASK [primary slot on active] *************************************************************************
ok: [1.1.1.1] => {
"msg": [
[
"Primary Slot ID 1"
]
]
}
有些设备没有主插槽 ID,因此此时输出将类似于:
输出2:
TASK [primary slot on active] ***********************************************************************
ok: [2.2.2.2] => {
"msg": []
}
所以我正在制作 jinja2 模板
{% if 'Primary Slot ID' in slotidoutput %}
{{slotidoutput.msg[0][0]}}
{% else %}
Single Slot
{% endif %}
即使我 运行 在具有输出 1
的多槽设备上,我也总是获得“单槽”的价值Single Slot
设备 1.1.1.1 的所需打印值为:
Primary Slot ID 1
设备 2.2.2.2 的所需打印值为:
Single Slot
我确定我在 jinja if else 语句中犯了一些错误。有人可以检查一下并告诉我吗?
要使模板正常工作,我们需要解决的条件很少。
- 有时
slotid.stdout_lines
是嵌套列表 - 在某些情况下它是一个空列表
[]
- 使用
in
的条件检查将对列表项执行精确匹配,并对字符串执行搜索匹配
此外,调试输出中的 register
似乎没有必要,因为它拥有与 slotid.stdout_lines
.
所以下面的任务和模板应该解决上述问题:
任务:
# Flatten nested list to single level
- set_fact:
slotidout: "{{ slotid.stdout_lines|flatten }}"
# Using random name for template
- template:
src: testtemplate.j2
dest: /tmp/testtemplate
模板testtemplate.j2
:
{% if slotidout[0] is defined %}
{% if "Primary" in slotidout[0] %}
{{ slotidout[0] }}
{% endif %}
{% else %}
Single slot
{% endif %}
这应该根据条件创建具有适当值的文件。您可以根据您的要求调整条件。