HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Ansible: How to get hostname without domain name?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
withoutdomaingetnamehostnamehowansible

Problem

How to get value from /etc/hostname ignoring domain name. For example, /etc/hostname says "client.test.dom" and I need to get "client".

I have tried "{{ ansible_nodename | replace('.rail.dom','') }}" but I get syntax problem and can't figure out how to solve it.

Solution

It is assumed that you have a proper and valid inventory defined. Then, according Information about Ansible: magic variables

You can use the magic variable inventory_hostname, the name of the host as configured in your inventory, as an alternative to ansible_hostname when fact-gathering is disabled. If you have a long FQDN, you can use inventory_hostname_short, which contains the part up to the first period, without the rest of the domain.

If facts are gathered you can use additionally ansible_hostname or ansible_facts['nodename'].

A minimal example playbook
---
  • hosts: localhost


become: false
gather_facts: true

tasks:

- name: Show hostname
debug:
msg: "Host: {{ ansible_hostname }} FQDN: {{ ansible_nodename }}"


will result into an output of
TASK [Show hostname] *
ok: [localhost] =>
msg: 'Host: test FQDN: test.example.com'


You may then have a look into the following examples
- name: Split nodename
debug:
msg: "{{ ansible_nodename.split('.')[0] }}"

- name: Split nodename
debug:
msg: "{{ ansible_nodename | split('.') | first }}"


resulting both into an output of
TASK [Split nodename]
ok: [localhost] =>
msg: test


Further Documentation

  • split filter – split a string into a list



Similar Q&A

  • Ansible string split



  • How to split value in Ansible with delimiter?



  • What's the difference between inventory_hostname and ansible_hostname?

Context

StackExchange DevOps Q#17135, answer score: 4

Revisions (0)

No revisions yet.