我想将多个参数作为列表存储在一个变量中。
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
循环:
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 %}
不要在过滤器中使用引号,但一定要在循环中使用它们。 for
循环虽然稍长一些,但它提供了更多调整输出的可能性。例如,为列表项添加前缀或后缀,如 "prefix {{ item }} suffix"
,或对项目应用过滤器,甚至使用 loop.*
variables 选择性地处理项目。
有问题的例子是:
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 %}
关于Ansible:将命令参数作为列表传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49799595/