Ansible 從主機檔案取得主機名

Ansible 從主機檔案取得主機名

我希望能夠從主機檔案中取得群組中第一個主機的前 8 個字元。所以在下面的例子中我想要分配一個變數xx33sx01。我知道我可以使用 inventory_hostname 來取得主機,但它會傳回全部 4 個主機,我只需要第一個主機和前 8 個字元。

Ansible 的清單範例(INI 樣式):

[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

答案1

若要取得群組中第一個主機名稱的前 8 個字符,請嘗試

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

(未測試)


  • 當然,為了使調試任務正常工作,該組必須可供劇本使用。例如
- hosts: all
  tasks:
    - debug:
        msg: "{{ groups[target_group][0][:8] }}"

相關內容