Additional Gradle Properties

I have a Gradle build file, where one of the tasks is to enter docker. In this task, I want the user / CI to provide docker_username, docker_password and docker_email parameters.

task loginDockerHub(group: "Docker", type:Exec) { executable "docker" args "login","-u", docker_username, "-p", docker_password, "-e", docker_email } 

Doing gradle loginDockerHub -Pdocker_username=vad1mo ... works as expected.

But when I execute, for example, gradle build , I get an error:

Could not find property 'docker_username' on task ': loginDockerHub'.

I would expect this error when doing gradle loginDockerHub without providing the -P option, but not for other tasks that don't have access to docker_username / password options.

How can I have optional parameters for my loginDockerHub task in Gradle that do not make the parameter mandatory for any other task.

+8
build.gradle gradle
source share
3 answers

You can check if a property exists and not return the default value.

 args "login", "-u", project.hasProperty("docker_username") ? docker_username : "" 

Update: Starting with Gradle 2.13, you can simplify this.

 args "login", "-u", project.findProperty("docker_username") ?: "" 
+7
source share

I could not find a solution to the problem. In this description, there was a hint of declaring actions within the task. Putting the exec shell in an action task has the behavior that I expected, because actions are evaluated when the task is executed.

 task loginDockerHub(group: "Docker", type:Exec) { doFirst{ executable "docker" args "login","-u", docker_username, "-p", docker_password, "-e", docker_email } } 

Running loginDockerHub without providing docker_* parameters will cause an error. Performing any other task will work properly.

+4
source share

I had to do this and did not want my build to fail. I solved this by doing this:

 ext.shouldLoginDockerHub = project.hasProperty("docker_username"); task loginDockerHub(group: "Docker") { doLast{ if(shouldLoginDockerHub) { exec { executable "docker" args "login","-u", docker_username, "-p", docker_password, "-e", docker_email } } else { println "Not logging in to docker hub because docker_username was not provided."; } } } 

You can expand the first line to search for docker_password, docker_email, etc.

0
source share

All Articles