copy
modulelineinfile
module 修改或新增特定行copy
直接覆蓋整份檔案lineinfile
僅修改檔案中的某一行# 先創建一個 tmp.txt 檔案
echo "hello ansible world" > tmp.txt
# 透過 copy moduel 把檔案複製到遠端機器上的 /tmp
# 筆者比較喜歡用 yaml,所以這邊就直接使用 yaml 清單當 inventory (host.yml)
ansible all -i host.yml -m ansible.builtin.copy -a "src=tmp.txt dest=/tmp/ backup=yes"
💡 Tips:
dest
指到目錄時會以原檔名放進去 (例如:/tmp/tmp.txt)。- 想同時設定權限/擁有者,可加上
mode=0644 owner=root group=root
。- 加上
backup=yes
可在覆蓋前自動備份原檔。
# 確保檔案中有指定的一行,沒有則新增
ansible all -i host.yml -m ansible.builtin.lineinfile -a "path=/tmp/tmp.txt line='my name is jasper' state=present create=yes backup=yes"
如果你想「精準替換」既有的那一行 (例如開頭是 my name is
),可以用 regexp
:
ansible all -i host.yml -m ansible.builtin.lineinfile -a "path=/tmp/tmp.txt regexp='^my name is ' line='my name is jasper' create=yes backup=yes"
💡 Tips:Ansible 具備冪等性。相同指令重跑,若內容已經符合期待,結果會是
ok
,有變更才會是changed
。
copy
複製到遠端機器。lineinfile
幫剛剛那個檔案新增或更新一行文字。regexp
做精準替換,並觀察 ok/changed
的差異。明天我們來學學寫 Playbook,讓我們的操作更有條理、更好維護!