Skip to content

Instantly share code, notes, and snippets.

@nobbynobbs
Last active May 9, 2023 20:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save nobbynobbs/9806240e71893d94ce76de2e4d167f98 to your computer and use it in GitHub Desktop.
Save nobbynobbs/9806240e71893d94ce76de2e4d167f98 to your computer and use it in GitHub Desktop.
example of sidecar service in jenkins declarative pipeline
pipeline {
agent { label "docker" }
stages {
stage("test sidecar") {
steps{
script {
withDockerNetwork { n ->
// we could use Image.withRun() instead of Image.run(),
// and get rid of try/catch/finally blocks
// It's prefferable way, but it doesn't remove volumes after containers
def c = docker.image("mongo:3.4").run("--rm --network=${n} --net-alias=mongo", "mongod --storageEngine ephemeralForTest")
try {
docker.image("python:3.7-slim").inside("--network=${n}") {
sh "python --version"
sh "false"
}
} finally {
try {
c.stop()
} catch (Exception) {
// just ignore the error.
// it has thrown because of --rm flag
// which used to remove volumes after container stop
// container.stop() executes `docker stop container && docker rm container`,
// and thinks that error happens on rm command,
// and error actually happens, but it's OK because container already removed.
}
}
}
}
}
}
}
}
// from https://issues.jenkins.io/browse/JENKINS-49567?focusedCommentId=363468&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-363468
def withDockerNetwork(Closure inner) {
try {
networkId = UUID.randomUUID().toString()
sh "docker network create ${networkId}"
inner.call(networkId)
} finally {
sh "docker network rm ${networkId}"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment