Friday, September 2nd 2016 (almost 2 years ago)

Environment Variables and Secrets

Guillermo Rauch (@rauchg)

Today we are introducing a new option, a new command and a new API to manage your deployment's environment variables and secrets.

As of now 0.23.0, now help has two new examples: Storing a secret and deploying with env vars.

Let's first look at now secret.

now's secret management allows you to store sensitive data needed by your apps to function (such as API tokens or passwords) in a secure way.

Once you store a secret, its contents are no longer accessible directly by anyone. They can only be exposed to deployments as enviroment variables, which we'll show below.

Let's create a secret with an API key:

now secret add acme-api-key my-value-here

Once it's created, you can rename it withnow secret rename or delete it completely with now secret rm. For more examples, run now help secret.

To expose environment variables to deployments we introduced the -e flag.

To demonstrate it, I'll create a Node.js project that prints out a variable MY_VARIABLE to the browser.

Let's create a new directory for it:

▲ mkdir my-node-project
▲ cd my-node-project

Inside my-node-project, create a package.json:

{
"name": "my-node-project",
"dependencies": {
  "sign-bunny": "1.0.0"
},
"scripts": {
  "start": "node index"
}
}

And a index.js containing:

const http = require('http')
const bunny = require('sign-bunny')
http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end(bunny(process.env.MY_VARIABLE))
}).listen()

So, how do we populate process.env.MY_VARIABLE? When deploying, use the -e option:

▲ now -e MY_VARIABLE="Hello world :)"

Then I ran:

▲ now alias my_deployment_url_here my-node-bunny

… and here it is!

In order to make the value of the variable a secret, you can invoke the -e using @ as the value followed by the name or id of your secret:

▲ now -e MY_VARIABLE=@acme-api-key

You can also include -e multiple times:

▲ now -e API_KEY=@my-key -e APP_NAME="ZEIT, Inc"

And we also have the capability to inherit from your shell's environment. To do so, just skip the =value part:

▲ now -e MY_SHELL_VAR

How about other programming languages? The same mechanism applies to any project with a Dockerfile. The variables you include will be available to your RUN andCMD instructions.

Finally, our API users will find the new /now/secrets REST endpoints useful.