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

标签 ansible

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

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/

相关文章:

python - 如何使用 ansible 和 module portinstall 安装 FreeBSD port?

ansible - Ansible 中角色的串行执行

cron - Ansible with_items 不断覆盖循环的最后一行

bash - Shell 命令手动工作,不使用 Ansible

Ansible 分离主机、group_vars 和 host_vars

azure - 通过 Bastion Host 配置 VMSS 创建的 Windows VM

regex - Ansible Lineinfile - 使用反向引用时转义单引号

bash - 如何在ansible shell模块中转义特殊字符

shell - 是否可以从ansible角色/文件目录运行shell脚本?

ansible - 你需要 root 才能执行 - ansible