【问题标题】:Ansible global variable in template模板中的 Ansible 全局变量
【发布时间】:2015-09-25 17:00:00
【问题描述】:

我无法从 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: ...

模板/template.conf.j2

The global variable is: {{ GlobalVariable }}

group_vars/all.yml

GlobalVariable: something

当我运行 playbook 时,尝试编写该模板时出现错误。

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

【问题讨论】:

    标签: jinja2 ansible


    【解决方案1】:

    将您的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.
        """
    

    【讨论】:

    • 这是绝对正确的。当我查看standard directory layout 时,我尝试将我所有的剧本移动到项目目录并且它有效。看起来它确实基于相邻文件夹。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2011-01-14
    • 2014-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多