Gradle Environment variables. Load from file
Asked Answered
C

8

20

I am new to Gradle.

Currently I have this task:

task fooTask {
    doLast {
        exec {
            environment 'FOO_KEY', '1234567' // Load from file here!
            commandLine 'fooScript.sh'
        }
    }
}

fooScript.sh

#!/bin/bash
echo $FOO_KEY

Everything works great. But I have env.file with all needed environment variables. This file is used in Docker builder.

env.file

FOO_KEY=1234567

Question: how can I use env.file together with Gradle environment to load all needed env. params?

Churchwell answered 24/5, 2018 at 12:9 Comment(2)
Doing this in bash would surely be a hack, I'm sure gradle has a way to do this more neatlyFoldaway
to read a file String fileContents = new File('/path/to/file').text then you will need to parse the content.Escutcheon
E
23

What about this :

task fooTask {
    doLast {
        exec {
            file('env.file').readLines().each() {
                def (key, value) = it.tokenize('=')
                environment key, value
            }
            commandLine 'fooScript.sh'
        }
    }
}
Eggert answered 24/5, 2018 at 12:31 Comment(0)
G
23

I give also my version (check if line is not empty and not a comment, also donot override env var):

file('.env').readLines().each() {
    if (!it.isEmpty() && !it.startsWith("#")) {
        def pos = it.indexOf("=")
        def key = it.substring(0, pos)
        def value = it.substring(pos + 1)

        if (System.getenv(key) == null) {
            environment key, value
        }
    }
}

But actually, I think they should add this feature as a exec plugin property! It's quite common now to use .env file.

Geostrophic answered 5/11, 2018 at 16:19 Comment(3)
great solution that won't override existing ENVVarlet
actually ran into problem and ended up creating my own properties variable and using your code to populate it. def envProperties = new Properties() ... your code and ... envProperties.setProperty(key, value)Varlet
found an easier way just using existing framework to load a Properties file https://mcmap.net/q/394335/-gradle-environment-variables-load-from-fileVarlet
M
1

The following code is the only one i've been able to produce and which satisfies two of the most importants requirements to provide an efficient "UNIX standard environment file import" in Android studio :

  • Loads a file which depends of the Build Type (at least : debug and release)
  • Exposes specified environment variables in the Android code, actually not as environment variables but as buildConfigFields content.
ext {
    node_env = ""
}

android.applicationVariants.all { variant ->
    if (variant.name == "debug") {
        project.ext.set("node_env", "development")
    } else if (variant.name == "release") {
        project.ext.set("node_env", "production")
    }

    file("." + node_env + '.env').readLines().each() {
        if (!it.isEmpty() && !it.startsWith("#")) {
            def pos = it.indexOf("=")
            def key = it.substring(0, pos)
            def value = it.substring(pos + 1)

            if (System.getProperty(key) == null) {
                System.setProperty("env.$key", value)
            }
        }
    }

    if (variant.name == "release") {
        android.signingConfigs.release.storeFile file(System.getProperty("env.ANDROID_APP_SIGNING_STOREFILE"))
        android.signingConfigs.release.keyAlias System.getProperty("env.ANDROID_APP_SIGNING_KEYALIAS")
        android.signingConfigs.release.storePassword System.getProperty("env.ANDROID_APP_SIGNING_STOREPASSWORD")
        android.signingConfigs.release.keyPassword System.getProperty("env.ANDROID_APP_SIGNING_KEYPASSWORD")
    }
    android.defaultConfig.buildConfigField "String", "ANDROID_APP_URL", "\"${System.getProperty("env.ANDROID_APP_URL")}\""
}

Kotlin :

Log.i(TAG, BuildConfig.ANDROID_APP_URL)

Please let me know what you think of it as i'm not completly sure how it works, especially to select the good file to load.

Mortgagee answered 18/8, 2019 at 19:47 Comment(0)
M
1

There are plugins to load env vars from a .env file (e.g. this one)

So a sample build file will look something like this (Kotlin DSL)


plugins {
    id("co.uzzu.dotenv.gradle") version "1.1.0"
}

tasks.withType<Test> {
    useJUnitPlatform()
    //will pass the env vars loaded by the plugin to the environment of the tests
    environment = env.allVariables
}
Midterm answered 15/2, 2021 at 16:9 Comment(1)
This throws an erorr, shouldn't it be tasks.withType(Test)?Rapper
R
1

If you're using Spring Boot bootRun task or anything that has a runner

tasks.named('bootRun') {
    doFirst {
        file('.env').readLines().each() {
            def (key, value) = it.tokenize('=')
            environment key, value
        }
    }
}
Ricks answered 24/10, 2022 at 16:37 Comment(0)
T
0

I have ended up doing it in my gradlew file. A possible drawback is that the change tends to be overwritten on upgrades to gradle.

# Hack: export all variables in the .env file
#
ENV_FILE=../../.env
if [ ! -f $ENV_FILE ];then
    echo "WARNING/DEV ENV Missing a ${ENV_FILE} file with environment variables (secrets)";
fi
for secret in `cat $ENV_FILE`;do export $secret;done
Tessi answered 31/8, 2021 at 12:51 Comment(0)
A
0

For those folks who are using build.gradle.kts

fun getMyVersion() : String {
    return file(".env.file")
        .readLines()
        .map { item -> item.split("=") }
        .single { (k, v) -> k == "APP_VERSION" }
        .get(index = 1)
}

my_version = getMyVersion()
Ascension answered 5/12, 2023 at 21:25 Comment(0)
V
0

I require this for Flutter / Android build.

Found an real easy way, the .env file is basically a Properties file. So you just need to know how to load a Properties file.

def envProperties = new Properties()
def envPropertiesFile = file('../../.env')
envPropertiesFile.withReader('UTF-8') { reader ->
    envProperties.load(reader)
}
println(envProperties.getProperty('SOME_VAR')

Source for how to load properties file: https://mcmap.net/q/334869/-get-values-from-properties-file-using-groovy

Varlet answered 18/7 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.