blockinfile

用來確定檔案裡有指定文字片斷的模組,使用很簡單。

我們直接用範例來說明,第一個例子是確定 sshd_config 裡有以下文字,如果沒有,先備份檔案,然後把這段文字放進去。

Match User ansible-agent
PasswordAuthentication no

使用模組時,這樣寫

- name: Insert/Update "Match User" configuration block in /etc/ssh/sshd_config
  ansible.builtin.blockinfile:
    path: /etc/ssh/sshd_config
    block: |
      Match User ansible-agent
      PasswordAuthentication no      
    state: present
    backup: yes
  • path: 是要處理的檔案路徑
  • block: 是要安插或移除的文字片斷
  • state: present 表示要有這段文字,若是 absent ,就是要沒有這段文字。
  • backup: yes 表示要備份,預設是不備份。

再舉另外一個例子,這是要在 <body> 後面加入這段 HTML

<h1>Welcome to {{ ansible_hostname }}</h1>
<p>Last updated on {{ ansible_date_time.iso8601 }}</p>

使用模組時,這樣寫

- name: Insert/Update HTML surrounded by custom markers after <body> line
  ansible.builtin.blockinfile:
    path: /var/www/html/index.html
    marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
    insertafter: "<body>"
    block: |
      <h1>Welcome to {{ ansible_hostname }}</h1>
      <p>Last updated on {{ ansible_date_time.iso8601 }}</p>      
  • marker: 在文字片段安插到檔案裡的時候,前後會加上一段註解,marker 就是註解的範本。{mark} 會被替換為 BEGIN 或 END, BEGIN 或 END 可以用 marker_begin, marker_end 來指定。
  • insertafter: "<body>" 表示要安插在 <body> 之後。

看完這兩個例子,相信你應該會使用這個模組了。

最後一個要提醒的地方是,如果 playbook 裡有多個 task 都是對同個檔案處理文字片段時,一定要加上 marker ,確保 marker 是不一樣的,否則的話,會導致後面的 task 蓋掉前面 task 所新增的文字片段。