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:

  1. Open your k6 test script and replace any hardcoded URLs with __ENV.BASE_URL. For example, change:

    JavaScript
    const res = http.get('https://staging.example.com/api/health');

    to:

    JavaScript
    const res = http.get(`${__ENV.BASE_URL}/api/health`);

    __ENV is a k6 global object that provides access to environment variables passed with the -e / --env flag or set in the shell environment. For details, refer to Environment variables.

  2. Run the script locally with the -e flag to pass the base URL:

    Bash
    k6 run -e BASE_URL=https://staging.example.com test.js

    Verify that the test runs successfully against the specified environment.

  3. Add a default value check at the top of your script to catch missing variables early:

    JavaScript
    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_URL produces confusing HTTP errors instead of a clear message about the missing variable.

  4. Test that the error message works by running without the -e flag:

    Bash
    k6 run test.js

    You 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 __ENV for 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.


page 4 of 9