How to pass thresholds from ENV variables


#1

I have defined below options in my script which has threshold.

export let options = {
    setupTimeout: commonsData.generalData.setupTimeout + 'h',
    vus: commonsData.generalData.users,
    rps: commonsData.generalData.requestsPerSecond,
    thresholds:{
            searchVariants: [{
                    threshold: "max<1"
                },
                {
                    threshold: "p(95)<1"                    
                },
                {
                    threshold: "avg<1"
                }
            ]
        },
    duration: commonsData.generalData.loadDuration + 's'
}

Now our requirement is that we need to pass threshold as env variables, and if it not passed, above defaults should be used. Can anyone guide me on this?

(question copied from the k6 Slack channel)


#2

You can use __ENV variables, as described in the docs: https://docs.k6.io/docs/environment-variables

You can use default values, when the vars are not supplied.

var max_iterations = "count<5"
if (__ENV.max_iterations !== undefined) {
   max_iterations = __ENV.max_iterations
}

export let options =  {
    thresholds: {
        iterations: [{threshold: max_iterations}]
    }
}

export default function() {
    console.log(JSON.stringify(options.thresholds.iterations))
}

The example is with the iterations metric as to be shorter
running from terminal
k6 run test.js will not fail because we will run 1 iterations
k6 run -i 5 test.js will fail because we will run 5 which is not less than 5
k6 run -i 5 -e max_iterations="count<6" test.js will not fail because we overwrite the threshold

or you could use a ternary operator to make is shorter:

export let options =  {
    thresholds: {
        iterations: [(__ENV.max_iterations !== undefined ? __ENV.max_iterations : "count<5")]
    }
}

export default function() {
    console.log(JSON.stringify(options.thresholds.iterations))
}