Skip to content

Using Environment Variables

Tonight I'm giving a talk about YS and YAML to the Toronto DevOps Meetup External link .

What could be more important to a developer than environment variables?!

Let me show you how to use environment variables in YS and in your YAML files.

The Environment is just a Simple Map🔗

A shell environment is just a simple map of strings to strings.

In YS, this mapping is called ENV.

'ENV' is a normal symbol

Later we'll talk about YS symbols (names of variables), but they are just kebab-case alphanumeric strings. Case doesn't matter. By convention however, YS uses all uppercase for special global variables like ENV.

Let's see how to use ENV in YS.

$ $ ys -e 'say: "Hi there. I am $(ENV.USER.uc1())."'
Hi there. I am Ingy.

My system username is ingy, and the environment puts the username in the USER variable:

$ whoami
ingy
$ echo $USER
ingy

The uc1() function converts the first letter to uppercase.

Using Environment Variables in YAML🔗

What if your YAML file could load different values for different environments? For instance it could use different database credentials for dev, test, stage and prod.

Let's see how to do that.

First our main config file:

# config.yaml
YS-v0:
vars =:
  load:
    case ENV.ENVIRONMENT:
      'dev': 'dev-vars.yaml'
      'test': 'test-vars.yaml'
      'staging': 'staging-vars.yaml'
      'prod': 'prod-vars.yaml'
      else:
        die: "The 'ENVIRONMENT' variable must be one of
              'dev', 'test', 'staging', or 'prod'"

# Or just:
vars =: load("$(ENV.ENVIRONMENT)-vars.yaml")

database:
  host:: vars.db-host
  port:: vars.db-port
  user:: vars.db-user
  password:: vars.db-password

Then our environment-specific variables files:

# dev-vars.yaml
db-host: 127.0.0.1
db-port: 5432
db-user: dev
db-password: d3v

Let's load the config.yaml file with ys -Y:

$ ys -Y config.yaml
Error: The 'ENVIRONMENT' variable must be one of 'dev', 'test', 'staging', or 'prod'

Oops! We forgot to set the ENVIRONMENT variable!

$ export ENVIRONMENT=dev
$ ys -Y config.yaml
database:
  host: 127.0.0.1
  port: 5432
  user: dev
  password: d3v

That's a pretty good setup.

We can make it even more streamlined, but we'll save that for another time.

I have a talk to finish writing!!! So I'll see you next time!

Comments