Karate DSL environment configuration ignores KARATE_ENV variable in CI pipelines
0 reputation · 15 Mar 2021, 04:14 UTC
0 reputation · 15 Mar 2021, 04:14 UTC
Goal: Ensure that Karate DSL selects the correct environment block from karate-config.js consistently across local development and production CI pipelines.
Constraint: Karate reads only the JVM system property karate.env to determine which environment to load; it does not consult the OS environment variable KARATE_ENV. When CI provides only KARATE_ENV, the framework falls back to the default configuration, leading to missing endpoints or credentials and test failures. This behavior is documented and unchanged across recent releases.
Questions: Is there a supported way for Karate to honor the KARATE_ENV environment variable directly? Should users always expose KARATE_ENV as a JVM system property, or is there a recommended approach to bridge OS env vars to system properties within karate-config.js without modifying the launch script?
30775 reputation · 15 Mar 2021, 08:42 UTC
Karate DSL does not natively honor the KARATE_ENV OS environment variable. It exclusively consults the JVM system property karate.env to determine which configuration block to load from karate-config.js.
To ensure your CI pipeline selects the correct environment, you must explicitly map the OS environment variable to the JVM system property during the test execution command. There is no supported way to make Karate read KARATE_ENV directly without this bridge.
Modify your CI launch script or pipeline configuration to include the -D flag. This passes the value of the OS variable into the JVM:
# Example for Maven execution
mvn test -Dkarate.env=$KARATE_ENV
# Example for Gradle execution
./gradlew test -Dkarate.env=$KARATE_ENV
If you cannot modify the launch script, you can attempt to bridge the variables inside karate-config.js using Java's System.getenv(). However, this is a manual override and does not change how Karate's internal environment logic functions; it simply allows you to use the OS variable to set your own configuration variables.
function fn() {
var env = karate.env;
// Fallback to OS environment variable if JVM property is missing
if (!env) {
env = java.lang.System.getenv('KARATE_ENV');
}
if (env == 'prod') {
// prod config
} else if (env == 'stage') {
// stage config
}
// ...
}
To verify which environment is actually being resolved at runtime, add a print statement to the top of your karate-config.js file:
karate.log('Resolved Environment: ' + karate.env);
Note: If you are using a custom JUnit runner, ensure that the system properties are being passed through to the forked JVM process, as some build tools isolate the test JVM from the shell environment.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.