Purpose:
When the production environment backup fails, receive an email notification.
Requirements:
SendGrid API
TODO:
- Store
SENDGRID_API_KEY
outside of the source code - Query Platform.sh API to pull project admins instead of hardcoding email address values.
/**
* FILE: backup-notifications.js
* AUTHOR: travis.raup@platform.sh
* DESCRIPTION: Example activity script for sending an email notification upon an environment backup activity failure via SendGrid API
* INSTALLATION: platform integration:add --type script --file ./backup-notifications.js --events="environment.backup" --environments=master --states=complete
*/
function sendEmail(title, message, result){
/*
* Only send an email notification when a backup fails
*/
if (result == 'success') {
console.log("Successful backup, no notification necessary")
return
}
/*
* Hardcode the SENDGRID API KEY
*/
var SENDGRID_API_KEY = '<SENDGRID_API_KEY>';
if (!SENDGRID_API_KEY) {
throw new Error('You must define a SendGrid API Key project variable.');
}
var body = JSON.stringify({
"personalizations": [ {
"to": [{
"email": "<EMAIL_TO>"
}],
"subject": "Activity Script: " + title + " Notification"
}],
"from": {
"email": "<EMAIL_FROM>"
},
"content": [{
"type": "text/plain",
"value": message
}]
});
var resp = fetch('https://api.sendgrid.com/v3/mail/send',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + SENDGRID_API_KEY,
},
body: body,
});
if (!resp.ok) {
console.log("SendGrid failed to send.");
}
}
/*
* Example dump for `project` and `activity` objects
* Examine output via `platform integration:activity:log <integrationID> <activityID>
*
* # uncomment below
* console.log(JSON.stringify(project, null, 2));
* console.log(JSON.stringify(activity, null, 2));
*/
sendEmail(activity.text, activity.log, activity.result);