Jenkinsfile Pipeline: reach ip of sidecar of host

10/29/2018

I'm running Jenkins on GKE with the Kubernetes plugin. I added a postgres container as a sidecar with the jnlp agent container. It's reachable on localhost:5432 from the agent. I also mount the GKE node's Docker socket and bin in the agent so I can spin up "sister" containers. This is also working fine.

Now I want to do the following:

pipeline {

    stages {

        stage('pytest') {

            agent {
                docker {
                    image "<image created in a previous stage>"
                    args '--add-host=database:\$(hostname\\ -i)'
                }
            }

            steps {
                // use postgres in sidecar of jnlp agent
                // e.g. on `database:5432`
            }
        }
    }
}

Doing this manually works great, but in Jenkins the above fails with:

Error: invalid argument "database:$(hostname -i)" for --add-host=database:$(hostname -i): invalid IP address in add-host: "$(hostname -i)"

Does anyone have an idea on how to escape the above? Or perhaps a completely different way of approaching this problem?

I don't have Docker 18.03+ available on GKE (stuck at 17.03.2-ce) so I can't do host.docker.internal

docker run --network host does nothing either.

-- Rutger de Knijf
docker
jenkins
jenkins-pipeline
kubernetes

1 Answer

10/29/2018

If it's a sidecar you don't need $(hostname) you should be able to connect with localhost:5432. Containers in pods share the same address space.

Another option is to use initContainers in your pod spec to set up the file that you want. You can write a bash script like this:

#!/bin/bash
cat <<EOF
pipeline {

    stages {

        stage('pytest') {

            agent {
                docker {
                    image "<image created in a previous stage>"
                    args "--add-host=database:${HOSTMAME}"
                }
            }

            steps {
                // use postgres in sidecar of jnlp agent
                // e.g. on `database:5432`
            }
        }
    }
}
EOF > /your-config-file

${HOSTNAME} being the environment variable in the pod.

-- Rico
Source: StackOverflow