LoginSignup
1
1

More than 1 year has passed since last update.

rsyncでのディレクトリ同期

Last updated at Posted at 2022-10-07

EC2上のディレクトリ同期を行う必要があり、試行錯誤の結果、Rsyncでの方法が良さそうだったので、やり方をメモしておこうと思います。

Amazon Linux 2 on EC2の環境です。

必要パッケージのインストール

Master側での作業

sudo amazon-linux-extras install -y epel
sudo sed -i -e "s/enabled=1/enabled=0/" /etc/yum.repos.d/epel.repo
sudo yum --enablerepo=epel install -y rsyncd inotify-tools

Slave側での作業

sudo amazon-linux-extras install -y epel
sudo sed -i -e "s/enabled=1/enabled=0/" /etc/yum.repos.d/epel.repo
sudo yum --enablerepo=epel install -y xinetd rsyncd

通信するためのSSHキーの作成

Master側でSSHキーを作成する

sudo su
ssh-keygen -t rsa -N ""

Master側で作成されたid_rsa.pubの中身をコピーする

vi /root/.ssh/id_rsa.pub

Slave側にSSHキーをコピー(設置)する

vimでファイルをオープンし、さっきコピーした中身を貼り付ける

vim ~/.ssh/id_rsa.pub

Permissionを変更する

chmod 644 ~/.ssh/id_rsa.pub

Master側に変更検知のスクリプトを設置する

スクリプトは、任意の場所に配置でOKです。私は、/usr/local/binに配置してみました。
.shは実行権限を付与する必要があります。

watch.sh
#!/bin/bash
# required package: inotify-tools

WATCH_DIR=/var/www/html/xxx
SLAVE_IP=xxx.xxx.xxx.xxx(<= EC2のLocal IPでOK: 172.16.X.X)

events=(-e CREATE -e DELETE -e MODIFY -e MOVED_TO)
while inotifywait ${events[@]} $WATCH_DIR; do
    echo "Detect Changes"
    rsync -avogh --chown=nginx:nginx --delete --exclude=".*" $WATCH_DIR $SLAVE_IP::wp
done

systemdにサービス登録する

sudo vim /etc/systemd/system/watch.service
watch.service
[Unit]
Description=Rsync service 
[Service]
ExecStart=/usr/local/bin/watch.sh
Restart=always
Type=simple

[Install]
WantedBy=multi-user.target

.serviceファイルができたら、サービス登録を行います。

sudo systemctl enable watch

Slave側でxinetdとrsyncを設定する

xinetdの設定

sudo vim /etc/xinetd.d/rsync

設定は以下の通り。

# default: off
# description: The rsync server is a good addition to an ftp server, as it \
#   allows crc checksumming etc.
service rsync
{
    disable         = no
    flags           = IPv6
    socket_type     = stream
    wait            = no
    user            = root
    server          = /usr/bin/rsync
    server_args     = --daemon
    log_on_failure  += USERID
}

rsyncの設定

sudo vim /etc/rsyncd.conf

設定は以下の通り。

#--------------
# Global options
#--------------
uid           = root
gid           = root
log file      = /var/log/rsyncd.log
pid file      = /var/run/rsyncd.pid
hosts allow   = xxx.xxx.xxx.xx/32 (<= MasterEC2インスタンスのLocal IP)
hosts deny    = *
dont compress = *.gz *.tgz *.zip *.pdf *.sit *.sitx *.lzh *.bz2 *.jpg *.gif *.png

[wp]
  comment      = rsync server
  path         = /var/www/html/xxx
  read only    = false
  exclude      = *.mp
  include      = *.mp30

xinetdを再起動する

sudo systemctl restart xineted

以上でMasterからSlaveへのディレクトリ同期ができるようになっているはずです。

1
1
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
1
1