robert.kane
robert.kane

Reputation: 129

How to get the first part of the "inventory_hostname" in Ansible?

I am trying to get the first part of my inventory_hostname.

server00122.linux.ca.domain.com

All I want is the server00122 part.

My Code:

hostName: "{{ inventory_hostname | basename }}"

I use the above code. However, it just gives me the same output.

Upvotes: 5

Views: 7526

Answers (3)

dokaspar
dokaspar

Reputation: 8644

If you want the short form of any hostname similar to what the Unix command hostname --short provides, you can do it with split() like this (of course the hard-coded hostname can be replaced with any variable):

- name: Print short host name
  debug:
    msg: "{{ 'server00122.linux.ca.domain.com'.split('.')[0] }}"

The above task returns:

msg: server00122

Upvotes: 2

tharriott
tharriott

Reputation: 111

Instead of using the inventory_hostname use ansible_hostname.

That should give you want you need.

Upvotes: 0

Zeitounator
Zeitounator

Reputation: 44799

There is an other magic variable called inventory_hostname_short.

Extract from the above link:

inventory_hostname_short: The short version of inventory_hostname

Upvotes: 8

Related Questions