Skip to content

Instantly share code, notes, and snippets.

@Bharat-B
Created January 9, 2022 18:57
Show Gist options
  • Save Bharat-B/0e31e06eb6a5fbac91791b964fb46772 to your computer and use it in GitHub Desktop.
Save Bharat-B/0e31e06eb6a5fbac91791b964fb46772 to your computer and use it in GitHub Desktop.
MySQL Master-Slave Replication setup
#!/bin/sh
# Should be run on the master
MASTER_IP=""
MASTER_SSH_PORT=""
MASTER_DATABASE=""
MASTER_BACKUP_PATH="/"
BACKUP_FILENAME="replica_backup.sql"
SLAVE_IP=""
SLAVE_SSH_USER="root"
SLAVE_SSH_PORT="22"
SLAVE_BACKUP_PATH="/"
SLAVE_REPLICA_USER=""
SLAVE_REPLICA_PASSWORD=""
mysql -e "CREATE USER '$SLAVE_REPLICA_USER'@'$SLAVE_IP' IDENTIFIED BY '$SLAVE_REPLICA_PASSWORD';GRANT REPLICATION SLAVE ON *.* TO '$SLAVE_REPLICA_USER'@'$SLAVE_IP';FLUSH PRIVILEGES;"
mysql -e 'FLUSH TABLES WITH READ LOCK;'
BINLOG_FILE=`mysql -e 'show master status \G;' | tail -n+2 | head -n+2 | grep 'File' | awk '{print $2}'`
POSITION=`mysql -e 'show master status \G;' | tail -n+2 | head -n+2 | grep 'Position' | awk '{print $2}'`
mysqldump $MASTER_DATABASE > "$MASTER_BACKUP_PATH/$BACKUP_FILENAME"
mysql -e 'UNLOCK TABLES;'
COMMAND="STOP SLAVE; CHANGE MASTER TO MASTER_HOST=\'$MASTER_IP\', MASTER_USER=\'$SLAVE_REPLICA_USER\', MASTER_PASSWORD=\'$SLAVE_REPLICA_PASSWORD\', MASTER_LOG_FILE=\'$BINLOG_FILE\', MASTER_LOG_POS=$POSITION; START SLAVE;"
echo $COMMAND
rsync -e "ssh -p $SLAVE_SSH_PORT" -a --progress "$MASTER_BACKUP_PATH/$BACKUP_FILENAME" $SLAVE_SSH_USER@$SLAVE_IP:$SLAVE_BACKUP_PATH/
ssh $SLAVE_SSH_USER@$SLAVE_IP -p $SLAVE_SSH_PORT "mysql -e 'CREATE DATABASE IF NOT EXISTS $MASTER_DATABASE;'"
ssh $SLAVE_SSH_USER@$SLAVE_IP -p $SLAVE_SSH_PORT "mysql $MASTER_DATABASE < $SLAVE_BACKUP_PATH/$BACKUP_FILENAME"
ssh $SLAVE_SSH_USER@$SLAVE_IP -p $SLAVE_SSH_PORT "mysql -e '$COMMAND'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment