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