How to pass thresholds from ENV variables

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)

You can use __ENV variables, as described in the 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))
}

I face kind of the same issue: I want to have different threshold values if I run a test in environment A or B.
ENV variables could be a solution…but with dozens of thresholds it doesn’t seem to be a proper solution.

Would it be possible/make sense to load the thresholds from a file?
(given that files seem to be only readable from the setup() function)

Hi @troble, you can take a look at this comment in the issues which proposes a solution involving opening and reading files.

I don’t know why you came to that conclusion. Have we written it that way somewhere ? As far as I can see the documentation correctly states that open needs to be used in the init context and the init context only. But you can use the read data everywhere you want not only in the init context or setup

Yeah, what I wrote was misleading. I thought files could only be opened after the options were set. But the comment you link shows it’s not that way :slight_smile:
Thanks a lot, it seems to perfectly fit my use case!

1 Like