我想将多个参数作为列表存储在变量中。
vars:
my_args:
- --verbose
- --quiet
- --verify
然后将列表作为带引号的参数传递给命令。最明显的是join
过滤器没有按我的预期工作。它生成包含所有列表元素的单个单词,而不是每个列表元素一个单词:
tasks:
- command: printf '%s\n' "{{ my_args | join(' ') }}"
...
changed: [localhost] => {
"changed": true,
"cmd": [
"printf",
"%s\\n",
" --quiet --verbose --verify "
],
STDOUT:
--quiet --verbose --verify
如何将它们传递给命令?
要将列表元素作为参数传递给模块,请使用map('quote') | join(' ')
过滤器或for
loop:
tasks:
- name: Pass a list as arguments to a command using filters
command: executable {{ my_args | map('quote') | join(' ') }}
- name: Pass a list as arguments to a command using for loop
command: executable {% for arg in my_args %} "{{ arg }}" {% endfor %}
不使用带过滤器的引号,但是do use他们有一个循环。虽然长度稍长,for
循环提供了更多塑造输出的可能性。例如,为列表项添加前缀或后缀,例如"prefix {{ item }} suffix"
,或者对项目应用过滤器,甚至使用以下方法选择性地处理项目loop.*
变量 http://jinja.pocoo.org/docs/2.10/templates/#for.
有问题的例子是:
tasks:
- command: printf '%s\n' {{ my_args | map('quote') | join(' ') }}
- command: printf '%s\n' {% for arg in my_args %} "{{ arg }}" {% endfor %}
...
changed: [localhost] => {
"changed": true,
"cmd": [
"printf",
"%s\\n",
"--quiet",
"--verbose",
"--verify"
],
STDOUT:
--quiet
--verbose
--verify
列表元素不限于简单的字符串,还可以包含一些逻辑:
vars:
my_args:
- --dir={{ my_dir }}
- {% if my_option is defined %} --option={{ my_option }} {% endif %}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)