【问题标题】:Update GCP metadata via apps script通过应用脚本更新 GCP 元数据
【发布时间】:2021-01-01 13:35:00
【问题描述】:

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

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

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

【问题讨论】:

  • 如果有相同的http rest api,可以通过urlfetch
  • 所以您的意图基本上是使用 Apps 脚本修改 GCP 项目属性(元数据)?
  • @MateoRandwolf 是的

标签: javascript google-apps-script google-cloud-platform


【解决方案1】:

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

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

我希望这对您有所帮助。让我知道您是否需要其他任何内容,或者您​​是否不理解某些内容。 :)

【讨论】:

    【解决方案2】:

    所以基本上感谢 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});
    }
    

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

    {
      "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 项目中编辑项目元数据的权限。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-25
      • 2014-06-15
      • 1970-01-01
      • 2020-03-03
      • 2021-07-16
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多