I would like to run some docker commands such as
docker login -u foo -p bar myregistry
docker build --pull=true -t myregistry/myimage path/to/dockerfile
docker push myregistry/myimage
I have tried several plugins for it such as this one, but none of those was satisfying, or maybe I am missing something...
My question is, what is the best way to run docker commands inside of my gradle tasks
Here is my build.gradle file and what I would like him to do
import GenerateDockerFile
apply plugin : 'groovy'
repositories {
    mavenCentral()
    jcenter()
}
dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.4.7'
    compile localGroovy()
    compile gradleApi()
    classpath 'com.bmuschko:gradle-docker-plugin:3.0.1'
}
def copyFiles() {
    //Some stuff
}
def versionNumber(){
    //Some stuff    
}
def clean(){
   exec {
        executable "sh"
        args "-c", "ls"
    }
}
}
task build (){
    copyFiles()
    versionNumber()
    def version = new File('tmp_version').text
    def buildTag= ""
    if (project.hasProperty('args')) {
      buildTag = args
    }
    else{
      buildTag = System.console().readLine 'Enter a build tag'
    }
    println "\nGenerating DockerFile for version $version with build tag $buildTag"
    GenerateDockerFile.configure(version, buildTag);
    println 'DockerFile generated'
    //Execute docker commands here
    // docker login ....
    doLast {
        clean()
    }
}
If possible, something like the exec sh like in the clean method would be perfect. However, if a plugin can easily do this, it's ok too
I have not tried it out, but how about following suggestion, inspired by the answer on Run shell command in gradle but NOT inside a task and by the discussion on https://discuss.gradle.org/t/how-to-execute-shell-command-source-or-dot-doesnt-work-with-exec/7271/9?
For running the two commands
docker login localhost:8080
docker build .
you could try with:
def runDockerLogin(String target) {
    exec {
        executable "docker"
        args "login", target
    }
}
def runDockerBuild(String target) {
    exec {
        executable "docker"
        args target
    }
}
task doIt {
    doLast {
        runDockerLogin("localhost:8080")
        runDockerBuild(".")
    }
}
Note that the args need to be specified in lists. E.g. if you want to issue a command like
docker build -t fail .
using runDockerBuild, then I expect that 
runDockerBuild("-t fail .")
will not work. Instead, runDockerBuild could be re-written to something like
def runDockerBuild(String target) {
   exec {
        executable "docker"
        args "-t", "fail", target
    }
}
Is this pointing in the right direction?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With