Knowledgebase

Environment variables


Purpose

Environment variables is a useful mechanism for being able to change configurations or behavior of a test without changing the code itself, e.g. making your tests reusable across different hosting environment (dev, staging, production etc.) by changing a base URL.

Accessing environment variables

To access an environment variable from a k6 test you use the global __ENV variable. So if you set an env var MY_ENV_VAR you’d access it like so:

1
2
3
export default function() {
    console.log(__ENV.MY_ENV_VAR);
}

Setting environment variables

There are two ways to pass environment variables to a k6 test:

  • By setting one or more -e KEY=VALUE flags when executing k6
  • By reading from the system environment

Setting CLI flags

The most portable way to pass environment variables to a k6 test is by using one or more -e KEY=VALUE CLI flags:

If we have a test script like this:

1
2
3
4
5
6
7
8
9
10
import { check, sleep } from "k6";
import http from "k6/http";

export default function() {
    var r = http.get(`https://${__ENV.MY_HOSTNAME}/`);
    check(r, {
        "status is 200": (r) => r.status === 200
    });
    sleep(5);
}

you would set the environment variable MY_HOSTNAME and execute k6 like this:

k6 run -e MY_HOSTNAME=test.loadimpact.com script.js

Reading from system environment

Using the same the same test script as above:

1
2
3
4
5
6
7
8
9
10
import { check, sleep } from "k6";
import http from "k6/http";

export default function() {
    var r = http.get(`https://${__ENV.MY_HOSTNAME}/`);
    check(r, {
        "status is 200": (r) => r.status === 200
    });
    sleep(5);
}

you would set the environment variable MY_HOSTNAME and execute k6 like this:

MY_HOSTNAME=test.loadimpact.com k6 run script.js
MY_HOSTNAME=test.loadimpact.com k6 run script.js
Cmd
c:\k6> set MY_HOSTNAME="test.loadimpact.com"
c:\k6> k6 run script.js

PowerShell
c:\k6> $env:MY_HOSTNAME = "test.loadimpact.com"
c:\k6> k6 run script.js

See the k6 docs on environment variables for more information.

Next: Custom metrics