Ask and Learn
Ask and Learn

Reputation: 8959

How can I specify a different domain name in Ansible inventory

I am using a Linux VM managed many Linux boxes (in a different domain), I find it annoying to use FQDN for each individual servers, because our internal domain name is very long.

For example

[web]
serve1.part.one.of.very.long.internal.domain.name.com
anotherserver.part.one.of.very.long.internal.domain.name.com

Is there a way to specify a default domain for groups of servers in inventory? I tried adding andible_domain variable in inventory file as a variable but did not work.

Upvotes: 10

Views: 11609

Answers (2)

jojoob
jojoob

Reputation: 153

A slightly different version of the answer from @ydaetskcoR to avoid breaking delegation by utilizing inventory_hostname_short instead of inventory_hostname:

[all:vars]
host_domain=part.one.of.very.long.internal.domain.name.com
ansible_host="{{inventory_hostname_short}}.{{host_domain}}"

[web]
server1
anotherserver

From Ansible docs:

inventory_hostname_short
The short version of inventory_hostname, is the first section after splitting it via .. As an example, for the inventory_hostname of www.example.com, www would be the inventory_hostname_short This is affected by delegation, so it will reflect the ‘short name’ of the delegated host

while inventory_hostname...

is not affected by delegation, it always reflects the original host for the task

Therefore, the problem with ansible_host="{{inventory_hostname}}.{{host_domain}}" is that that it resolves back to the original host when trying to delegate the task to another host with delegate_to. This was also elaborated on GitHub/ansible.

Upvotes: 2

ydaetskcoR
ydaetskcoR

Reputation: 56917

By default Ansible will assume that your inventory_hostname (the first string on the line in the inventory file) is what you would use to connect to that.

You can, however, always override this by using ansible_host (or ansible_ssh_host in older versions) which is useful if for some reason that's not the FQDN of the host or the domain for the host isn't in your DNS search domain list.

So you could do something like this:

[all:vars]
host_domain=part.one.of.very.long.internal.domain.name.com
ansible_host="{{inventory_hostname}}.{{host_domain}}"

[web]
server1
anotherserver

Upvotes: 20

Related Questions