如何使用Node.js编程方式自动创建谷歌云项目、启用API并创建服务账户?
谢谢
Chris
如何使用Node.js编程方式自动创建谷歌云项目、启用API并创建服务账户?
谢谢
Chris
答案在REST API中。
假设您正在使用Cloud Shell,首先运行以下命令安装Node.JS客户端库:
npm install googleapis --save
my-project-id
替换为所需的项目 ID,并将 my-project-name
替换为所需的项目名称。const {google} = require('googleapis');
var cloudResourceManager = google.cloudresourcemanager('v1');
authorize(function(authClient) {
var request = {
resource: {
"projectId": "my-project-id", // TODO
"name": "my-project-name" // TODO
},
auth: authClient,
};
cloudResourceManager.projects.create(request, function(err, response) {
if (err) {
console.error(err);
return;
}
console.log(JSON.stringify(response, null, 2));
});
});
my-project-id
替换为与服务帐号关联的项目ID,将my-service-account
替换为所需的服务帐号ID:const {google} = require('googleapis');
var iam = google.iam('v1');
authorize(function(authClient) {
var request = {
name: 'projects/my-project-id', // TODO
resource: {
"accountId": "my-service-account" // TODO
},
auth: authClient,
};
iam.projects.serviceAccounts.create(request, function(err, response) {
if (err) {
console.error(err);
return;
}
console.log(JSON.stringify(response, null, 2));
});
});
然后,要启用API或服务,请使用Service Usage API的'services.enable'方法。在这种情况下,我将启用Cloud Pub/Sub API。请将123
替换为您的项目编号:
const {google} = require('googleapis');
var serviceUsage = google.serviceusage('v1');
authorize(function(authClient) {
var request = {
name: "projects/123/services/pubsub.googleapis.com", // TODO
auth: authClient,
};
serviceUsage.services.enable(request, function(err, response) {
if (err) {
console.error(err);
return;
}
console.log(JSON.stringify(response, null, 2));
});
});
您可以使用‘services.batchEnable’方法来在单个调用中启用多个API。您可以在此处找到可以启用的所有API的完整列表。
您可以使用以下方式定义每个调用:
function authorize(callback) {
google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
}).then(client => {
callback(client);
}).catch(err => {
console.error('authentication failed: ', err);
});
}
请注意,您应该根据自己的需求调整代码,简化它,并修改或添加任何您对 API 调用需要的参数。
部署管理器允许您提供所有这些资源,并可以通过API触发。
甚至在GitHub上有一个官方示例,可以执行以下操作:
记得替换config.yaml
文件中的值。要获取计费账户ID,您可以使用billingAccounts.list方法,要获取组织ID,您可以使用gcloud organizations list
命令。
gcloud deployment-manager deployments create
命令测试部署,并通过添加--log-http
标志获取发送到Deployments: insert API的请求正文。请注意,您感兴趣的是第一个请求,其他请求是为了检查操作进度而进行的。