|
const {Buffer} = require('safe-buffer'); |
|
const Compute = require('@google-cloud/compute'); |
|
const compute = new Compute(); |
|
|
|
/** |
|
* Resize Compute Engine instance-group. |
|
* |
|
* Expects a PubSub message with JSON-formatted event data containing the |
|
* following attributes: |
|
* zone - the GCP zone the instances are located in. |
|
* name - the name of a instance group. |
|
* size - the number of instance(s) to resize |
|
* |
|
* |
|
* @param {!object} event Cloud Function PubSub message event. |
|
* @param {!object} callback Cloud Function PubSub callback indicating completion. |
|
*/ |
|
exports.resizeInstanceGroupPubSub = (event, context, callback) => { |
|
try { |
|
const payload = _validatePayload( |
|
JSON.parse(Buffer.from(event.data, 'base64').toString()) |
|
); |
|
|
|
const zone = compute.zone(payload.zone); |
|
const instanceGroupManager = zone.instanceGroupManager(payload.name); |
|
instanceGroupManager.resize(payload.size).then(data => { |
|
// Operation pending. |
|
const operation = data[0]; |
|
const apiResponse = data[1]; |
|
console.log(apiResponse); |
|
return operation.promise(); |
|
}).then(() => { |
|
// Operation complete. Instance successfully stopped. |
|
const message = 'Successfully resize to ' + payload.size + ' the instance group named ' + payload.name; |
|
console.log(message); |
|
callback(null, message); |
|
}).catch(err => { |
|
console.log(err); |
|
callback(err); |
|
}); |
|
} catch (err) { |
|
console.log(err); |
|
callback(err); |
|
} |
|
}; |
|
|
|
|
|
/** |
|
* Validates that a request payload contains the expected fields. |
|
* |
|
* @param {!object} payload the request payload to validate. |
|
* @return {!object} the payload object. |
|
*/ |
|
function _validatePayload(payload) { |
|
if (!payload.zone) { |
|
throw new Error(`Attribute 'zone' missing from payload`); |
|
} else if (!payload.name) { |
|
throw new Error(`Attribute 'name' missing from payload`); |
|
} else if (!payload.size) { |
|
throw new Error(`Attribute 'size' missing from payload`); |
|
} |
|
return payload; |
|
} |
I'm so sorry. How to use this example to change the Instance group
I want to change the Instance group - Number of instances