Ansible:将命令参数作为列表传递

gad*_*iak 3 ansible

我想将多个参数作为列表存储在一个变量中。

vars:
  my_args:
    - --verbose
    - --quiet
    - --verify
Run Code Online (Sandbox Code Playgroud)

然后将列表作为带引号的参数传递给命令。最明显的join 过滤器没有按我预期的那样工作。它生成一个包含所有列表元素的单词,而不是每个列表元素一个单词:

tasks:
  - command: printf '%s\n' "{{ my_args | join(' ') }}"
...
changed: [localhost] => {
"changed": true,
"cmd": [
    "printf",
    "%s\\n",
    " --quiet  --verbose  --verify "
],

STDOUT:

 --quiet  --verbose  --verify
Run Code Online (Sandbox Code Playgroud)

如何将它们传递给命令?

gad*_*iak 5

要将列表元素作为参数传递给模块,请使用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 %}
Run Code Online (Sandbox Code Playgroud)

不要在过滤器中使用引号,而是在循环中使用它们。虽然略长,但for循环提供了更多塑造输出的可能性。例如,为列表项添加前缀或后缀"prefix {{ item }} suffix",或者对项应用过滤器,甚至有选择地使用loop.* 变量处理项。

有问题的例子是:

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
Run Code Online (Sandbox Code Playgroud)

列表元素不限于简单的字符串,可以包含一些逻辑:

vars:
  my_args:
    - --dir={{ my_dir }}
    - {% if my_option is defined %} --option={{ my_option }} {% endif %}
Run Code Online (Sandbox Code Playgroud)