Search code examples
bashdockerjenkinsdocker-composejenkins-plugins

Pass variable from Jenkinsfile pipeline to docker-compose


I have a simple docker-compose file with a dynamic image value like this:

version: '3.8'
services:
    my-app:
        image: ${IMAGE}

I am trying to set this image value from my Jenkins pipeline like this:

stage('deploy app') {
    steps {
        script {
            echo 'deploying the application...'

            def dockerComposeCmd = "docker-compose -f  docker-compose.yaml up --detach"

            sh "export IMAGE=test"
               
            sshagent(['ec2-server-key']) {                 
                sh "scp docker-compose.yaml ec2-user@***:/home/ec2-user"
                sh "ssh -o StrictHostKeyChecking=no ec2-user@*** ${dockerComposeCmd}"
            }
        }
    }
}

The stage finish with the following error, meaning that I could'nt pass the image.

ssh -o StrictHostKeyChecking=no ec2-user@*** docker-compose -f docker-compose.yaml up --detach time="2023-04-04T11:38:37Z" level=warning msg="The "IMAGE" variable is not set. Defaulting to a blank string." service "java-maven-app" has neither an image nor a build context specified: invalid compose project

How can I pass a value from Jenkins to docker compose?


Solution

  • You are setting the environment variable in your agent's local shell, but running the command on a remote machine. Try

    def dockerComposeCmd = "IMAGE=test docker-compose -f  docker-compose.yaml up --detach"