Jenkins – Kubernetes plugin: An example of building an image with a Maven project

 

An example of a pipeline for working with the plugin for kubernetis. We build the maven project, create a docker image with the received artifact and push it into the docker image storage.

 

Pipeline:

podTemplate(
  containers: [
    containerTemplate(
      name: 'maven',
      image: 'maven:latest',
      command: 'cat',
      ttyEnabled: true),
    containerTemplate(
      name: 'docker',
      image: 'docker:latest',
      command: 'cat',
      ttyEnabled: true,
      envVars: [
        secretEnvVar(key: 'DOCKER_LOGIN', secretName: 'docker-regestry-credentials', secretKey: 'username'),
        secretEnvVar(key: 'DOCKER_PASSWORD', secretName: 'docker-regestry-credentials', secretKey: 'password'),
        envVar(key: 'DOCKER_REGESTRY_URL', value: 'docker.artem.services'),
        envVar(key: 'DOCKER_REPO', value: 'artem')
      ]
    )
  ],
  volumes: [
    hostPathVolume(
      hostPath: '/var/run/docker.sock',
      mountPath: '/var/run/docker.sock')]
)
{
  node(POD_LABEL) {
    stage('Get a Maven project') {
      git 'https://git.artem.services/artem/maven-project.git'
      container('maven') {
        stage('Build a Maven project') {
          sh 'mvn -B clean install'
        }
      }
    }

    stage('Build Docker image') {
      container('docker') {
        writeFile file: "Dockerfile", text: """
            FROM tomcat:jdk8
            COPY ./web/target/*.war /usr/local/tomcat/webapps/
        """
        sh "docker build -t \$DOCKER_REGESTRY_URL/\$DOCKER_REPO/maven:${env.BUILD_ID} ."
        sh "docker login -u \$DOCKER_LOGIN -p \$DOCKER_PASSWORD \$DOCKER_REGESTRY_URL"
        sh "docker push \$DOCKER_REGESTRY_URL/\$DOCKER_REPO/maven:${env.BUILD_ID}"
      }
    }
  }
}

 

Dockerfile – already created in the pipeline itself.
envVar – taken from the secret of kubernetes

Tagged: Tags

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments