Ansible:将命令参数作为列表传递 [英] Ansible: Pass command arguments as a list

查看:37
本文介绍了Ansible:将命令参数作为列表传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to store multiple arguments in a variable as a list.

vars:
  my_args:
    - --verbose
    - --quiet
    - --verify

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

Then pass the list as quoted arguments to a command. The most obvious join filter doesn't work as I expected. It produces a single word containing all list elements as opposed to one word per list element:

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

STDOUT:

 --quiet  --verbose  --verify

如何将它们传递给命令?

How to pass them to a command?

推荐答案

要将列表元素作为参数传递给模块,请使用 map('quote') |join(' ') 过滤器或 for 循环:

To pass a list elements as arguments to a module use either map('quote') | join(' ') filters or the 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 %}

不要将引号与过滤器一起使用,而将它们与循环一起使用.尽管略长,for 循环提供了更多的输出整形可能性.例如,为列表项添加前缀或后缀,如 "prefix {{ item }} suffix",或对项目应用过滤器,甚至使用 loop.* 变量.

Do not use quotes with filter, but do use them with a loop. Although being slightly longer, the for loop gives more possibilities of shaping the output. For example prefixing or suffixing the list item like "prefix {{ item }} suffix", or applying filters to the item or even selectively processing items using 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

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

List elements are not limited to simple strings and can contain some logic:

vars:
  my_args:
    - --dir={{ my_dir }}
    - {% if my_option is defined %} --option={{ my_option }} {% endif %}

这篇关于Ansible:将命令参数作为列表传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆