Search code examples
windowsjenkinsjenkins-pipeline

How set Batch variable to be used into other Batch commands into Jenkins pipeline file


When trying to use a variable inside another BATCH command, the result of %DOCKER_GATEWAY_ADDR% is empty.

bat "set DOCKER_GATEWAY_ADDR=docker inspect container1 -f {{.NetworkSettings.Gateway}}"
bat "docker run -d --name container2 -p 8084:8084 container-test:latest --container1-uri=http://%DOCKER_GATEWAY_ADDR%:4444"

How can I set a variable to be used in a Jenkins pipeline file?


Solution

  • You need to either combine both these bat commands into one, like this:

    bat """
       set DOCKER_GATEWAY_ADDR=docker inspect container1 -f {{.NetworkSettings.Gateway}}
       docker run -d --name container2 -p 8084:8084 container-test:latest --container1-uri=http://%DOCKER_GATEWAY_ADDR%:4444
    """
    

    OR get the output of first command and save it as env var in script and use string interpolation in second command, like this:

    env.DOCKER_GATEWAY_ADDR = bat returnStdout:true, script: "docker inspect container1 -f {{.NetworkSettings.Gateway}}"
    
    // Trim the trailing newline
    env.DOCKER_GATEWAY_ADDR = env.DOCKER_GATEWAY_ADDR.trim()
    
    bat "docker run -d --name container2 -p 8084:8084 container-test:latest --container1-uri=http://${env.DOCKER_GATEWAY_ADDR}:4444"