Playbook to set Hostname for servers

Hi,

I am thinking on what would be the best way to set hostname on servers (trying to provision test machines) and if there are already a sample playbook or what would be the best approach,

Write playbook, to use sequence and then name it using that or maybe set it in ansible hostfile and use that variable to set the hostname ? Any recommendations would be really great!!

Possible suggestion:

You can use $inventory_hostname for whatever is in inventory and
$inventory_hostname_short will include everything but will chop off
the domain name part.

Do not confuse with $ansible_hostname which is the fact derived from
talking to the system! :slight_smile:

Thanks for the reply, Which documentation i should follow to define ($inventory_hostname) in hostfile for a list of IP’s.

I could not find any reference in this: http://ansible.cc/docs/patterns.html

is it something like “ntp_server: acme.example.org” or “ntp_server=ntp.atlanta.example.com” ?

Do you mean to get that value, or to define it?

You can use $ansible_hostname which is the hostname fact.

If you have the IP in the inventory file, the $inventory_hostname is
actually going to be the IP, but you are right in that you can set
arbitrary variables on those lines, or in a "host_vars/<name of host>"
file too, in a directory alongside your inventory file.

--Michael

Thanks, Sorry for the confusion, Will try to clarify it, So basically all the test servers have hostname as localhost now, I want to basically change the hostname to say “u1”

So from what i understand “$inventory_hostname” is a magic variable, but i dont know how to set this variable. So if “$inventory_hostname” is just going to be the IP from /etc/ansible/hosts file. Might not help me in this problem, but if i can have key=value , for the IP, So i can just use IP as the key and value can be whatever hostname i need to set.

I guess easiest thing would be set variable along with IP and use that to set the hostname? Or is there a recommended way to solve this.

Sorry i am still learning Ansible.

Sounds like you have decided to SSH in by IP and set the hostname.

If doing so, I would do it like this

[whatever_group]
2.2.2.122 hostname=foo.example.com

and then just use $hostname

there is nothing magic about hostname, you could have called it
'blippy' in this case, but that's an easy way to set a variable in the
host file.

You can of course also use "host_vars/<hostname>" to keep them in
seperate files, but it's overkill in this case.

Thank you very much, This is very helpful.