I'm trying to get the short name of a server being worked on.
I have this in jinja2:
ServerAlias graphite.{{ hostvars[inventory_hostname] }}
ServerAlias graphite.{{ hostvars[inventory_hostname] }}.{{dc}}.{{subnet}}
The above just spills the whole glob of facts instead of just the short name.
This is what the hosts.yaml looks like:
graphite.experimental.com dc=lv1 subnet=coupons.lan
inventory_hostname. The inventory_hostname is the hostname of the current host, as known by Ansible. If you have defined an alias for a host, this is the alias name. For example, if your inventory contains a line like this: server1 ansible_host=192.168.4.10. then inventory_hostname would be server1 .
ansible's inventory_hostname is a built-in variable. It takes the hostname of the machine from the inventory script or the ansible configuration file. Since the value is taken from the configuration file we are defining, the actual runtime hostname value might vary from what is returned by this variable.
Simple ansible playbook which reads the host name in the local machine and prints the result. echo $HOSTNAME shell command returns the host nname of the current machine. result is the output of Get hostnmae task and output is in the JSON format.
What you want to use is just {{ inventory_hostname }}
(or {{ inventory_hostname_short }}
for the short name).
The hostvars
object is a way to access the variables of every host that Ansible knows about. So hostvars[inventory_hostname]
will give you the object containing all known facts about the current host, hostvars['foo']
will give you the object containing all the known facts about the host 'foo', etc.
Suppose you have a group of hosts called 'db_servers' and you wanted to generate a list of the IP addresses of all those hosts in a template. Here's how you would do that:
{% for host in groups['db_servers'] %}
{{ hostvars[host]['ansible_eth0']['ipv4']['address'] }}
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With