根据组更改Ansible模板中的变量

Cha*_*wey 11 templates jinja2 ansible

我有一个Ansible库存文件有点像这样:

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

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

[es:children]
es-masters
es-slaves
Run Code Online (Sandbox Code Playgroud)

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

我确信有一种简单的方法可以做到这一点,但经过一些谷歌搜索和阅读文档后,我画了一个空白.

我正在寻找像Jinja2模板这样的简单和程序化的东西:

{% if hostvars[host][group] == "es-masters" %}
node_master=true
{% else %}
node_master=false
{% endif %}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

t2d*_*t2d 16

你反过来做.您检查标识符(主机名或IP或库存中的任何内容)是否在定义的组中.如果该组属于hostvars,则不会.

{% if ansible_fqdn in groups['es-masters'] %}
node_master=true
{% else %}
node_master=false
{% endif %}
Run Code Online (Sandbox Code Playgroud)

但是,你最好应该做的是:

在模板中提供默认值

# role_name/templates/template.j2
node_master={{ role_name_node_master | default(true) }}
Run Code Online (Sandbox Code Playgroud)

比在group_vars中覆盖

# group_vars/es-masters.yml
role_name_node_master: false
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您的清单未使用ansible_fqdn,ansible_hostname等标识主机,则还可以group_names用来检查当前主机是否将“ es-masters”作为其组之一。

{% if 'es-masters' in group_names %}
node_master=true
{% else %}
node_master=false
{% endif %}
Run Code Online (Sandbox Code Playgroud)

参见https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables


pan*_*icz 5

为了避免出现不存在组的错误,您应该首先检查该组是否存在:

{% if 'es-masters' in group_names and ansible_fqdn in groups['es-masters'] %}
node_master=true
{% else %}
node_master=false
{% endif %}
Run Code Online (Sandbox Code Playgroud)