ansible无法获得inventory_hostname

时间:2015-02-24 01:05:21

标签: jinja2 ansible ansible-playbook

我试图获取正在处理的服务器的简称。

我在jinja2中有这个:

ServerAlias graphite.{{ hostvars[inventory_hostname] }}
ServerAlias graphite.{{ hostvars[inventory_hostname] }}.{{dc}}.{{subnet}}

以上只是泄漏了整个事实,而不仅仅是短名称。

这就是hosts.yaml的样子:

graphite.experimental.com dc=lv1 subnet=coupons.lan

1 个答案:

答案 0 :(得分:14)

您想要使用的只是{{ inventory_hostname }}(简称{{ inventory_hostname_short }})。

hostvars对象是一种访问Ansible知道的每个主机的变量的方法。因此hostvars[inventory_hostname]将为您提供包含有关当前主机的所有已知事实的对象,hostvars['foo']将为您提供包含有关主机“foo'”等所有已知事实的对象。 / p>

假设您有一组名为' db_servers'的主机。并且您希望生成模板中所有这些主机的IP地址列表。以下是您将如何做到这一点:

{% for host in groups['db_servers'] %}
   {{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}