Hey Devs 👋🏻

We always have some .env files in our projects to assign the environment variables.

Now as mentioned here, we can pass the env vars like:

k6 run -e MY_NAME=MoKhajavi75 script.js

And use them in our k6 project like:

export default function () {
  console.log(__ENV.MY_NAME);
}

This works if the env variables are not too many.

But what if we have many? Or even if we don't want to pass them via CLI and use a .env file 🤔

I have a nice yet effective bash script to assign those env vars from a .env file:

#!/bin/bash

ENV_FILE_PATH=".env"
ENV_VARS=()

if [[ ! -f "${ENV_FILE_PATH}" ]]; then
  echo "\"${ENV_FILE_PATH}\" file not found!"
  exit 1
fi

while IFS= read -r line; do
  key=${line%%=*}
  value=${line#*=}

  ENV_VARS+=("-e" "${key}=${!key:-${value}}")
done < <(grep -vE '^\s*($|#)' "${ENV_FILE_PATH}")

exec k6 run "${ENV_VARS[@]}" "$@"

This script skips comment lines (the ones starting with "#" and empty lines) so feel free to write your .env file as you like, as many variables you like!

We can name it run.sh and use it like:

./run.sh script.js

Just don't forget to make it executable! (chmod +x run.sh)


Now, what about the usage part? What if we're using TypeScript, as it's getting into k6?

Let's write a nice getEnv utility function too:

type EnvVars = 'KEY1' | 'KEY2' | 'KEY3';

/**
 * Retrieves environment variables.
 * @param key - The key of the environment variable to retrieve.
 * @returns - The value of the environment variable.
 * @throws {Error} - Throws an error if the environment variable is not set.
 * @example
 * const value = getEnv('KEY');
 */
export const getEnv = (key: EnvVars): string => {
  const env = __ENV[key];

  if (env === undefined) throw new Error(`Environment variable ${key} is not set`);
  return env;
};

So we can improve the above example:

import { getEnv } from './env';

export default function () {
  console.log(getEnv('MY_NAME'));
}

This way, it suggests code intellisense and we have a nice, well-documented utility function for usage too.

Hope this helps :)
Feel free to comment with any questions or suggestions!