Reputation: 1268
basically I want to create a button in a spreadsheet which would run the equivalent of the following command
gcloud compute project-info add-metadata --project ${project} --metadata "test_label=test_value"
Is it possible? I'm not very familiar with the google javascript libraries.
Upvotes: 0
Views: 248
Reputation: 2930
At the moment of this answer, unfortunately, there is no method or class in Apps Script to change the metadata of a Google Cloud project. However, you can get and modify the document, script or user metadata using the class Properties Service.
However, if you want to edit your GCP project properties programmatically you will need to use Google Cloud API as it lets you modify these properties either from gcloud
, its API or throughout the console.
Upvotes: 0
Reputation: 1268
So basically thanks to Mateo's pointers I was able to update the project metadata using this script:
function alex_test_function() {
// get existing oauth token
var theAccessTkn = ScriptApp.getOAuthToken();
// get existing project metadata
var response =
UrlFetchApp.fetch('https://compute.googleapis.com/compute/v1/projects/myProject', {
headers: {
Authorization: 'Bearer ' + theAccessTkn
}
});
var data = JSON.parse(response.getContentText());
var metadata = data.commonInstanceMetadata
fingerprint = metadata.fingerprint;
new_metadata_items = metadata.items;
// update metadata
var timestamp = new Date().getTime()
setMetaKey(new_metadata_items, Session.getActiveUser().getEmail().split("@")[0], timestamp)
var formData = {
'fingerprint': fingerprint,
'items': new_metadata_items
};
var postresponse = UrlFetchApp.fetch("https://compute.googleapis.com/compute/v1/projects/myProject/setCommonInstanceMetadata", {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(formData),
'headers': {
Authorization: 'Bearer ' + theAccessTkn
}
});
}
function setMetaKey(metadata, key, value){
// Function to add metadata or update if exists
for (var i = 0; i < metadata.length; i++) {
if (metadata[i].key === key) {
metadata[i].value = value;
return;
}
}
metadata.push({key:key, value:value});
}
some gotchas, we need to set OAuth scopes to the AppScript manifest
{
"timeZone": "America/New_York",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": [
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/script.external_request"]
}
and the user who's running the script needs to have permissions to edit the project metadata in the GCP project.
Upvotes: 2