Skip to content

Instantly share code, notes, and snippets.

@kekru
Last active May 19, 2021 16:43
Show Gist options
  • Save kekru/d728c79dc0ad8088150297dba1375495 to your computer and use it in GitHub Desktop.
Save kekru/d728c79dc0ad8088150297dba1375495 to your computer and use it in GitHub Desktop.
Gradle read secrets from gpg encrypted file

Gradle: Read repository secret from gpg encrypted .netrc file

This is how to read credentials from a .netrc formatted file, which is encrypted using gpg and use these credentials as login data for gradle remote repositories.

First you need to have gpg keys created.

Then create a ~/.netrc as shown below and encrypt it with gpg -r <your email> -e ~/.netrc, which will create a .netrc.gpg. Remove the unencypted .netrc afterwards.
Now create a ~/.gradle/init.gradle as shown below.

When gpg is locked, your next gradle build will cause gpg to show a window to enter you gpg key's password.
You can control how long the password should be cached with your ~/.gnupg/gpg-agent.conf using --default-cache-ttl and --max-cache-ttl properties.

This was tested on Windows with a default Git installation. gpg is already included in the Git installation.

machine myserver.example.com
login someone
password my-secret-pw
machine something2.example.com
login someoneelse
password secret123
final def repoCredentials = readLoginAndPasswordFromEncryptedNetrc("~/.netrc.gpg", "myserver.example.com")
final def repoMirror="https://myserver.example.com/somepath"
allprojects {
settingsEvaluated { settings ->
settings.pluginManagement {
repositories {
mavenLocal()
maven {
url = repoMirror
credentials {
username = repoCredentials["login"]
password = repoCredentials["password"]
}
}
}
}
}
buildscript {
repositories {
mavenLocal()
maven {
url = repoMirror
credentials {
username = repoCredentials["login"]
password = repoCredentials["password"]
}
}
}
}
repositories {
mavenLocal()
maven {
url = repoMirror
credentials {
username = repoCredentials["login"]
password = repoCredentials["password"]
}
}
}
}
def Map<String, String> readLoginAndPasswordFromEncryptedNetrc(String encryptedNetrcFile, String repoHostname) {
def netrcContent = "gpg -q -d ${encryptedNetrcFile}".execute().text.split("\n")
boolean foundMachine = false
String login = null, password = null
for (String line : netrcContent) {
if (line.startsWith("machine") && line.substring("machine".length()).trim().equals(repoHostname)) {
foundMachine=true
} else if (foundMachine && login == null && line.startsWith("login")) {
login = line.substring("login".length()).trim()
} else if (foundMachine && password == null && line.startsWith("password")) {
password = line.substring("password".length()).trim()
}
}
if (login == null || password == null) {
throw new RuntimeException("Credentials not found in " + encryptedNetrcFile)
}
return [
"login" : login,
"password" : password
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment