Ansible 没有在文件之间传递变量

Ansible didnt pass down variables between files

我试图使用 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

So what could be wrong here?

有几件事在起作用。

最重要的是,您缺少 with_nested: 的 jinja 替换;我不知道为什么你甚至得到 "a" 和 "b",因为这很明显是你喂给 with_nested:strlist。我相信你想要 with_nested: "{{ test_var }}"。可能是 ansible "helped" 你因为 令人难以置信地,令人不安的 你正在使用的 ansible 的古老版本,但现代版本不会自动将该名称强制转换为变量,所以要注意。

但是,即使修复也无法解决您的问题,因为 with_nested: 想要 listlist,而不是 dictlist ;正如您从 dictthe fine manual, it is effectively calling {{ with_nested[0] | product(with_nested[1]) }} and product 中看到的那样,它的 .keys()tuplelist,这解释了 "a" 和 "b" 你看到了

如果你想让srcdest分别成为ab键的值,那么跳过伪装并构造with_nested: 这样:

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