Created
November 30, 2020 20:08
-
-
Save Murali91/8a767d4f39a921b78ee09a39e7461377 to your computer and use it in GitHub Desktop.
JS ES6 Util class to create and export AWS RDS snapshot to S3
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
const moment = require('moment'); | |
/** | |
* ExportDbSnapshotToS3 has methods | |
* 1. to create a db snapshot and also to export | |
* 2. export a db snapshot to S3 | |
* @param {Object.<string>} | |
* rds - AWS RDS API object | |
* name - name of the service/export operation. | |
* region - AWS region in which the resources exists | |
* accountId - AWS AccountID on which the export operation has to be performed | |
* dbInstanceIdentifier - DB Identifier for which snapshot has to be created | |
* s3UploaderRoleArn - Role Arn that should be used to upload snapshot to S3 bucket | |
* snapshotEncryptKeyId - KMS Key ID/ARN that should be used to encrypt the snapshot | |
* destinationS3Name - S3 bucket name to which the snapshot has to be uploaded | |
* @constructor | |
*/ | |
class ExportDbSnapshotToS3{ | |
constructor(params){ | |
Object.assign(this,params); | |
} | |
getIdentifier(){ | |
let timestamp = moment().unix(); | |
return `${this.name}-${timestamp}`; | |
} | |
async createDbSnapshot(){ | |
let createSnapshotParams = { | |
DBSnapshotIdentifier: this.getIdentifier(), | |
DBInstanceIdentifier: this.dbInstanceIdentifier | |
}; | |
try{ | |
return this.rds.createDBSnapshot(createSnapshotParams).promise(); | |
} catch(err) { | |
console.error("Failed to create DB snapshot", err); | |
throw err; | |
} | |
} | |
async exportToS3(DBSnapshotIdentifier){ | |
let waitSnapshotParams = { | |
DBSnapshotIdentifier, | |
SnapshotType: "manual" | |
}; | |
try{ | |
//waiter service - uses the describeDbSnapshot function on the identifier and runs in cycle every n secs until the status says `available` | |
await this.rds.waitFor('dBSnapshotAvailable', waitSnapshotParams).promise(); | |
} catch (e) { | |
console.error("Create snapshot wait service failed", e); | |
throw e; | |
} | |
let params = { | |
ExportTaskIdentifier: this.getIdentifier(), | |
IamRoleArn: this.s3UploaderRoleArn, | |
KmsKeyId: this.snapshotEncryptKeyId, | |
S3BucketName: this.destinationS3Name, | |
SourceArn: `arn:aws:rds:${this.region}:${this.accountId}:snapshot:${DBSnapshotIdentifier}` | |
}; | |
try{ | |
await this.rds.startExportTask(params).promise(); | |
} catch(err) { | |
console.error("Failed to start export of RDS snapshot to S3", err); | |
throw err; | |
} | |
} | |
} | |
module.exports = ExportDbSnapshotToS3; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment