# envkey-cmd

> Executes a command using the environment variables from a provided ENVKEY

Latest version **10.1.6** (published 2021-02-16) · MIT license · 0 weekly downloads

## Install

```sh
npm install envkey-cmd
pnpm add envkey-cmd
yarn add envkey-cmd
bun add envkey-cmd
```

Provides the command `envkey-cmd`.

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 10.1.6 |
| Published | 2021-02-16 |
| First published | 2021-02-15 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Node | >=8.0.0 |
| Dependencies | 3 |
| Unpacked size | 38 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Todd Bluhm |
| Maintainers | guycreate |
| Keywords | env, environment, cli, command, cmd, execute, run, file, variables, config |

## Links

- npm: https://www.npmjs.com/package/envkey-cmd
- Repository: https://github.com/iopa-io/envkey-cmd
- Homepage: https://github.com/iopa-io/envkey-cmd#readme
- Issues: https://github.com/iopa-io/envkey-cmd/issues
- npm.io page: https://npm.io/package/envkey-cmd

## Dependencies (3)

- [envkey](https://npm.io/package/envkey.md) ^1.2.9
- [commander](https://npm.io/package/commander.md) ^5.0.0
- [cross-spawn](https://npm.io/package/cross-spawn.md) ^7.0.0

## Alternatives

- [replicas-cli](https://npm.io/package/replicas-cli.md) — 3.0K weekly downloads
- [env-contract](https://npm.io/package/env-contract.md) — 133 weekly downloads
- [@openveo/api](https://npm.io/package/@openveo/api.md) — 61 weekly downloads
- [@ryniaubenpm2/cumque-error-reiciendis](https://npm.io/package/@ryniaubenpm2/cumque-error-reiciendis.md) — 54 weekly downloads
- [ts-global-type-extra](https://npm.io/package/ts-global-type-extra.md) — 11 weekly downloads

## Recent versions

- 10.1.6 (latest) — 2021-02-16
- 10.1.5 — 2021-02-16
- 10.1.2 — 2021-02-15
- 10.1.1 — 2021-02-15
- 10.1.0 — 2021-02-15

## README

[![Linux Tests](https://github.com/iopa-io/envkey-cmd/workflows/linux%20tests/badge.svg)](https://github.com/iopa-io/envkey-cmd/actions?query=workflow%3A%22linux%20tests%22)
[![Windows Tests](https://github.com/iopa-io/envkey-cmd/workflows/windows%20tests/badge.svg)](https://github.com/iopa-io/envkey-cmd/actions?query=workflow%3A%22windows%20tests%22)
[![Coverage Status](https://badgen.net/coveralls/c/github/iopa-io/envkey-cmd)](https://coveralls.io/github/iopa-io/envkey-cmd?branch=master)
[![npm](https://badgen.net/npm/v/envkey-cmd)](https://www.npmjs.com/package/envkey-cmd)
[![npm](https://badgen.net/npm/dm/envkey-cmd)](https://www.npmjs.com/package/envkey-cmd)
[![License](https://badgen.net/github/license/iopa-io/envkey-cmd)](https://github.com/iopa-io/envkey-cmd/blob/master/LICENSE)
[![TS-Standard - Typescript Standard Style Guide](https://badgen.net/badge/code%20style/ts-standard/blue?icon=typescript)](https://github.com/toddbluhm/ts-standard)
[![Dependabot badge](https://badgen.net/dependabot/iopa-io/envkey-cmd?icon=dependabot)](https://dependabot.com/)

# envkey-cmd

A simple node program for executing commands using an environment from a given ENVKEY

Simply set an ENVKEY variable in the existing environment or provide as a command line argument, and then the 
given child process will be executed will the full environment corresponding to this ENVKEY

This is a simple wrapper around ['envkey'](https://www.npmjs.com/package/envkey) with all the child process spawn logic forked from ['envkey-cmd'](https://github.com/toddbluhm/env-cmd)

## 💾 Install

`npm install envkey-cmd` or `npm install -g envkey-cmd`

## ⌨️ Basic Usage

**Environment**

```yaml
ENVKEY=wYv78UmHsfEu6jSqMZrU-3w1kwyF35nRYwsAJ
```
**Package.json**

```json
{
  "scripts": {
    "test": "envkey-cmd mocha -R spec"
  }
}
```

**Terminal**

```sh
./node_modules/.bin/envkey-cmd node index.js
```



## 📜 Help

```text
Usage: _ [options] <command> [...args]

Options:
  -v, --version                       output the version number
  -e, --envkey [ENVKEY]               The ENVKEY to use; defaults to process.env.ENVKEY
  --permitted [var1,var1,...]         whitelist of permitted vars (useful for client-side config) - defaults to  all
  --no-override                       Do not override existing environment variables
  --silent                            Ignore any envkey-cmd errors and only fail on executed program failure.
  --use-shell                         Execute the command in a new shell with the given environment
  --verbose                           Print helpful debugging information
  -x, --expand-envs                   Replace $var in args and command with environment variables
  -h, --help                          output usage information
```

## 🔬 Advanced Usage

### Using ENVKEY provided in command line

**Terminal**

```sh
./node_modules/.bin/envkey-cmd -e ENVKEY=wYv78UmHsfEu6jSqMZrU-3w1kwyF35nRYwsAJ node index.js
```

### `--permitted` option

Whitelist of permitted vars (useful for client-side config) - defaults to  all

```sh
./node_modules/.bin/envkey-cmd -e ENVKEY=wYv78UmHsfEu6jSqMZrU-3w1kwyF35nRYwsAJ --permitted FIREBASE_TOKEN,FIREBASE_URI node index.js
```

### `--no-override` option

Prevents overriding of existing environment variables on `process.env` and within the current
environment.

### `--use-shell`

Executes the command within a new shell environment. This is useful if you want to string multiple
commands together that share the same environment variables.

**Terminal**

```sh
./node_modules/.bin/envkey-cmd -f ./test/.env --use-shell "npm run lint && npm test"
```

### `-x` expands vars in arguments

EnvKeyCmd supports expanding `$var` values passed in as arguments to the command. The allows a user
to provide arguments to a command that are based on environment variable values at runtime.

**NOTE:** You must escape the `$` character with `\` or your terminal might try to auto expand it before passing it to `envkey-cmd`.

**Terminal**

```sh
# $VAR will be expanded into the env value it contains at runtime
./node_modules/.bin/envkey-cmd -x node index.js --arg=\$VAR
```

or in `package.json` (use `\\` to insert a literal backslash)
```json
{
  "script": {
    "start": "envkey-cmd -x node index.js --arg=\\$VAR"
  }
}
```


### `--silent` suppresses envkey-cmd errors

EnvKeyCmd supports the `--silent` flag the suppresses all errors generated by `envkey-cmd`
while leaving errors generated by the child process and cli signals still usable. This
flag is primarily used to allow `envkey-cmd` to run in environments where the `.env`
file might not be present, but still execute the child process without failing
due to a missing file.


## 💽️ ENVKEYS
An addition variable ENVKEYS is supplied in the provided environment with the keynames of all
the variables downloaded from the ENVKEY (filtered to the permitted whitelist if provided).

This can be useful for providing to webpack or other utilities that need to know which of the
process.env variables to use.

```js
const webpack = require('webpack')

const secretKeys = process.env.ENVKEYS.split(',').reduce((accum, key) => {
    accum[key] = false
    return accum
}, {})

const plugins = [
    new webpack.EnvironmentPlugin({
        ...secretKeys,
        NODE_ENV: process.env.NODE_ENV || 'production'
    })
]
```


## 💽️ Environment Files

If you want to provide ENVKEY in an environment file and/or include other environment variables not provided from
the cloud ENVKEY, then use `env-cmd` right before this program.

**Package.json**

```json
{
  "scripts": {
    "test": "env-cmd -f ../.config/env-secrets.json envkey-cmd mocha -R spec"
  }
}
```

## 🗂 Path Rules

This lib attempts to follow standard `bash` path rules. The rules are as followed:

Home Directory = `/Users/test`

Working Directory = `/Users/test/Development/app`

| Type | Input Path | Expanded Path |
| -- | -- | ------------- |
| Absolute | `/some/absolute/path.env` | `/some/absolute/path.env` |
| Home Directory with `~` | `~/starts/on/homedir/path.env` | `/Users/test/starts/on/homedir/path.env` |
| Relative | `./some/relative/path.env` or `some/relative/path.env` | `/Users/test/Development/app/some/relative/path.env` |
| Relative with parent dir | `../some/relative/path.env` | `/Users/test/Development/some/relative/path.env` |

## 🛠 API Usage

### `EnvKeyCmd`

A function that executes a given command in a new child process with the given environment and options

- **`options`** { `object` }
  - **`command`** { `string` }: The command to execute (`node`, `mocha`, ...)
  - **`commandArgs`** { `string[]` }: List of arguments to pass to the `command` (`['-R', 'Spec']`)
  - **`envKey`** { `string` }: The ENVKEY to use (defaults to process.env.ENVKEY)
  - **`permitted`** { `string[]` }: Whitelist of environment variables to select from the downloaded environment
  - **`options`** { `object` }
    - **`expandEnvs`** { `boolean` }: Expand `$var` values passed to `commandArgs` (default: `false`)
    - **`noOverride`** { `boolean` }: Prevent `.env` file vars from overriding existing `process.env` vars (default: `false`)
    - **`silent`** { `boolean` }: Ignore any errors thrown by envkey-cmd, used to ignore missing file errors (default: `false`)
    - **`useShell`** { `boolean` }: Runs command inside a new shell instance (default: `false`)
    - **`verbose`** { `boolean` }: Prints extra debug logs to `console.info` (default: `false`)
  - **Returns** { `Promise<Record<string, string>>` }: key is env var name and value is the env var value

### `GetEnvVars`

A function that parses environment variables from a given ENVKEY

 { envKey: string, permitted?: string[], verbose?: boolean }

- **`options`** { `object` }
  - **`envKey`** { `string` }: The ENVKEY to use (defaults to process.env.ENVKEY)
  - **`permitted`** { `string[]` }: Whitelist of environment variables to select from the downloaded environment
  - **`verbose`** { `boolean` }: Prints extra debug logs to `console.info` (default: `false`)
- **Returns** { `Promise<Record<string, string>>` }: key is env var name and value is the env var value

## 🧙 Why

Because scripts shouldnt have to know that the environment variables came from ENVKEY;  they just 
expect them to be there.     The standard ENVKEY approach requires evaling a shell script from 
Github or writing a custom node program that calls 'envkey', whereas this is a standard NPM package that
just works wherever you can execute a shell script.

## 🧬 Related Projects

[`env-cmd`](https://github.com/toddbluhm/envkey-cmd) - Original source without ENVKEY
[`envkey`](https://github.com/envkey/envkey-node) - The Node wrapper around the ENVKEY cloud fetch logic
[`envkey-source`](https://github.com/envkey/envkey-source) - The equivalent logic but requires multiple steps to 
download the script and `eval` it, whereas `envkey-cmd` can just be included as an npm dependency
[`cross-env`](https://github.com/kentcdodds/cross-env) - Cross platform setting of environment scripts

## 🎊 Special Thanks

Special thanks to [`envkey-cmd`](https://github.com/toddbluhm/envkey-cmd) for all the hard work, [`envkey`](https://github.com/envkey/envkey-node) for the custom fetch logic that works on multiple platforms, and [`cross-env`](https://github.com/kentcdodds/cross-env) for inspiration (uses the same `cross-spawn` lib underneath too

## 📋 Contributing Guide

 Please make sure you add appropriate test cases for any features
added. Before opening a PR please make sure to run the following scripts:

- `npm run lint` checks for code errors and format according to [ts-standard](https://github.com/toddbluhm/ts-standard)
- `npm test` make sure all tests pass
- `npm run test-cover` make sure the coverage has not decreased from current master

---
_Source: https://npm.io/package/envkey-cmd · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
