I am testing a Cloud Function in GCP and I want to modify labels of my compute instance with Cloud Function i.e. change label "status=active" to "status=tobedeleted".
Is there a way to do it with Cloud Function and node.js ?
Looks as if the method compute.instances.setLabels requires additional libraries ?
I already created Cloud Function to stop/start instances.
Here is the error :
resource: {…}
severity: "ERROR"
textPayload: "{ Error: Login Required at Gaxios.request (/srv/node_modules/googleapis-common/node_modules/gaxios/build/src/gaxios.js:70:23) at at process._tickDomainCallback (internal/process/next_tick.js:229:7) response: { config: { url: 'https://www.googleapis.com/compute/v1/projects/wpress-v1/zones/us-central1-a/instances/instance-1/setLabels?labels%5Bis-scheduled%5D=manual', method: 'POST', paramsSerializer: [Function], headers: [Object], params: [Object], validateStatus: [Function], retry: true, responseType: 'json', retryConfig: [Object] }, data: { error: [Object] },
Then here is my code :
const Compute = require('@google-cloud/compute');
/*const compute = new Compute();*/
const {google} = require('googleapis');
/*const google = require('@google-cloud/googleapis');*/
var compute = google.compute('v1');
exports.setInstanceScheduleMode = (event, context, callback) => {
try {
const payload = _validatePayload(
JSON.parse(Buffer.from(event.data, 'base64').toString())
);
var request = {
project: 'wpress-v1',
zone: 'us-central1-a',
instance: 'instance-1',
labels: {
"is-scheduled": "manual"
},
auth: google.authClient,
};
compute.instances.setLabels(request, function(err, response) {
if (err) {
console.error(err);
return;
}
console.log(JSON.stringify(response, null, 2));
});
} catch (err) {
console.log(err);
callback(err);
}
};
// [END functions_start_instance_pubsub]
function _validatePayload(payload) {
if (!payload.zone) {
throw new Error(`Attribute 'zone' missing from payload`);
} else if (!payload.label) {
throw new Error(`Attribute 'label' missing from payload`);
}
else if (!payload.instance) {
throw new Error(`Attribute 'instance' missing from payload`);
}
return payload;
}
function authorize(callback) {
google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
}).then(client => {
callback(client);
}).catch(err => {
console.error('authentication failed: ', err);
});
}