如何使用 Playbook 將 inventory_hostname 記錄到遠端檔案?

如何使用 Playbook 將 inventory_hostname 記錄到遠端檔案?

我正在嘗試將清單主機名稱寫入遠端檔案以供以後處理(最終是遠端事實檔案)。下面的主機具有實體主機名,calvin.mydomain但是控制器使用庫存主機名稱(不同的 DNS)連接到它,calvin.test.mydomain因此我不能只使用-m setup僅從遠端(AFAIK)角度收集資訊的事實變數。

我想我可以透過將環境變數匯出到遠端然後將其寫入檔案來做到這一點,但這只會產生文字庫存主機名

如何寫入hostvars[inventory_hostname]或寫入遠端{{inventory_hostname}}檔案?/etc/ansible/facts.d/

sudo ansible-playbook ./playbooks/hostname.yml -k -u root -i calvin.test.mydomain,
TASK [echo the LAN_HOSTNAME environment var] *******...
changed: [calvin.my.testing.dom]

這是我的劇本

---
- hosts: all
  tasks:
      - name: "echo the LAN hostname into a file on the remote"
        shell: "echo $LAN_HOSTNAME > /tmp/hostname.ans"
        environment:
            LAN_HOSTNAME: inventory_hostname

答案1

需要使用它(copy按照@Michael Hampton的建議更改為):

---
- hosts: all
  tasks:
   - name: "Create custom fact directory"
     file:
         path: "/etc/ansible/facts.d"
         state: "directory"

   - name: "Insert custom fact file"
     copy:
         content: "#!/bin/bash\necho {\\\"ansible_LAN_hostname\\\" : \\\"{{ inventory_hostname }}\\\"}"
         dest: /etc/ansible/facts.d/lan_hostname.fact
         owner: root
         group: sysadmin
         mode: 0775

相關內容