慕斯709654
所以基本上感谢 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来执行脚本