所以基本上感谢 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来执行脚本我想显示“Orange”2 秒,“Kiwi”或 1 秒,“Mango”3 秒。这是我的尝试,它显示静止的“橙色:2000”,而我希望它根据指定的秒数翻转。我错过了什么?
月关宝盒
慕虎7371278
慕的地8271018
相关分类