Home > Mobile >  Gradle: set env variable for static method on evaluation stage
Gradle: set env variable for static method on evaluation stage

Time:08-10

In my build.gradle script I have a static method:

static def startDbContainer() {
    var postgres = new PostgreSQLContainer(
            DockerImageName.parse("registry/testcontainers/postgres:11.2-alpine")
                    .asCompatibleSubstituteFor("postgres"))
    postgres.withInitScript("init.sql")
    postgres.start()
    return postgres
}

def postgres = startDbContainer()

On evaluation stage I drop to this point:

(in class org.testcontainers.DockerClientFactory)

    public static String start(DockerClient client) {
        String ryukImage = ImageNameSubstitutor.instance()
            .apply(DockerImageName.parse("testcontainers/ryuk:0.3.3"))
            .asCanonicalNameString();
        DockerClientFactory.instance().checkAndPullImage(client, ryukImage);
        ...

There's no ryuk:0.3.3 image in my local repository, so build fails.

I can't rise up version of Testcontainers for some reasons.

I have an option to set env variable TESTCONTAINERS_RYUK_DISABLED=true to avoid behavior described, because of this branch:

        boolean useRyuk = !Boolean.parseBoolean(System.getenv("TESTCONTAINERS_RYUK_DISABLED"));
        if (useRyuk) {
            log.debug("Ryuk is enabled");
            try {
                //noinspection deprecation
                ryukContainerId = ResourceReaper.start(client);
            } catch (RuntimeException e) {
                cachedClientFailure = e;
                throw e;
            }
            log.info("Ryuk started - will monitor and terminate Testcontainers containers on JVM exit");
        } else {
            log.debug("Ryuk is disabled");
            ryukContainerId = null;
        }

So the question is:

How I can set environment variable in Gradle script before running static method on evaluation stage?

P.S.: I've read topics here about setting env vars in test and Exec tasks: it's not my case.

CodePudding user response:

You can't easily set the environment variable from within the already running Gradle process. You need to set the environment variable as part of calling Gradle or inside your environment.

And you can't access Docker Hub to pull testcontainers/ryuk:0.3.3? Did you consider bringing the image into your registry and configuring it? See the official docs on how to do this: https://www.testcontainers.org/features/image_name_substitution/#automatically-modifying-docker-hub-image-names

  • Related