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

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

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

是否可以?我对谷歌 javascript 库不是很熟悉。


GCT1015
浏览 114回答 2
2回答

慕斯709654

所以基本上感谢 Mateo 的指点,我能够使用这个脚本更新项目元数据:function alex_test_function() {&nbsp;// get existing oauth token&nbsp;var theAccessTkn = ScriptApp.getOAuthToken();&nbsp;// get existing project metadata&nbsp;var response =&nbsp;&nbsp;UrlFetchApp.fetch('https://compute.googleapis.com/compute/v1/projects/myProject', {&nbsp; &nbsp;headers: {&nbsp; &nbsp; &nbsp;Authorization: 'Bearer ' + theAccessTkn&nbsp; &nbsp;}&nbsp;});&nbsp;var data = JSON.parse(response.getContentText());&nbsp;var metadata = data.commonInstanceMetadata&nbsp;fingerprint = metadata.fingerprint;&nbsp;new_metadata_items = metadata.items;// update metadata&nbsp;var timestamp = new Date().getTime()&nbsp;setMetaKey(new_metadata_items, Session.getActiveUser().getEmail().split("@")[0], timestamp)&nbsp;var formData = {&nbsp; 'fingerprint': fingerprint,&nbsp; 'items': new_metadata_items&nbsp; };&nbsp;var postresponse = UrlFetchApp.fetch("https://compute.googleapis.com/compute/v1/projects/myProject/setCommonInstanceMetadata", {&nbsp; 'method' : 'post',&nbsp; 'contentType': 'application/json',&nbsp; 'payload' : JSON.stringify(formData),&nbsp; 'headers': {&nbsp; &nbsp; Authorization: 'Bearer ' + theAccessTkn&nbsp; &nbsp;}&nbsp; });}function setMetaKey(metadata, key, value){&nbsp; // Function to add metadata or update if exists&nbsp; for (var i = 0; i < metadata.length; i++) {&nbsp; &nbsp; if (metadata[i].key === key) {&nbsp; &nbsp; &nbsp; metadata[i].value = value;&nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; }&nbsp; }&nbsp; metadata.push({key:key, value:value});}一些陷阱,我们需要将 OAuth 范围设置为 AppScript 清单{&nbsp; "timeZone": "America/New_York",&nbsp; "dependencies": {&nbsp; },&nbsp; "exceptionLogging": "STACKDRIVER",&nbsp; "runtimeVersion": "V8",&nbsp; "oauthScopes": [&nbsp; &nbsp; "https://www.googleapis.com/auth/userinfo.email",&nbsp;&nbsp; &nbsp; "https://www.googleapis.com/auth/compute",&nbsp;&nbsp; &nbsp; "https://www.googleapis.com/auth/script.external_request"]}并且运行脚本的用户需要具有编辑 GCP 项目中的项目元数据的权限。我没有对范围进行很多实验,可以用更窄的范围而不是https://www.googleapis.com/auth/compute来执行脚本

江户川乱折腾

不幸的是,在回答这个问题时,Apps 脚本中没有方法或类来更改 Google Cloud 项目的元数据。但是,您可以使用Properties Service类获取和修改文档、脚本或用户元数据。但是,如果您想以编程方式编辑 GCP 项目属性,则需要使用Google Cloud API,因为它允许您从gcloud、其 API 或整个控制台修改这些属性。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript