CI CD jenkins pipeline for python app deploy to kubernetes

Run ec2 server with t2.medium configuration

Step1: create role for ec2 server to access EKS

Create Iam role.

click on next

give policy administrator access.

click on create

Modify instance and give this role.

click on modify Iam Role.

give this role which we have created.

Step2: Installation of jenkins

Install jenkins in ec2 server.

install

  • awscli

  • eksctl

  • kubectl

setup jenkins server and install plugins

  • docker

  • docker pipeline

  • kubernetes cli

create Project with demo name

select pipeline and create .

put this code on pipeline.

pipeline{


    stages {
        stage('clean workspace'){
            steps{
                cleanWs()
            }
        }
        stage('Checkout from Git'){
            steps{
                git branch: 'main', url: 'https://github.com/harish343/pythonwebserver.git'
            }
        }

        stage("Docker Build & Push"){
            steps{
                script{
                   withDockerRegistry(credentialsId: 'docker', toolName: 'docker'){
                       sh "docker build -t webserver ."
                       sh "docker tag webserver harish343/websever:latest "
                       sh "docker push harish343/webserver:latest "
                    }
                }
            }
        }
        stage('Deploy to kubernets'){
            steps{
                script{
                    dir('Kubernetes') {
                        withKubeConfig(caCertificate: '', clusterName: '', contextName: '', credentialsId: 'k8s', namespace: '', restrictKubeConfigAccess: false, serverUrl: '') {
                                sh 'kubectl apply -f deployment.yml'
                                sh 'kubectl apply -f service.yml'
                        }
                    }
                }
            }
        }
    }

}

Step3: Create EKS cluster

eksctl create cluster --name demo-eks --region us-east-1 --nodegroup-name my-nodes --node-type t3.small --managed --nodes 2

check cluster name.

eksctl get cluster --name demo-eks --region us-east-1

Update Kube config by entering below command:

aws eks update-kubeconfig --name demo-eks --region us-east-1

you have successfully updated kubeconfig file.

step4: Setting up credentials for Docker and kubernetes

click on pipeline syntax

select withkubeconfig cred

here you can add kubernetes cluster cred.

copy it from your jenkins server and save it on your local computer with config name.

add jenkins cred

give id of kubernetes config

setup for docker

add docker credentials

save it

click on pipeline configure

paste all pipeline code in script

make sure you have paste your kubernetes config ID and docker Cred ID.

run this pipeline.

deployment is already exposed.

kubectl get svc

open this external ip in web browser.