ディレクトリやファイルの更新を検知して自動でrsyncする仕組みを作る


sftp(鍵認証)でサーバにソースをアップロードした際もしくはサーバ内の特定ディレクトリ(quotaを使わない容量制限有)以下のファイルを更新した際に自動で更新を検知してアプリケーションサーバにrsyncする仕組みを作ってみた。
OSはAmazon Linux、更新の検知はinotifyで行う。


※下記参考にpsshは事前にインストール
pssh-2.3.1をCentOS6.5にインストール

  1. sftp専用ユーザー作成
    # useradd sftptest
    # groupadd staff
    # gpasswd -a sftptest staff
    Adding user sftptest to group staff
    # id sftptest

  2. sftp接続するクライアントのSSH公開鍵を登録する
    # su - sftptest
    $ echo "xxxxx鍵文字列xxxxx" >>.ssh/authorized_keys
    $ chmod 600 .ssh/authorized_keys

  3. 容量制限(5GB)のあるファイルシステム作成
    # mv /home/sftptest /home/sftptest_bk
    # dd if=/dev/zero of=/home/sftptest.fs bs=1M count=5120
    # mke2fs -t ext4 /home/sftptest.fs
    # chown sftptest.sftptest /home/sftptest
    # mount -o loop -t ext4 /home/sftptest.fs /home/sftptest
    # df -h
    Filesystem Size Used Avail Use% Mounted on
    /dev/xvda1 30G 13G 17G 43% /
    devtmpfs 490M 92K 490M 1% /dev
    tmpfs 499M 0 499M 0% /dev/shm
    /dev/xvdf 30G 161M 28G 1% /data2
    /dev/loop0 4.8G 10M 4.6G 1% /home/sftptest
    # vi /etc/fstab
    /home/sftptest.fs /home/sftptest ext4 defaults,loop 0 0
    # cp -rp /home/sftptest_bk/*.* /home/sftptest/

  4. sftp専用ユーザーでsshログインできないようにする
    # usermod -s /sbin/nologin sftptest
    # vi /etc/ssh/sshd_config
    # override default of no subsystems
    Subsystem sftp /usr/libexec/openssh/sftp-server
    Match user sftptest
    ChrootDirectory /home/%u@
    ForceCommand internal-sftp

  5. sshdの再起動
    # service sshd restart

  6. アプリケーションサーバにもユーザー「sftptest」を作成
    # useradd sftptest
    # chmod 755 /home/sftptest

  7. rootのssh公開鍵をアプリケーションサーバに登録
    割愛

  8. inotifyインストール
    # yum --enablerepo=epel -y install inotify-tools

  9. デーモン化起動スクリプト作成
    (参考) inotifywaitによる更新除外ファイルの更新通知について試作してみました
    # vi /etc/rc.d/init.d/inotifywait
    「/usr/bin/Mail -s」のあたりで下記を実行する等
    /usr/local/pssh/bin/prsync -x --delete -h /root/pssh/nodelist/web -a /home/sftptest/ /home/sftptest/ > /dev/null 2>&1
    # chmod 755 /etc/rc.d/init.d/inotifywait
    # chkconfig --add inotifywait
    # chkconfig inotifywait on
    # chkconfig inotifywait --list
    inotifywait 0:off 1:off 2:on 3:on 4:on 5:on 6:off

  10. inotifywait起動
    # service inotifywait start

終わり