Chr*_*ley 3 node.js google-cloud-platform
如何以编程方式配置 Google Cloud 项目、启用 API 并使用 Node js 创建服务帐户?
谢谢
克里斯
答案就在 REST API 中。
\n\n假设您\xe2\x80\x99 使用 Cloud Shell,首先通过运行以下命令安装 Node.JS 客户端库:
\n\nnpm install googleapis --save\nRun Code Online (Sandbox Code Playgroud)\n\n要创建项目,您可以使用资源管理器 API 方法 \xe2\x80\x98projects.create\xe2\x80\x98,如 Node.JS 代码示例中所示。替换my-project-id为所需的项目 ID 和my-project-name所需的项目名称:
const {google} = require(\'googleapis\');\nvar cloudResourceManager = google.cloudresourcemanager(\'v1\');\n\nauthorize(function(authClient) {\n  var request = {\n    resource: {\n      "projectId": "my-project-id", // TODO\n      "name": "my-project-name" // TODO\n    },\n    auth: authClient,\n  };\n\n  cloudResourceManager.projects.create(request, function(err, response) {\n    if (err) {\n      console.error(err);\n      return;\n    }\n    console.log(JSON.stringify(response, null, 2));\n  });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n同样,您可以使用Cloud IAM API \xe2\x80\x98projects.serviceAccounts.create\xe2\x80\x99 方法来创建服务帐户。替换my-project-id为与服务帐户关联的项目 ID,以及my-service-account所需的服务帐户 ID:
const {google} = require(\'googleapis\');\nvar iam = google.iam(\'v1\');\n\nauthorize(function(authClient) {\n  var request = {\n    name: \'projects/my-project-id\', // TODO\n    resource: {\n      "accountId": "my-service-account" // TODO\n    },\n    auth: authClient,\n  };\n\n  iam.projects.serviceAccounts.create(request, function(err, response) {\n    if (err) {\n      console.error(err);\n      return;\n    }\n    console.log(JSON.stringify(response, null, 2));\n  });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n然后,要启用 API 或服务,请使用服务使用 API \xe2\x80\x98services.enable\xe2\x80\x99 方法。在本例中,我将启用Cloud Pub/Sub API。替换123为您的项目编号:
const {google} = require(\'googleapis\');\nvar serviceUsage = google.serviceusage(\'v1\');\n\nauthorize(function(authClient) {\n  var request = {\n    name: "projects/123/services/pubsub.googleapis.com", // TODO\n    auth: authClient,\n  };\n\n  serviceUsage.services.enable(request, function(err, response) {\n    if (err) {\n      console.error(err);\n      return;\n    }\n    console.log(JSON.stringify(response, null, 2));\n  });\n});\nRun Code Online (Sandbox Code Playgroud)\n\n或者,您可以使用\xe2\x80\x98services.batchEnable\xe2\x80\x98 方法在一次调用中启用多个 API。您可以在此处找到可启用的 API 的完整列表。
\n\n您可以使用以下方式定义每个调用:
\n\nfunction authorize(callback) {\n  google.auth.getClient({\n    scopes: [\'https://www.googleapis.com/auth/cloud-platform\']\n  }).then(client => {\n    callback(client);\n  }).catch(err => {\n    console.error(\'authentication failed: \', err);\n  });\n}\nRun Code Online (Sandbox Code Playgroud)\n\n请注意,您应该根据您的需求调整代码、简化代码,并修改或添加 API 调用所需的任何其他参数。
\n|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           1675 次  |  
        
|   最近记录:  |