Thomas
Thomas

Reputation: 4330

Why gradle is throwing error on missing project property

I'm using maven-publish plugin to release an artifact to nexus repository. I don't want to put the actual credentials of my nexus repository in my build.gradle file. So I decided to use project properties like shown below

credentials {
            username "$nexus_username"
            password "$nexus_password"
}

Now I can use gradle publish -Pnexus_username=<myusername> -Pnexus_password=<mypass> to publish my artifact to my nexus repository. But it doesn't make any sense to keep passing this project properties for a normal gradle build. And if I don't pass gradle is throwing an error saying Could not find property 'nexus_username' Anybody know a better approach to solve this.

Upvotes: 6

Views: 2545

Answers (2)

William Price
William Price

Reputation: 4102

I keep my credentials in my user-specific Gradle properties, so only my user account has access to the values and I can leave dummy (or undefined) values in the Gradle project. That way, if I distribute the project to others or commit the project to source control, no one gets my personal credentials or settings.

As explained in the Gradle User Guide: The Build Environment, your user-specific properties will override any properties set in a project's local gradle.properties file where the property names match. Values entered on the command line using -P will still take precedence over both of the former sources.

Your user-specific file is named gradle.properties and is located in the path specified by the GRADLE_USER_HOME environment variable (if set), and defaults to:

  • Linux / OS X: ~/.gradle/gradle.properties
  • Windows: %USERPROFILE%\.gradle\gradle.properties

You can then use the hasProperty approach in the build script, or define default values by editing (or creating) the project's gradle.properties file (at the same level as your build.gradle file):

# Do not put real credentials here!
# Instead, copy to ~/.gradle/gradle.properties and set the values there.
nexus_username =
nexus_password =

The main caveat to this approach is that your user-specific property file can only provide a single value for a given property name. That could be an issue if you have multiple projects that use the same property names but need different values. Also, the file is plain text, so it might not be the best place for passwords unless you're willing to take that risk.

Upvotes: 2

Thomas
Thomas

Reputation: 4330

Found a solution after some digging

if(! hasProperty("nexus_username")){
    ext.nexus_username=""
}
if(! hasProperty("nexus_password")){
    ext.nexus_password=""
}

Here what I'm doing is creating a blank username and password if the project property is not available. But I still feel this is a work around and not the right solution. Please do respond if anybody find a more elegant solution.

Upvotes: 5

Related Questions