我如何 assemble 复制模块列表项中的文件名?

How can I assemble a file name from list items on copy module?

在我的 Ansible 剧本中,我将此列表作为变量:

 collections: [customers licenses system]

该列表在多个地方使用。
在一个地方,我需要复制包含我的数据的现有文件(customers.jsonlicenses.jsonsystem.json)。

这不起作用:

 - copy: src="{{ item }}.json" dest=~/import/
   with_items: "{{ collections }}"

它首先连接列表,然后连接我的文件扩展名,所以它就像 files/customers licenses system.json

这也不行:

 - copy: src={{ item ~ ".json" }} dest=~/import/
   with_items: "{{ collections }}"

在这种情况下,它忽略了文件扩展名,第一项看起来像 files/customers

有没有一种方法可以让它在不复制变量或重命名文件的情况下工作?

问题是当前定义的这个变量只是一个字符串,而不是包含 3 个项目的列表:

collections: [customers licenses system]

这里有一个简单的例子来演示:

- hosts: localhost
  vars:
    collections: [customers licenses system]

  tasks:
    - debug: var=item
      with_items: collections

上面的输出是:

TASK: [debug var=item] ********************************************************
ok: [localhost] => (item=customers licenses system) => {
    "item": "customers licenses system"
}

因此 ansible 将 collections 视为其中包含一项的列表。定义列表的正确方法是:

collections: ['customers', 'licenses',  'system']

或者,你也可以这样定义:

collections:
  - customers
  - licenses
  - system

当您将 collections 更改为其中之一时,上述测试的输出将变为:

TASK: [debug var=item] ********************************************************
ok: [localhost] => (item=customers) => {
    "item": "customers"
}
ok: [localhost] => (item=licenses) => {
    "item": "licenses"
}
ok: [localhost] => (item=system) => {
    "item": "system"
}

更改列表的定义方式,复制模块应按您预期的方式工作。