模板中的 Ansible 全局变量

Ansible global variable in template

我无法从 ansible 获取我的 jinja2 模板,无法读取 group_vars/all.yml 中设置的全局变量。

** 我的问题是 **:如何让我的 j2 模板能够看到 group_vars/all.yml 中设置的全局变量?根据我的理解,group_vars/all 应该适用于所有群体。

我的ansible项目如下:

group_vars/
  all.yml

playbooks/
  roles/
    some-role/
      tasks/
        main.yml
      templates/
        template.conf.j2
  my-playbook.yml

tasks/main.yml

---
- name: do it
  template:
    src: template.conf.j2
    dest: ...

templates/template.conf.j2

The global variable is: {{ GlobalVariable }}

group_vars/all.yml

GlobalVariable: something

当我 运行 剧本时,我在尝试编写该模板时遇到错误。

AnsibleUndefinedVariable: One or more undefined variables: 'GlobalVariable' is undefined

将您的 group_vars 文件夹放在 playbooks 文件夹中,它应该可以解决您的问题。

类似的东西:

playbooks/
  group_vars/
    all.yml
  roles/
    some-role/
      tasks/
        main.yml
      templates/
        template.conf.j2
  my-playbook.yml

然后无论你在哪里执行你的ansible-playbook -i hosts my-playbook.yml命令(在剧本之外或里面)它应该工作

这里参考source-code

再多解释一下
   """
    Loads variables from group_vars/<groupname> and host_vars/<hostname> in directories parallel
    to the inventory base directory or in the same directory as the playbook.  Variables in the playbook
    dir will win over the inventory dir if files are in both.
    """