1

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

0

1 Answer 1

3

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] }}"
3
  • Thanks for the prompt reply. That works perfectly. This particular script will run against a number of groups from the host file. Is there a way to use the 'target' instead of hardcoding the group name since the target will change?? For example it could be 'target=TEST1' or 'target=TEST2'.
    – John
    Jan 14, 2021 at 16:38
  • You're welcome. Simply put the substitution into the code. I've updated the answer with an example. The details (hosts, vars, run_once ...) would depend on the use-case, of course. Open a new question and make it mre if you have another issue. Jan 14, 2021 at 16:45
  • Perfect solution. Thank you very much for your time.
    – John
    Jan 14, 2021 at 17:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .