LoginSignup
5
1

More than 5 years have passed since last update.

AWS EC2 でファイルが更新されたタイミングでrsyncと任意のコマンドを実行する

Last updated at Posted at 2019-05-15

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

Master側(同期元) AmazonLinux2

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側(同期先) AmazonLinux2

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

/root/.sshid_rsaid_rsa.pubが存在する状態

Slave側で公開鍵を設置する

Masterのid_rsa.pubの中身を貼り付ける

vim ~/.ssh/master_rsa.pub

Permissionの変更

chmod 644 ~/.ssh/master_rsa.pub

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

スクリプトは任意の場所に設置する

監視ディレクトリとIP、コマンドは各自任意のものに

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

WATCH_DIR=/var/www/html
SLAVE_IP=xxx.xxx.xxx.xxx

events=(-e CREATE -e DELETE -e MODIFY -e MOVED_TO)
while inotifywait ${events[@]} $WATCH_DIR; do
    echo "変更検知"
    rsync -avz $WATCH_DIR $SLAVE_IP::html
    // 任意のコマンド
done

自動起動するようにsystemdにサービスとして追加する

サービス名は任意(今回はreflesh)

sudo vim /etc/systemd/system/reflesh.service
[Unit]
Description=Product Server Rsync 
[Service]
ExecStart=/path/to/reflesh.sh
Restart=always
Type=simple

[Install]
WantedBy=multi-user.target

サービスを登録する

sudo systemctl enable reflesh

Slave側でxinetdとrsyncの設定

xinetdの設定

ファイルが存在しない場合は作成する

sudo vim /etc/xinetd.d/rsync 

disable = yesnoに変更する

# 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

許可するIPと同期するディレクトリを設定

#--------------
# 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
hosts deny    = *
dont compress = *.gz *.tgz *.zip *.pdf *.sit *.sitx *.lzh *.bz2 *.jpg *.gif *.png

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

同期先ディレクトリはなければ作る必要がある
permissionは755
(存在しないとrsyncがコケる)

xinetdを再起動する

sudo systemctl restart xineted

試験

監視ディレクトリにファイル変更を行う

設定したSlave側でrsyncが実施され任意のコマンドが実行されればOK

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