Linux

Ansible 事實在一行中輸出

  • May 21, 2021

我需要一些來自 Ansible 事實的資訊,因此在 YAML 下創建。但它給出的錯誤。我的要求是在一行中獲得輸出。這樣我們就可以使用 CSV 或電子表格對其進行過濾。

---
- hosts: all
 become: yes
 tasks:
 - name: Get content of remote server
   shell: echo system {{ inventory_hostname }} {{ crashkernel }} {{ ansible_os_family }}

錯誤:

+++++++++++++++++
TASK [Get content of remote server] ********************************************************************************************************************************************************************************************
fatal: [ip]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'crashkernel' is undefined\n\nThe error appears to be in 'status.yaml': line 5, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n  - name: Get content of remote server\n    ^ here\n"}

++++++++++++++++

也試過yamllint

$ yamllint status.yaml
status.yaml
 3:11      warning  truthy value should be one of [false, true]  (truthy)
 6:81      error    line too long (89 > 80 characters)  (line-length)

crashkernel不是事實本身,它是事實的子鍵ansible_proc_cmdline,所以使用

---
- hosts: all
 become: yes
 tasks:
 - name: Get content of remote server
   shell: echo system {{ inventory_hostname }} {{ ansible_proc_cmdline['crashkernel'] }} {{ ansible_os_family }}

請注意,您可以使用 ansible調試模組來列印消息,而不是echo在遠端端進行:

---
- hosts: all
 become: yes
 tasks:
 - name: Get content of remote server
   debug: 
     msg: "system {{ inventory_hostname }} {{ ansible_proc_cmdline['crashkernel'] }} {{ ansible_os_family }}"

另請注意,您可以使用gather_facts模組將有關主機的事實收集到包含 JSON 數據的文件中:

ansible localhost -m gather_facts –tree /tmp/facts

然後使用您選擇的程式語言或jq之類的工具來提取您想要的資訊:

jq ‘.ansible_facts.ansible_proc_cmdline.crashkernel’ /tmp/facts/localhost

引用自:https://unix.stackexchange.com/questions/650707