0
votes

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!

2

2 Answers

0
votes

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 }}"
1
votes

Code

- name: Loop through example servers and show the hostname, ansible_host attribute
  debug:
    msg: "ansible_host attribute of {{ item }} is {{ hostvars[item]['ansible_host'] }}"
  loop: "{{ groups['servergroupexample'] }}"

Result

ok: [localhost] => (item=host1) => {
    "msg": "ansible_host attribute of host1 is 1.2.3.4"
}
ok: [localhost] => (item=host2) => {
    "msg": "ansible_host attribute of host2 is 5.6.7.8"
}

You can change the task from debug to shell or template, etc.

To output only the matching ansible_host:

- name: Loop through example servers and show the hostname, ansible_host attribute
  debug:
    msg: "ansible_host attribute of {{ item }} is {{ hostvars[item]['ansible_host'] }}"
  when: ansible_host == hostvars[item]['ansible_host']
  loop: "{{ groups['servergroupexample'] }}"