Ansible 剧本变量在模板中不起作用

Ansible playbook vars not working in templates

我在让变量在我的模板中工作时遇到问题。变量在我的剧本中有效,但在模板中,它们被渲染 'as is' 而没有被它们的值替换。这是我正在尝试的简单 test-playbook.yml

---
- name: Test playbook vars
  hosts: webservers
  vars:
    hello_var: Hello World
    hello_file_path: /tmp/hello_file.txt
  tasks:
    - name: Copy hello world file
      copy: src=templates/hello_world.txt.j2 dest={{ hello_file_path }}

在我的templates/hello_world.txt.j2中,我有以下内容

hi  {{ hello_var }}

在 运行 剧本之后,我在 /tmp/hello_world.txt 的主机上拥有与我的模板相同的内容

hi  {{ hello_var }}

剧本中使用的变量 hello_file_path 有效,但我的模板中使用的变量 hello_var 无效。

在您使用的任务中 copy module which simply copies the file without any template processing. In order to use template you need to use template module

- name: Copy hello world file
  template: src=templates/hello_world.txt.j2 dest={{ hello_file_path }}