Skip to content

Instantly share code, notes, and snippets.

@tomlarkworthy
Created August 18, 2019 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomlarkworthy/c2dc0428d3cd357e7a757c2812f46703 to your computer and use it in GitHub Desktop.
Save tomlarkworthy/c2dc0428d3cd357e7a757c2812f46703 to your computer and use it in GitHub Desktop.
Google App Engine Flex toggler
const moment = require("moment");
const {google} = require('googleapis');
const gae = google.appengine('v1');
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/appengine.admin',
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/cloud-platform.read-only']
});
async function scheduleGAE(pubSubEvent, context) {
const authClient = await auth.getClient();
const versionsResponse = await gae.apps.services.versions.list({
auth: authClient,
appsId: "<APP_ID>",
servicesId: "default",
fields: "versions(id,name,servingStatus)"
});
if (versionsResponse.status == 200) {
const versions = versionsResponse.data.versions;
// find the latest version
const latest = versions.reduce(
(prev, current) => prev.id > current.id ? prev : current,
versions[0]
);
console.log(`Latest version is ${latest.name} with status ${latest.servingStatus}`);
const time = moment(context.timestamp);
const newStatus = time.hour() % 12 == 0 ? "SERVING" : "STOPPED";
console.log(`Patching to status ${newStatus}`);
return gae.apps.services.versions.patch({
auth: authClient,
appsId: "<APP_ID>",
servicesId: "default",
versionsId: latest.id,
updateMask: "servingStatus",
requestBody: {
servingStatus: newStatus
}
});
} else {
throw new Error(`Error ${versionsResponse.statusText}: ${versionsResponse.statusText}`);
}
}
module.exports = {
scheduleGAE: scheduleGAE
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment