Building on the concept of extensibility, k6 has the ability to read variables set in the local environment and apply them to test scripts. Reusable scripts often only require minor changes to be used in different contexts, and k6 environment variables provide this. In addition, there are some k6 extensions that depend on environment variables to set their configuration. In this post, we will show you how to set k6 environment variables both in your local development environment, and in tests that run on RedLine13.
Local Environment
Natively, k6 supports environment variables set at the command line level. There is a concise syntax described in the official documentation, which is as follows:
$ k6 run -e MY_VARIABLE=my_value script.js
In this format, an environment variable will be set with the name “MY_VARIABLE
”, and it will contain “my_value
”. If you want to use this variable directly within your test script, you can use the ${__ENV.MY_VARIABLE}
convention to insert your value. For example, if you set -e MY_HOSTNAME=api.my-domain.com
at the command line, you can access the value as follows within your test:
export default function () {
const result = http.get(`http://${__ENV.MY_HOSTNAME}/get-widget`);
}
This will direct the request to api.my-domain.com/get-widget
without any modification of the actual test script. Test designers familiar with JMeter user variables will find this syntax similar, and it functions in much the same way.
Tests on RedLine13
If you are running your k6 test in the cloud using RedLine13, as an alternative to setting at the command line environment variables can instead be set using the xk6-dotenv
extension. You can enable this extension for your test by selecting it from the list of available extensions under “Advanced k6 Test Options”.
In a separate file, we can specify any number of environment variables in the same MY_VARIABLE=my_value
format explained above. Each assignment within this file should go on its own line. The documentation for this extension specifies naming conventions for .env
files, however it will look for a file named “.env.development.local
” first. Let’s go ahead and save our file with this name.
To upload the file with your test, we can simply attach it as an extra file:
The environment configuration file will be uploaded to your load generator servers and read alongside your k6 test plan.
Did you know that RedLine13 offers a full-featured, time-limited free trial? Sign up now, and start testing today!