英文:
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> cat pb.yml
- hosts: localhost
vars:
url_username: "{{ username | d(offline | d(omit)) }}"
tasks:
- debug:
var: url_username
给出(缩略)
shell> ansible-playbook -e username=value_of_username pb.yml
url_username: value_of_username
shell> ansible-playbook -e offline=value_of_offline pb.yml
url_username: value_of_offline
shell> 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: "{{ username | d(offline | d(omit)) }}"
<hr>
<sup>
Example of a complete playbook for testing
shell> cat pb.yml
- hosts: localhost
vars:
url_username: "{{ username | d(offline | d(omit)) }}"
tasks:
- debug:
var: url_username
gives (abridged)
shell> ansible-playbook -e username=value_of_username pb.yml
url_username: value_of_username
shell> ansible-playbook -e offline=value_of_offline pb.yml
url_username: value_of_offline
shell> ansible-playbook pb.yml
url_username: __omit_place_holder__eb8bf53eb654413fef765058f68f455d9e0a191e
</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论