Ansible Jinja模板检查多个值是否未定义,然后使用默认值(omit)。

huangapple go评论82阅读模式
英文:

Ansible Jinja templating check if multiple values are undefined before using default(omit)

问题

我有这个代码块

url_username: "{{ download.username | default(omit) }}"


我想要说如果 `download.username` 没有定义,那就看看 `offline_download` 是否定义。如果两者都没有定义,那么使用 default(omit)。类似这样

url_username: "{{ download.username | offline_download | default(omit) }}"

显然,我上面的语法在使用管道时是错误的。那么正确的做法是什么呢?

基本上在使用 default(omit) 之前检查多个值是否已定义。
英文:

I have this block

url_username: "{{ download.username | default(omit) }}"

I want to say if download.username is not defined, see if offline_download is defined. If both are not defined then use default(omit). Something like

url_username: "{{ download.username | offline_download | default(omit) }}"

Obviously my syntax above is wrong while pipe'ing. So what is the right way to do?

Basically check if multiple values are defined before doing the default(omit)

答案1

得分: 2

你可以递归使用 [*默认*](https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.default)

```yaml
url_username: "{{ username | d(offline | d(omit)) }}"

<hr>

<sup>

测试的完整playbook示例

shell&gt; cat pb.yml
- hosts: localhost

  vars:

    url_username: &quot;{{ username | d(offline | d(omit)) }}&quot;

  tasks:

    - debug:
        var: url_username

给出(缩略)

shell&gt; ansible-playbook -e username=value_of_username pb.yml

  url_username: value_of_username
shell&gt; ansible-playbook -e offline=value_of_offline pb.yml

  url_username: value_of_offline
shell&gt; ansible-playbook pb.yml

  url_username: __omit_place_holder__eb8bf53eb654413fef765058f68f455d9e0a191e

</sup>


<details>
<summary>英文:</summary>

You can use [*default*](https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.default) recursively

```yaml
url_username: &quot;{{ username | d(offline | d(omit)) }}&quot;

<hr>

<sup>

Example of a complete playbook for testing

shell&gt; cat pb.yml
- hosts: localhost

  vars:

    url_username: &quot;{{ username | d(offline | d(omit)) }}&quot;

  tasks:

    - debug:
        var: url_username

gives (abridged)

shell&gt; ansible-playbook -e username=value_of_username pb.yml

  url_username: value_of_username
shell&gt; ansible-playbook -e offline=value_of_offline pb.yml

  url_username: value_of_offline
shell&gt; ansible-playbook pb.yml

  url_username: __omit_place_holder__eb8bf53eb654413fef765058f68f455d9e0a191e

</sup>

huangapple
  • 本文由 发表于 2023年7月7日 07:28:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76633080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定