通过应用程序脚本更新GCP元数据



基本上,我想在电子表格中创建一个按钮,该按钮将运行以下命令

gcloud compute project-info add-metadata --project ${project} --metadata "test_label=test_value"

有可能吗?我对谷歌javascript库不是很熟悉。

因此,基本上得益于Mateo的指针,我能够使用以下脚本更新项目元数据:

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});
}

有些问题,我们需要将OAuth范围设置为AppScript清单

{
"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"]
}

并且运行脚本的用户需要具有编辑GCP项目中的项目元数据的权限。

  • 我没有对作用域进行太多实验,可以用更窄的作用域执行脚本,而不是https://www.googleapis.com/auth/compute

不幸的是,在给出这个答案的时候,Apps Script中没有方法或类来更改谷歌云项目的元数据。但是,您可以使用类Properties Service获取和修改文档、脚本或用户元数据。

但是,如果您想以编程方式编辑GCP项目属性,则需要使用Google Cloud API,因为它允许您从gcloud、其API或整个控制台修改这些属性。

最新更新