ansible.builtin.slurp - 讀取檔案內容

在某些情況需要讀取檔案內容,例如送出 HTTP POST 請求,或者是需要對內容編碼,那麼可以怎麼去寫 Playbook 呢?

首先想到可以用的方法是 lookup('file', 'your_file')

像下面這個例子,就是讀取主控端機器上的 readme.txt,然後使用 debug 模組印出來。

---
- name: Read file content
  hosts: all
  
  tasks:
  - name: Display file content
    debug:
      msg: "{{ lookup('file', 'readme.txt') }}"

用 lookup 有幾個要注意的地方:

  1. lookup 是在主控端執行,所以讀取的是主控端上的檔案。
  2. lookup(‘file’) 能處理的檔案內容只能是文字檔,如果是二進位檔就不行。

那麼,如果要讀取二進位檔案該怎麼辦呢?這時候可以用 slurp

下面這個例子就是用 slurp 讀取檔案內容後,使用 uri 模組進行上傳。

---
- name: Use HTTP POST to upload file
  hosts: all
  
  tasks:
    - name: Read binary file content
      slurp:
        path: "/bin/ls"
      register: bin_file

    - name: Send HTTP POST Request
      uri:
        url: "https://your_server/upload.php"
        headers:
          Accept: "application/json"
          Content-Type: "application/octet-stream"
        method: POST
        validate_certs: false
        body: "{{ bin_file.content }}"
        status_code:
          - 200
          - 201
      register: upload_result
      
    - name: Display upload_result
      debug:
        var: upload_result

使用 slurp,就可以避掉 lookup(‘file’) 的限制。

  1. 可以讀取受控端主機上的檔案,也可以利用 delegate_to: localhost 來讀取主控端主機上的檔案。
  2. 可以讀取二進位檔案來做進一步處理,例如做 base64 編碼
---
- name: Use base64 to encode file
  hosts: all
  
  tasks:
    - name: Read binary file content
      slurp:
        path: "/bin/ls"
      register: bin_file

    - name: Encode with base64
      copy:
        content: "{{ bin_file.content | b64encode }}"
        dest: "/tmp/output.txt"

讀到這裡,相信你已經知道該怎麼寫 Ansible playbook 來讀取檔案內容,並做出更多變化了,讓我們繼續朝 Ansible Pro 前進!