任何人都可以解释 Ansible 中的以下 Jinja 行为吗?
以下代码有效:任务被跳过,因为 job_function 不在 Exclusion_functions 数组中
- name: Lowercase test
hosts: localhost
gather_facts: false
vars:
job_function: 'VRIJwillig'
exclusion_functions:
- vrijwilliger
- maatje
tasks:
- name: Test for function in exclusions
debug:
msg: In exclusions
when: (job_function | lower) in exclusion_functions
下面的代码也可以工作,第二个任务被跳过。
- name: Lowercase test
hosts: localhost
gather_facts: false
vars:
job_function: 'VRIJwillig'
exclusion_functions:
- Vrijwilliger
- Maatje
tasks:
- name: Initialiseer variabelen
set_fact:
exclusions: "{{ exclusion_functions | lower }}"
- name: Test for function in exclusions
debug:
msg: In exclusions
when: (job_function | lower) in exclusions
但这不起作用,任务不会被跳过:
---
- name: Lowercase test
hosts: localhost
gather_facts: false
vars:
job_function: 'VRIJwillig'
exclusion_functions:
- Vrijwilliger
- Maatje
tasks:
- name: Test for function in exclusions
debug:
msg: In exclusions
when: (job_function | lower) in (exclusion_functions | lower)
为什么最后一个代码片段中没有跳过任务?
job_function | lower
是 vrijwillig
,exclusion_functions | lower
是 ['vrijwilliger','maatje']
,第一个不在第二个中。
我无法回答
问:“任何人都可以解释 Ansible 中的以下 Jinja 行为吗?”
为了在列表中搜索(子)字符串我建议使用以下最小示例剧本中的方法
---
- name: Lowercase test
hosts: localhost
become: false
gather_facts: false
vars:
job_function: 'VRIJwillig'
exclusion_functions:
- Vrijwilliger
- Maatje
tasks:
- name: Initialiseer variabelen
debug:
var: exclusion_functions | lower
- name: Test for function in exclusions
debug:
msg: In exclusions
when: exclusions is search(job_function | lower)
# Initialiseer variabelen
vars:
exclusions: "{{ exclusion_functions | lower }}"
产生
的输出TASK [Initialiseer variabelen] *******************************************************
ok: [localhost] =>
exclusion_functions | lower:
- vrijwilliger
- maatje
TASK [Test for function in exclusions] *******************************************************
ok: [localhost] =>
msg: In exclusions
contains
测试 – 列表是否包含此元素。
- name: Test for function in exclusions
debug:
msg: In exclusions
when: exclusions is contains(job_function | lower)
# Initialiseer variabelen
vars:
exclusions: "{{ exclusion_functions | lower }}"
导致任务被跳过。
PLAY RECAP *****************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1