A lot of the time, scripts will only need minor tweaking to be reusable in different contexts. Rather than having to create 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
- Configure 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 of passing environment variables to your testing script is using one or more -e / --env CLI flags (this command works the same for all platforms):
Note: This can not be used to configure k6 with environment variables as listed on the options page. In other words -e K6_ITERATIONS=120 will not configure the script iterations, it will just provide __ENV.K6_ITERATIONS to the script, unlike K6_ITERATIONS=120 k6 run script.js.
A second option of passing environment variables is by sourcing them from the local system.
By default, passing system environment variables does not work for k6 archive, k6 cloud and k6 inspect. It is a security measure to avoid the risk of uploading sensitive data to k6 Cloud. You can override this mode by explicitly specifying --include-system-env-vars.
k6 options can be configured by passing environment variables. Consider the following basic test script:
By default, running the above script locally will execute a single iteration using one virtual user(VU). We can modify the default behavior by passing along k6 options as environment variables. For example, we can configure the script to run 10 virtual users for a duration of 10 seconds:
As demonstrated above, you will need to prefix K6_ in the environment variable name in order for k6 to evaluate it as an option parameter. However, be aware not all options are supported as environment variables. You can confirm by checking the documentation for each option.
Note that when you use multiple ways to define options for a script, there's an order of precedence that is used to determine which option is actually used. To ensure you are always working with the highest precedence, always use command-line flags instead of environment variables: