Ansible Get hostname from hosts file

ansibleansible-playbook

I want to be able to get the first 8 characters of the first host in a group from a hosts file. So in the below example I want a variable to be assigned xx33sx01. I know I can use inventory_hostname to get the hosts but it returns all 4 and I only need the first host and only the first 8 characters.

example inventory of Ansible (INI-style):

[TEST1]
xx33sx0101.domain.com
xx33sx0102.domain.com
xx33sx0103.domain.com
xx33sx0104.domain.com

ansible-playbook /local_home/scripts/test.yml -i ~/hosts -e "target=TEST1" -K

Best Answer

To get the first 8 characters of the first hostname in the group, try

- debug:
    msg: "{{ groups[target_group][0][:8] }}"
  vars:
    target_group: TEST1

(not tested)


  • To make the debug task work, the group must be available to the playbook, of course. For example
- hosts: all
  tasks:
    - debug:
        msg: "{{ groups[target_group][0][:8] }}"