Created
December 13, 2017 09:16
-
-
Save avishayil/27f16de2fdb773c95940bb938109dff4 to your computer and use it in GitHub Desktop.
Lambda function for promoting replica to master
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var AWS = require('aws-sdk'); | |
AWS.config.update({ region: 'your-region-ie:eu-central-1' }); | |
var mysql = require('mysql'); | |
// Better to use environment variables, but for the example we'll leave it like this | |
var dbClusterIdentifier = 'your-cluster'; | |
var clusterEndpoint = 'your-cluster.cluster-identifier.your-region.rds.amazonaws.com'; | |
var user = 'username'; | |
var password = 'password'; | |
var database = 'database'; | |
exports.handler = (event, context, callback) => { | |
// Initialize new RDS object | |
var rds = new AWS.RDS(); | |
// Connect to the MySQL Instance | |
var con = mysql.createConnection({ | |
host: clusterEndpoint, | |
user: user, | |
password: password, | |
database: database | |
}); | |
var master; | |
var replica; | |
con.connect(function (err) { | |
if (err) console.log(err) && context.fail(); | |
console.log('Conneting to database...'); | |
con.query("select server_id from mysql.ro_replica_status where session_id <> 'MASTER_SESSION_ID' order by current_replay_latency_in_usec desc;", function (err, result, fields) { | |
if (err) console.log(err) && context.fail(); | |
replica = result[0].server_id; | |
console.log('trying to promote instance ' + replica + ' to cluster...') | |
var params = { | |
DBClusterIdentifier: dbClusterIdentifier, | |
TargetDBInstanceIdentifier: replica | |
}; | |
rds.failoverDBCluster(params, function (err, data) { | |
if (err) console.log(err, err.stack) && context.fail(); // an error occurred | |
else console.log(data) && console.log('instance ' + replica + ' + was successfully promoted to cluster.') && context.succeed('Success'); // successful response | |
}); | |
}); | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment