Parameterize your script for multiple environments
A CI/CD pipeline often runs the same script against different environments: a preview after a pull request, staging before a release, and sometimes production after deployment. If your script has a hardcoded URL, you need a separate script for each environment. Environment variables eliminate this problem. You define the target URL once as a variable and pass the value at runtime.
To parameterize your script, complete the following steps:
Open your k6 test script and replace any hardcoded URLs with
__ENV.BASE_URL. For example, change:const res = http.get('https://staging.example.com/api/health');to:
const res = http.get(`${__ENV.BASE_URL}/api/health`);__ENVis a k6 global object that provides access to environment variables passed with the-e/--envflag or set in the shell environment. For details, refer to Environment variables.Run the script locally with the
-eflag to pass the base URL:k6 run -e BASE_URL=https://staging.example.com test.jsVerify that the test runs successfully against the specified environment.
Add a default value check at the top of your script to catch missing variables early:
const BASE_URL = __ENV.BASE_URL; if (!BASE_URL) { throw new Error( 'BASE_URL environment variable is required. Use: k6 run -e BASE_URL=https://... test.js' ); }Without this check, a missing
BASE_URLproduces confusing HTTP errors instead of a clear message about the missing variable.Test that the error message works by running without the
-eflag:k6 run test.jsYou should see the error message you defined. This confirms that the script fails fast when the required variable is missing.
Tip: You can parameterize more than just the URL. Use
__ENVfor any value that varies between environments, such as authentication tokens (__ENV.API_TOKEN). Keep secrets out of the script and inject them from your CI platform’s secret store.
In the next milestone, you add k6 as a step in your CI/CD pipeline.