Jenkins pipeline to build and push a Django image to dockerhub and GitHub webhook integration.

Photo by Jess Bailey on Unsplash

Jenkins pipeline to build and push a Django image to dockerhub and GitHub webhook integration.

This is the fourth article in the series Deploy a Django app to AWS EC2 instance using Jenkins. A gentle guide to Jenkins.

In this article, you will piece together all the fundamentals that you have learned and build a full Jenkins pipeline that will build and deploy a Django image to Dockerhub. You are required to have gone through the previous articles beforehand

1. Add the init stage and load the script.groovy file.

In your JenkinsFile, add the init stage that loads our groovy script.

def gv  // we define this here to make it globally available. 
pipeline { 

    agent any
    stages { 

        stage('Init') { 

            steps { 
                script { 
                    gv = load "script.groovy"
                }
            }
        }
    }
}

Note that you should have a script.groovy file at the root of your project. If not , kindly create it by:

touch script.groovy

Add the following code inside the script.groovy file

def buildApp() { 
    echo "Building app"
}
return this // returns all the funcs inside the file.

2. Add a test stage to your JenkinsFile (optional).

You will now add a test stage to your JenkinsFile. This is however optional and you may add it if you want to run some tests.

You will first add a testApp function in your script.groovy file.

def testApp() { 
    echo "Testing our application" 
    // you can now run your test command here, e.g if using pytest you run 
    sh "pytest"
}

def buildApp() { 
    echo "Building app"
}

return this

You can now use the testApp func in the test stage in your JenkinsFile.

stage ('test') { 
            steps  { 
                script {
                    gv.testApp()
                }
            }
        }

Disclaimer: This step is optional and can be skipped unless you have tests that you want to run.

3. Add a build stage to your pipeline.

You can now add a build stage to your JenkinsFile, as usual, you first start with adding the buildApp function in the script.groovy file.

You will make use of the withCredentials functionality that you had covered before and the dockerhub credentials we had earlier created.

def buildApp() { 
    echo "Building app with build number #${env.BUILD_NUMBER}" // env variables are available and can be accesed in groovy files.
    withCredentials([usernamePassword(credentialsId:"dockerhub-id", passwordVariable:"PASS", usernameVariable:"USER")]) {        sh "docker build . -t YOUR_REPO_NAME:YOUR_TAG" // replace YOU_REPO_NAME and YOUR_TAG with the respective repo name and tag.
        sh "echo $PASS | docker login -u $USER --password-stdin"
        sh " docker push YOUR_REPO_NAME:YOUR_TAG" // replace YOU_REPO_NAME and YOUR_TAG with the respective repo name and tag.
    }
}

You can now use this in the build step

stage('build') { 
            steps{
                script { 
                    gv.buildApp()
                }
            }
        }

4. Add a deploy step to Jenkins pipeline.

You first add a deployApp to the script.groovy file.

def deployApp() { 
    echo "We will handle this in the next article!"
}

And use it in our JenkinsFile.


stage("deploy"){ 
            steps{
                gv.deployApp()
            }
        }

At the moment, your script.groovy should be similar to

// script.groovy
def testApp() { 
    echo "Testing our application" 
    // you can now run your test command here, e.g if using pytest you run 
    sh "pytest"
}

def buildApp() { 
    echo "Building app with build number #${env.BUILD_NUMBER}" // env variables are available and can be accesed in groovy files.
   withCredentials([usernamePassword(credentialsId:"dockerhub-id", passwordVariable:"PASS", usernameVariable:"USER")]) {
        sh "docker build . -t YOUR_REPO_NAME:YOUR_TAG" // replace YOU_REPO_NAME and YOUR_TAG with the respective repo name and tag.
        sh "echo $PASS | docker login -u $USER --password-stdin"
        sh " docker push YOUR_REPO_NAME:YOUR_TAG" // replace YOU_REPO_NAME and YOUR_TAG with the respective repo name and tag.
    }
}
def deployApp() { 
    echo "We will handle this in the next article!"
}
return this

And the JenkinsFile

def gv // define here for it to be globally available
pipeline { 

    agent any
    parameters { 
        choice(name: 'Version', choices:['1.1.0', '1.2.0', '1.3.0'], description:'')
    }
    stages { 

        stage('Init') { 

            steps { 
                script { 
                    gv = load "script.groovy"
                }
            }
        }
        stage ('test') { 
            steps  { 
                script {
                    gv.testApp()
                }
            }
        }
        stage('build') { 
            steps{
                script { 
                    gv.buildApp()
                }
            }
        }

        stage("deploy"){ 
            steps{
                gv.deployApp()
            }
        }
    }
}

You can now commit and push your changes to the version control of your choice then head over to your Jenkins dashboard and build. It should build successfully without any error. If you need any clarifications, kindly leave a comment and I will reply as fast as I can.

5. Integrate with GitHub.

Up to this point, you have been manually building our jobs, however, in large development teams, this is highly inefficient. You will now look at how to integrate GitHub with our jenkins server so that the jobs can run automatically.

Head over to your GitHub dashboard and click on the settings tab and navigate to the webhooks section.

Screenshot from 2022-08-31 12-56-05.png

In the ‘Payload URL’ field, paste your Jenkins environment URL. At the end of this URL add /github-webhook/. In the ‘Content type’ select: ‘application/json’ and leave the ‘Secret’ field empty

Screenshot from 2022-08-31 12-59-01.png

On the page ‘Which events would you like to trigger this webhook?’ choose ‘Let me select individual events.’ Then, check ‘Pull Requests’ and ‘Pushes’. At the end of this option, make sure that the ‘Active’ option is checked and click on ‘Add webhook’.

You are done with configurations on GitHub, now move to your Jenkins dashboard, select the job that you had created initially and select the Build triggers tab after clicking on configure.

Screenshot from 2022-08-31 13-05-02.png

Check on the GitHub hook trigger for GITScm polling option.

You have now successfully integrated GitHub with Jenkins. Head over to your code editor, make a change, push it to GitHub and you should see a build automatically runs.

In this article, you have come up with a full Jenkins pipeline that pushes a Django image to dockerhub and you have integrated GitHub with Jenkins for automated builds. In the next article, you will learn how to use Multi-branch pipelines , conditionals and how to set up email notifications (finally)

Happy hacking.