Skip to content

Instantly share code, notes, and snippets.

@rgalite
Created June 17, 2020 08:58
Show Gist options
  • Save rgalite/c45aeaf29fe2a888c67af759ea5d2eef to your computer and use it in GitHub Desktop.
Save rgalite/c45aeaf29fe2a888c67af759ea5d2eef to your computer and use it in GitHub Desktop.
Auto-replace preemptible VMs
const MANAGED_INSTANCE_GROUP_NAME = 'instance-group-2'
const MANAGED_INSTANCE_GROUP_ZONE = 'europe-north1-a'
const MANAGED_INSTANCE_GROUP_TEMPLATE_NAME_ONDEMAND = 'global/instanceTemplates/instance-template-ondemand-vms'
const MANAGED_INSTANCE_GROUP_TEMPLATE_NAME_PREEMTIBLE = 'global/instanceTemplates/instance-template-preemptible-vms-1'
const { auth, Compute } = require('google-auth-library')
const fns = {
resize: async () => {
const client = new Compute()
const projectId = await auth.getProjectId()
const apiUrl = `https://compute.googleapis.com/compute/v1/projects/${projectId}/zones/${MANAGED_INSTANCE_GROUP_ZONE}/instanceGroupManagers/${MANAGED_INSTANCE_GROUP_NAME}`
return client.request(
{
url: apiUrl,
method: 'PATCH',
data: {
updatePolicy: {
type: 'PROACTIVE'
},
versions: [
{
instanceTemplate: MANAGED_INSTANCE_GROUP_TEMPLATE_NAME_ONDEMAND,
targetSize: {
fixed: 1
}
},
{
instanceTemplate: MANAGED_INSTANCE_GROUP_TEMPLATE_NAME_PREEMTIBLE
}
]
}
}
)
}
}
const resizeInstanceGroup = async () => {
const response = await fns.resize()
console.log(response.data)
return response.data
}
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event Event payload.
* @param {!Object} context Metadata for the event.
*/
exports.resizeInstanceGroup = (event, context) => {
resizeInstanceGroup().then(res => {
console.log('Success!', res)
process.exit(0)
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment