How to use GitHub secrets or GitHub environment variables in build.gradle file

Viewed 751

I have some authentication secrets in GitHub and I have to use them in spring boot build.gradle file is there any example for the same.

1 Answers

There are two main possibilities IMHO:

1. Externalize the data:

Create a new file, let's say secrets.gradle, where you set your secrets, like:

mySecretUser = "me"
mySecretPassword = "password123"

Make sure, this file is never commited to your versioning system, e.g. by adding it to .gitignore!

Then, in your build.gradle, you can refer it like so:

apply from: 'secrets.gradle'

This would help you with local development e.g.

2. Use environment variables:

You can set the secrets as environent variables like this:

set mySecretUser=me
set mySecretPassword=password123

(On Windows, in Unix you might rather use export instead of set.)

Then, you can use them in your build.gradle like this:

mySecretUser = "$System.env.mySecretUser"
mySecretPassword = "$System.env.mySecretPassword"

2½ - Combine both methods:

In order to look for the secrets.gradle file and just use the environment variables, if it does not exist, you can do it like this in your build.gradle:

if (file('secrets.gradle').exists()) {
    apply from: 'secrets.gradle'
}
else {
    mySecretUser = "$System.env.mySecretUser"
    mySecretPassword = "$System.env.mySecretPassword"
}

Final note:

You didn't write anything about your setup - is the Gradle build executed locally or on a build server like Jenkins? In the first case, the secrets.gradle approach might be the better way to go. On a Jenkins server, you'll find great possibilities to store credentials as build environment variables via the configuration.

Anyway, I just gave some suggestions here. Please make sure, your secrets are really kept secret and not inadvertantly revealed. As I don't know your setup, I cannot say anything about how safe these methods are in your case.

Related