How To Create A CI/CD Pipeline With Jenkins
Introduction
In a previous tutorial, you learned how to install Jenkins on a Kubernetes Cluster. In this tutorial, we will create a Jenkins CI/CD pipeline to build a docker image, test it on a staging server to make sure it works as expected, and then push it to Docker Hub.
Prerequisites
- Jenkins installed on a Kubernetes cluster. Refer to this guide for installation
- Jenkins Kubernetes plugin configured as described at Automatic Scaling Jenkins Pods on Kubernetes
- Valid SSH key-value pairs.
How To Create an Nginx Pipeline
In this example, we will be using a Pipeline consisting of 4 steps:
- Git Checkout.
- Build the Docker Image.
- Push Docker Image to Docker Hub.
- Test Nginx Image On Staging Server, stop it, and delete it.
The actual pipeline code can be seen below:
remote-dev-server-credentials
is the credentials id withing Jenkins that holds our private key for connecting remotely (passwordless) to our staging server. Keep in mind that passing a secret variable containing sensitive information to “sh” using Groovy String interpolation is insecure. See Jenkins groovy string interpolation documentation for more details.
If everything goes well, you should see something like the image below:
You can clearly see all steps taken by Jenkins, and their corresponding time it took each of them to complete.
Now let’s take a look at a more complicated example
Creating and Deploying a WordPress Image
This scenario consists of 5 stages:
- Checking out a GitHub repository containing the WordPress Dockerfile.
- Build the image.
- Push the image to DockerHub.
- Deploy the image on a staging server.
- Checking the HTTP response.
The problem here is that there is no easy way to pass variables to a YAML file, so we will create a helper bash executable file that will pass the variables that we want. In our case, these variables are the WordPress image and the Nginx Image. Let’s name our bash script docker-compose.sh in the location in your home directory, and give it executable permissions with chmod +x docker-compose.sh
As you noticed from this file, the WordPress image is assigned with the variable ${1}, and the Nginx image with the variable ${2}, and it will create a file called wordpress-compose.yaml is the same home location.
The wordpress-compose.yaml file will be created automatically when we execute from within our Jenkins pipeline.
How To Create A WordPress Pipeline
Enough with the theory, let’s dive into the Jenkins code:
This example assumes that all docker-compose related files are residing in /home/user/docker/example.com/
and that the correct permissions are set.
If everything runs correctly, you will see something like this:
Now you have a fresh working WordPress Installation!