首页 > 解决方案 > Ansible 没有在文件之间传递变量

问题描述

我试图使用 Ansible 将一些 jinja2 模板放到一个目录中,例如path/from/*.j2 to path/to/*.txt.

在我的./defaults/main.yml

---

test_var:
  - a: 1
    b: 2
  - a: 10
    b: 20

在我的./tasks/main.yml

---

- name: "Copy file"
  include: copy-files.yml
  with_nested:
    - test_var
  loop_control:
    loop_var: test_loop

在我的./tasks/copy-files.yml

---

- name: "copy {{ test_loop }}"
  template:
    src: "{{ test_loop.0.a }}"
    dest: "{{ test_loop.0.b }}"

我收到以下错误:

fatal: [localhost]: FAILED! => {"failed": true, "msg": "'unicode object' has no attribute 'b'"}

然后我使用调试并看到变量丢失了。

task path: ./tasks/main.yml
Wednesday 06 February 2019  01:15:10 +0000 (0:00:00.286)       0:00:04.308 ****
ok: [localhost] => {
    "msg": [
        {
            "a": 1,
            "b": 2
        },
        {
            "a": 10,
            "b": 20
        }
    ]
}

TASK [./ : Copy files] ********
task path: ./tasks/main.yml
Wednesday 06 February 2019  01:15:11 +0000 (0:00:00.064)       0:00:04.373 ****

TASK [./ : debug] *******************************
task path: ./tasks/copy-files.yml
Wednesday 06 February 2019  01:15:11 +0000 (0:00:00.089)       0:00:04.463 ****
ok: [localhost] => {
    "msg": [
        "a",
        "b"
    ]
}

那么这里有什么问题呢? ansible 2.1.0.0

标签: ansibleansible-template

解决方案


那么这里有什么问题呢?

有几件事在起作用。

最重要的是,您缺少with_nested:;的 jinja 替换。我不知道为什么你甚至得到了“a”和“b”,因为这很明显是list你们中的 a 被str喂食的with_nested:。我相信你想要with_nested: "{{ test_var }}"由于您使用的是令人难以置信的、令人不安的古老版本的 ansible,因此 ansible 可能“帮助”了您,但是现代版本不会将该名称自动强制转换为变量,因此请注意。

但是,即使修复它也不能解决您的问题,因为with_nested:想要 a listof list,而不是 a listof dict; 正如您从精美手册中看到的那样,它有效地调用{{ with_nested[0] | product(with_nested[1]) }}并且a的乘积是它dict的一个,这解释了您所看到的“a”和“b”listtuple.keys()

如果您希望srcand分别dest是 theabkey 的值,请跳过伪装并以with_nested:这种方式构造:

with_nested:
- '{{ test_var | map(attribute="a") | list }}'
- '{{ test_var | map(attribute="b") | list }}'

推荐阅读