How do you create a google cloud project and service account using node js?
How do you programmatically serve a google cloud project, enable the API and create a service account with node js?
thanks
Chris
The answer lies in the REST API.
Assuming you are using Cloud Shell, first install the Node.JS client library by running:
npm install googleapis --save
To create a project, you can use the resource manager API method "projects.create" as shown in the Node.JS code sample. Replace my-project-id
with desired project ID and my-project-name
desired 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));
});
});
Likewise, you can use the Cloud IAM API 'projects.serviceAccounts.create' method to create service accounts. Replace my-project-id
with the project ID that the service account will be associated with, and my-service-account
the desired 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));
});
});
Then, to enable an API or service, use the API 'services.enable' method with the service . In this case, I will enable Cloud Pub/Sub API . Replace 123
with your item number:
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));
});
});
Alternatively, you can use the "services.batchEnable" method to enable multiple APIs in one call. You can find the full list of APIs that can be enabled here .
You can define each call:
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);
});
}
Note that you should adapt the code to your needs, simplify it, and modify or add any other parameters required by the API call.