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

查看:27
本文介绍了基于组更改 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 或清单中的任何内容)是否在定义的组中.如果该组在主机变量中,则不会.

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天全站免登陆