mateothegreat
6/5/2018 - 5:48 AM

Jenkins pipeline with k8/docker support

Jenkins pipeline with k8/docker support

pipeline {

    agent any

    options {

        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '1'))

    }
    parameters {

        choice(name: 'ENVIRONMENT',             choices: "Production",          description: 'Select target environment')

        booleanParam(defaultValue: true, name: 'PROVISION', description: 'Provision Kubernetes Infrastructure')

        string(name: 'CLUSTER_NAME',        defaultValue: 'your-cluster-na',    description: 'GKE Cluster Name') 
        string(name: 'CLUSTER_ZONE',        defaultValue: 'us-central1-a',      description: 'GKE Cluster Zone') 
        string(name: 'PROJECT',             defaultValue: 'asdfasdfasdf',       description: 'Google Cloud Project Name')
        string(name: 'REPOSITORY_NAME',     defaultValue: 'asdfasdfasdf-v1',    description: 'Google Cloud Repository Name') 

    }

    environment {

        IMAGE_TAG         = "${env.GIT_COMMIT}"

    }

    stages {

        stage('Notify Slack') {

            steps {

                slackSend (token: 'ek3r55KGGtmfs5edI1TdktG0', baseUrl: 'https://hooks.slack.com/services/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', channel: '#development', color: '#0000FF', message: "BUILD STARTED: For 'blitzalytics-v1', Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' (${env.BUILD_URL})")

            }

        }

        stage('Setup gcloud cli') {

            steps {

                sh "gcloud container clusters get-credentials ${params.CLUSTER_NAME} --project=${params.PROJECT} --zone=${params.CLUSTER_ZONE}"
                sh "echo Y | gcloud auth configure-docker"

            }

        }

        stage('Checkout source code from gcloud') {

            steps {

                sh "gcloud source repos clone ${params.REPOSITORY_NAME} --project=${params.PROJECT}"
                sh "ls -la"
                sh "cd ${params.REPOSITORY_NAME}"
                sh "ls -la"


            }

        }

        stage('Build Docker Image') {

            steps {

                dir("${params.REPOSITORY_NAME}") {

                    echo "*** Building docker image with IMAGE_TAG: ${IMAGE_TAG}"

                    sh "pwd"
                    sh "ls -la"

                    sh "docker build -t gcr.io/${params.PROJECT}/${params.REPOSITORY_NAME}:${IMAGE_TAG} ."
                    sh "docker push gcr.io/${params.PROJECT}/${params.REPOSITORY_NAME}:${IMAGE_TAG}"

                }

            }

        }

        stage('Update Deployment(s)') {

            steps {

                sh "kubectl set image deployment/${params.REPOSITORY_NAME} *=gcr.io/${params.PROJECT}/${params.REPOSITORY_NAME}:${IMAGE_TAG}"

            }

        }

    }

    post { 

        always { 

            cleanWs()

        }

    }

}