Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLDump RDS to S3 using Lambda

I am looking up how to export RDS to S3 using Lambda, so far I found a Python node and Java API but I can't find a way of programmatically running something like mysqldump without the actual executable.

Is there a way of doing it?

I am thinking using node.js to call SHOW CREATE TABLE for each element in SHOW TABLES

Then somehow create extended INSERT statements.

like image 920
Archimedes Trajano Avatar asked Sep 11 '25 20:09

Archimedes Trajano


1 Answers

Yes it is possible, you need to include mysqldump executable with your lambda package though!

Sample script in Node.js for backup using mysqldump and uploading to S3.

var S3 = require('./S3Uploader'); //custom S3 wrapper with stream upload functionality

var fs = require('fs');
var path = require('path');
var util = require('util');

const writeFile = util.promisify(fs.writeFile);

const execFile = util.promisify(require('child_process').execFile);
const exec = util.promisify(require('child_process').exec);

async function backupToS3(){

    var backupName = 'mysqlbackup-'+new Date().toISOString()+'.gz'

    var content = `cd /tmp
                   BACKUPNAME="[BACKUP_NAME]"
                  [EXE_PATH]/mysqldump --host [DB_ENDPOINT] --port [DB_PORT] -u [DB_USER] --password="[DB_PASS]" [DB_NAME] | gzip -c > $BACKUPNAME
                  `;
    content = content.replace('[BACKUP_NAME]', backupName);
    content = content.replace('[DB_ENDPOINT]', 'xx'); //get from lambda environment variables
    content = content.replace('[DB_PORT]', 'xx'); //get from lambda environment variables
    content = content.replace('[DB_USER]', 'xx'); //get from lambda environment variables
    content = content.replace('[DB_PASS]', 'xx'); //get from lambda environment variables
    content = content.replace('[DB_NAME]', 'xx'); //get from lambda environment variables
    content = content.replace('[EXE_PATH]', __dirname+'/tools'); //path where mysqldump executable is located withing the lambda package

    //generate backup script
    await writeFile('/tmp/db_backup.sh', content);
    fs.chmodSync('/tmp/db_backup.sh', '755');

    //run script
    var res1 = await execFile('/tmp/db_backup.sh');

    //stream upload to S3
    var res2 = await S3.uploadFile('/tmp/'+backupName, 'backups');

    //cleanup local backup (this should cleanup automatically according to lambda lifecycle)
    var res3 = await exec('rm /tmp/'+backupName);

    return  'Backup complete';
};

Sample S3Uploader posted here - Loading File directly from Node js req body to S3

like image 81
LiriB Avatar answered Sep 14 '25 10:09

LiriB