Create docker/container images in a Kubernetes Jenkins pipeline

 The challenge is quite simple: To deploy a pice of software to Kubernetes it's necessary to create the (docker) container image in a pipeline.

But the solution was not found directly. The most articles found show how to use the docker socket or tcp port to create images but since docker is no more part of Kubernetes this will not work any more.

The solution is to use 'kaniko'. Looks like the project is able to master image creation.

1) First install and configure Jenkins

values.xml

controller:

  JCasC:

    securityRealm: |-

      local:

        allowsSignup: false

        enableCaptcha: false

        users:

        - id: "admin"

          name: "Jenkins Admin"

          password: "xxx"

    authorizationStrategy: |-

      loggedInUsersCanDoAnything:

        allowAnonymousRead: false

  ingress:

       enabled: true

       paths: []

       apiVersion: "extensions/v1beta1"

       hostName: jenkins.mycluster.de


kubectl create namespace jx
helm install jenkins jenkins/jenkins -f values.yaml

2) To push images in a repository (e.g. sonatype nexus) it's necessary to configure the repository credentials:

Create a file 'config.json' (the name must fit) and import it into the Jenkins namespace:

CI_REGISTRY=docker.mycluster.de
CI_REGISTRY_USER=managernexus
CI_REGISTRY_PASSWORD=$(pass cloud/prod/mycluster/managernexus)
echo "{\"auths\":{\"${CI_REGISTRY}\":{\"auth\":\"$(printf "%s:%s" "${CI_REGISTRY_USER}" "${CI_REGISTRY_PASSWORD}" | base64 | tr -d '\n')\"}}}" > config.json

kubectl create secret generic -n jx docker-config --from-file=config.json

rm config.json

3) Create a pipeline:

pipeline {
agent {
kubernetes {
yamlFile 'jenkins-pod.yaml'
}
}
stages {
stage('Build image') {
steps {
container('kaniko') {
sh "/kaniko/executor \
--dockerfile `pwd`/Dockerfile \
--context `pwd` \
--destination=docker.mycluster.de/myimage:${env.BUILD_ID} \
--destination=docker.mycluster.de/myimage:latest"
}
}
}
}
}

4) Create a pod configuration

spec:
containers:
- name: kaniko
image: gcr.io/kaniko-project/executor:debug
command:
- cat
tty: true
volumeMounts:
- name: docker-config
mountPath: /kaniko/.docker
volumes:
- name: docker-config
secret:
secretName: docker-config

5) Create a Jenkins pipeline

In Jenkins create a new pipeline using the 'Jenkins' file as pipeline. Create a Dockerfile in the project root to create the container image.


Comments

Popular posts from this blog

Creating a flux sync configuration referring a config map for substitution

Sonatype Nexus fails with random "peer not authenticated" errors behind ingress

Create Spring Boot Images in Jenkins/CI in K8s, Part 1