I am trying to communicate the Ansible inventory name of a server to the server itself, so I can use that name in a script that changes the server's hostname to the same name. Sending it to a file, or an environment variable would work great.
For example, in my inventory (/etc/ansible/hosts) I have:
[servergroupexample]
host1 ansible_host=1.2.3.4
host2 ansible_host=5.6.7.8
And I'd like to somehow communicate to 1.2.3.4 that his name is "host1", and 5.6.7.8 that her name is "host2" so I can reference these names in a script and set their hostnames to host1/host2 respectively. Thanks!
inventory_hostname
and inventory_hostname_short
are part of the special variables available to you.
For this specific case, I suggest you use inventory_hostname_short
so the following example still works if you later decide to name your hosts after their full fqdn name (e.g. host3.mydomain.com)
If your goal is to configure your target hostname, you can use the following playbook which uses the hostname
module
- name: Set hostname of my machines
hosts: servergroupexample
tasks:
- name: Set hostname
hostname:
name: "{{ inventory_hostname_short }}"