根据组更改Ansible模板中的变量 [英] Change variable in Ansible template based on group

查看:198
本文介绍了根据组更改Ansible模板中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似Ansible的库存文件:

I've got an Ansible inventory file a bit like this:

[es-masters]
host1.my-network.com

[es-slaves]
host2.my-network.com
host3.my-network.com

[es:children]
es-masters
es-slaves

我还有一个Jinja2模板文件,如果主机属于"es-masters"组,则需要将其设置为"true".

I also have a Jinja2 template file that needs a certain value set to "true" if a host belongs to the "es-masters" group.

我敢肯定有一种简单的方法,但是在谷歌搜索并阅读了文档之后,我画了一个空白.

I'm sure that there's a simple way of doing it but after some Googling and reading the documentation, I've drawn a blank.

我正在Jinja2模板中寻找类似这样的简单程序化的东西:

I'm looking for something simple and programmatic like this to go in the Jinja2 template:

{% if hostvars[host][group] == "es-masters" %}
node_master=true
{% else %}
node_master=false
{% endif %}

有什么想法吗?

推荐答案

您可以采用另一种方法. 您检查标识符(主机名或IP或清单中的任何内容)是否在已定义的组中.如果该组位于hostvars中,则不会.

You do it the other way around. You check if the identifier (hostname or IP or whatever is in your inventory) is in the defined group. Not if the group is in the hostvars.

{% if ansible_fqdn in groups['es-masters'] %}
node_master=true
{% else %}
node_master=false
{% endif %}

但是,您最好执行以下操作:

在模板中提供默认值

But, what you better should do is this:

Provide default in template

# role_name/templates/template.j2
node_master={{ role_name_node_master | default(true) }}

比在group_vars中覆盖

Than override in group_vars

# group_vars/es-masters.yml
role_name_node_master: false

这篇关于根据组更改Ansible模板中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆