node.jshashicorp-vaultmoleculer

How to run Vault from my app instead of CLI?


I'm trying to start a Vault service in my NodeJS app. Using CLI to use Vault is ok, but i need it to work automatically when the app is started. I try this

    async started(ctx) {

        var options = {
            apiVersion: 'v1', // default
            endpoint: 'http://127.0.0.1:8500', // default

          };
           
            // get new instance of the client
            var vault = require("node-vault")(options);

            // init vault server
            vault.init({ secret_shares: 1, secret_threshold: 1 })
            .then( (result) => {
            var keys = result.keys;
            // set token for all following requests
            vault.token = result.root_token;
            // unseal vault server
            return vault.unseal({ secret_shares: 1, key: keys[0] })
            })
            .catch(console.error);

            // see if it is ok
            vault.status()
                .then (res => {
                  console.log('STATuuuuuuuuuuusS', res);
                  })
                  .catch((err) => {
                    console.log("errrrrrreur status");
                    console.error(err.message);
            });

But i've got this error:

RequestError: Error: connect ECONNREFUSED 127.0.0.1:8500
[...]
  cause: Error: connect ECONNREFUSED 127.0.0.1:8500
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16) {
    errno: 'ECONNREFUSED',
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 8500
  },

If i run this before, it worked vault server -config=config.hcl

Even when i kill it, it seems to work without reloading it. I'm missing something here, for sure :) I'm wondering if node-vault should start Vault server ? If not, i'm wondering how to start the Vault server from the app and not the CLI ?

If you know the good way to do it, or have clues, i'm all ears.

Nicolas


Solution

  • No, usually the code shouldn't start the server. Yes, your code is working correctly. If you have not started the server, the error means that it is impossible to connect to the specified IP address and port, they are closed. The vault server has nothing to do with it, the same behavior will be the database server or any other.