Using gcloud commands in nodejs application

Viewed 767

Some gcloud commands don't have API or client library support (for example - this one).

In these cases, is there a simple way to run gcloud commands from a nodejs application?

3 Answers

The gcloud endpoints service commands for IAM policy are difficult for me to check quickly but, if IIRC (and if this is similar to gcloud projects commands for IAM policy), it's not that there's no API, but that there's no single API call.

What you can always do with gcloud is append --log-http to see what happens beneath the covers. With IAM policy mutations (off-top-of-head), you get the policy, mutate it, and then apply the changes back using the etag the GET gave you. The backend checks the policy's state (the etag is like a hash of the policy) and, if it's unchanged, you can make the change.

If this is what's happening here, you should be able to repro the functionality in NodeJS using the existing (!) APIs and, if you're using API Client Libraries (rather than Cloud Client libraries), the functionality will be available.

Apart from the complexity involved in shelling out to gcloud, you'll need to also authenticate it and then you'll need to (un)marshal data to the shell and manage errors. Ergo, it's messy and generally discouraged.

In node.js ,we have child_process module. As the name suggests the child_process provides function like spawn or exec that creates new child process that executes shell command like independent process. spawn is a function that takes the main command as first argument and other command line options as an array values in place of second parameter. So with respect to link that you share, you might end-up writing something like this :

const { spawn } = require("child_process");
const listening = spawn('gcloud', ['endpoints', 'services', 'blah', '--option','someValue']);

listening.stdout.on("data", data => {
    console.log(`stdout: ${data}`);
});

listening.stderr.on("data", data => {
    console.log(`stderr: ${data}`);
});

listening.on('error', (error) => {
    console.log(`error: ${error.message}`);
});

References : https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

I'm not sure this directly answers your question but there is an npm package that can help you run unix commands from within the app.

Check out shell.js

Related