4

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.

U880D
  • 397
  • 1
  • 11
  • Regarding "I get syntax problem and can't figure out how to solve it." can you describe that in more detail and provide more information? – U880D Dec 28 '22 at 08:01

1 Answers1

4

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

Similar Q&A

U880D
  • 397
  • 1
  • 11