Often, scripts need only minor tweaks to be reusable in different contexts. Rather than creating several separate scripts for these different contexts or environments, you can use environment variables to make parts of your script tweakable.
You can use environment variables for two main purposes:
- Passing environment variables to the k6 Script
- Configuring k6 Options with environment variables
In k6, the environment variables are exposed through a global __ENV variable, a JS object. For reference, see the script example below:
The recommended option to pass environment variables to your testing script is to use one or more -e / --env CLI flags (this command works the same for all platforms):
⚠ The -e flag does not configure options
This flag just provides variables to the script, which the script can use or ignore. For example, -e K6_ITERATIONS=120 does not configure the script iterations.
Compare this behavior with K6_ITERATIONS=120 k6 run script.js, which does set iterations.
A second option to pass environment variables is to source them from the local system.
By default, passing system environment variables doesn't work for k6 archive, k6 cloud, and k6 inspect. This is a security measure to avoid the risk of uploading sensitive data to k6 Cloud. To override this mode, specify --include-system-env-vars.
You can also configure k6 options with environment variables. Consider this script:
By default, a local run of this script will execute a single iteration with one virtual user(VU). To modify the default behavior, pass k6 options as environment variables. For example, this snippet configures the script to run 10 virtual users for a duration of 10 seconds:
As the preceding example shows, you need to prefix K6_ in the environment variable name for k6 to evaluate it as an option parameter. However, be aware that not all options are supported as environment variables. You can confirm whether one is by checking the documentation for each option.
Note that when you define options in multiple places, there's an order of precedence that determines the option to use. To ensure you're always working with the highest precedence, use command-line flags instead of environment variables: