LoginSignup
3
4

More than 5 years have passed since last update.

備忘録 Ansibleファイルをコピー時のバックアップが簡単でござるの巻

Posted at

Ansibleでファイルをコピーする際、バックアップが非常に容易であることにびっくり!

1. Chefの場合・・・

Chefの場合、ファイル操作を行う場合は、自動的に/var/chef/backupに5世代のバックアップファイルを取ってくれます。
しかし、chefをやってない人からすれば、どこに自動的にバックアップを取ってくれるなんてわからない。。。。
なので、私はスクリプトのように自分でタイムスタンプ付の処理を作成していました。
こんなかんじで。

mtime = Time.now.strftime("%Y%m%d%H%M%S")
hosts_file = File.join("/etc",node['linuxos']['hosts'])

# backup /etc/hosts
bash "backup #{hosts_file}" do    
    code <<-EOH
       cp -p #{hosts_file} #{hosts_file}.#{mtime}   
    EOH   
    only_if {File.exists?("#{hosts_file}")}
end

2.Ansibleの場合

オプションに backup なるものがあるのですね!

image.png

実際にやってみました。

test2.yml
---
- hosts: web
  sudo: yes
  tasks:
   - name: copy a directory
     copy:
       src: ../files/test2.txt
       dest: /tmp
       mode: 0577
       backup: yes       ← バックアップファイルを取得

テスト用ファイルも合わせて編集

test comment1
test comment2
test comment3

実行してみます。

# ansible-playbook -i hosts ./task/test2.yml

対象ノードの実行結果をみてみると・・・・

# ls -l
total 8
-r-xrwxrwx 1 root root 42 Jan 15 17:12 test2.txt
-r-xrwxrwx 1 root root 28 Jan 15 17:02 test2.txt.32248.2018-01-15@17:12:45~

タイプスタンプ付きのバックアップファイルが出来ているのがわかります!
中身もこれらのファイルが違うこともわかります。

# diff test2.txt test2.txt.32248.2018-01-15@17:12:45~
3d2
< test comment3

冪統性の確認をしてみたところ、ファイルがコピーされていませんでしたので、ファイルの編集があった場合のみ、バックアップファイルが作成されます。

バックアップのファイル名をもっと違う名前にしたり、世代管理ができるのかが不明・・・・
そのへん、また時間があったら調べてみるか。

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4