Showing posts with label Jenkins Pipelines. Show all posts
Showing posts with label Jenkins Pipelines. Show all posts

Thursday, October 31, 2024

Deploy Python App into Kubernetes Cluster using kubectl Jenkins Pipeline | Containerize Python App and Deploy into EKS Cluster | Kubectl Deployment using Jenkins

We will learn how to automate Docker builds using Jenkins and Deploy into Kubernetes Cluster in AWS Cloud. We will use kubectl command to deploy Docker images into EKS cluster. We will use Python based application. I have already created a repo with source code + Dockerfile. The repo also have Jenkinsfile for automating the following:

- Automating builds using Jenkins
- Automating Docker image creation
- Automating Docker image upload into Elastic container registry
- Automating Deployments to Kubernetes Cluster using kubectl CLI plug-in



Pre-requisites:
1. EKS Cluster is setup and running. Click here to learn how to create EKS cluster.
2. Jenkins Master is up and running.
3. Install Docker in Jenkins.
4. Docker, Docker pipeline and Kubectl CLI plug-ins are installed in Jenkins





5. ECR repo created to store docker images.

The Code for this video is here:
and make necessary changes in eks-deploy-from-ecr.yaml file after you fork into your account.

Step #1 - Create Credentials for connecting to EKS cluster using Kubeconfig
Go to Jenkins UI, click on Credentials -->


Click on Global credentials
Click on Add Credentials

use secret file from drop down.

execute the below command to login as jenkins user.
sudo su - jenkins

you should see the nodes running in EKS cluster.

kubectl get nodes


Create namespace to deploy containers
kubectl create namespace python-app-ns
kubectl get ns

Execute the below command to get kubeconfig info, copy the entire content of the file:
cat /var/lib/jenkins/.kube/config




Open your text editor or notepad, copy and paste the entire content and save in a file.
We will upload this file.

Enter ID as K8S and choose File and upload the file and save.


Step # 2 - Create a pipeline in Jenkins
Create a new pipeline job.


Step # 3 - Copy the pipeline code from below
Make sure you change values as per your settings highlighted in yellow below:

pipeline {
    agent any

    environment {
        registry = "account_id.dkr.ecr.us-east-1.amazonaws.com/coachak/my-docker-repo"
    }
    stages {
        stage('checkout') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/master']], extensions: [], userRemoteConfigs: [[url: 'https://github.com/akannan1087/myPythonDockerRepo']]])
            }
        }
        
        stage ("build image") 
        {
            steps {
                script {
                    dockerImage = docker.build registry
                      dockerImage.tag("$BUILD_NUMBER")
                    }
                }
        }
        
        stage ("upload ECR") {
            steps {
                script {
                    sh "aws ecr get-login-password --region us-east-2 | docker login --username AWS --password-stdin account_id.dkr.ecr.us-east-2.amazonaws.com"
                sh 'docker push account_id.dkr.ecr.us-east-1.amazonaws.com/coachak/my-docker-repo:$BUILD_NUMBER'
                }
            }
        }
        
    // Avoid latest tag image and pass build ID dynamically from Jenkins pipeline
       stage('K8S Deploy') {
        steps{   
            script {
                withKubeConfig([credentialsId: 'K8S', serverUrl: '']) {
                echo "Current build number is: ${env.BUILD_ID}"
               // Replace the placeholders in the deployment.yaml file 
                sh """ 
                sed -i 's/\${BUILD_NUMBER}/${env.BUILD_ID}/g' k8s-deployment.yaml
                """ 
                sh ('kubectl apply -f  k8s-deployment.yaml -n springboot-app-ns')
                }
            }
        }
       }
    }    
}

Step # 4 - Build the pipeline



Step # 5 - Verify deployments to EKS

kubectl get pods


kubectl get deployments
kubectl get services


Steps # 6 - Access Python App in K8S cluster
Once deployment is successful, go to browser and enter above load balancer URL 

You should see page like below:



Thursday, August 26, 2021

How to send approval notification from Jenkins Pipeline to Slack | Trigger Jenkins Job using Webhooks from Slack

How to integrate Slack with Jenkins using webhooks? How to send approval notification from Jenkins to Slack and approve and trigger job from Slack to Jenkins. We need to create webhooks in Slack to send messages to Slack channel.



Pre-requisites:
1. Jenkins is up and running
2. Slack account is is created and channel is created.

Steps to integrate Slack with Jenkins using Webhooks

Create Webhooks in Slack
2. Click on Create an app

3. Select from scratch


4. Name the app and choose the workspace

Now click on incoming webhooks

Enable it by clicking on


Now select the channel where you like to post messages

Now copy the Webhook url which we will be using in Jenkins pipeline:



Now go to Jenkins and create this pipeline:

import groovy.json.JsonOutput

pipeline {
    agent any
    tools {
        maven 'Maven3'
    }
    environment {
        jenkins_server_url = "http://ec2-3-129-59-179.us-east-2.compute.amazonaws.com:8090"
        notification_channel = 'aug-2021-weekday-batch'
        slack_url = 'https://hooks.slack.com/services/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'
        
    }

   stages {
       
    stage('Cloning Git') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/main']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '8b429648-98dd-446a-80c6-120f9eab44fe', url: 'https://github.com/akannan1087/myAug21WeekendRepo']]])     
            }
        }
    stage ('Build') {
      steps {
      sh 'mvn clean install -f MyWebApp/pom.xml'
      }
    }

    stage ('DEV Deploy') {
      steps {
      echo "deploying to DEV Env "
      deploy adapters: [tomcat9(credentialsId: '341bc648-7df9-4b41-b520-9872cd2d8097', path: '', url: 'http://ec2-18-222-124-177.us-east-2.compute.amazonaws.com:8080/')], contextPath: null, war: '**/*.war'
      }
    }
    stage('QA approve') {
        steps {
          notifySlack("Do you approve QA deployment? $jenkins_server_url/job/$JOB_NAME", notification_channel, [])
            input 'Do you approve QA deployment?'
            }
        }
        
    stage ('QA Deploy') {
      steps {
      echo "deploying to QA Env "
      deploy adapters: [tomcat9(credentialsId: '341bc648-7df9-4b41-b520-9872cd2d8097', path: '', url: 'http://ec2-18-222-124-177.us-east-2.compute.amazonaws.com:8080/')], contextPath: null, war: '**/*.war'
      }
    }
    
    }
}

def notifySlack(text, channel, attachments) {

    def payload = JsonOutput.toJson([text: text,
        channel: channel,
        attachments: attachments
    ])

    sh "curl -X POST --data-urlencode \'payload=${payload}\' ${slack_url}"
}


Thursday, April 1, 2021

How to create Multibranch pipeline in Jenkins | Multibranch pipeline tutorial

Let us learn how to create multi branch pipeline using Jenkins.

What is Multi-branch pipeline?

 - Automatically create new pipelines for every Git branch in source version control.

- Enables different pipeline implementation for every branch. for e.g let us say you want to have CICD pipeline for master branch and only CI pipeline for develop branch.

- an automatically discover new branches in the source control (GitHub or any SCM) and automatically create a pipeline for that branch.

Watch the steps in YouTube:

Pre-requisites:

  • Jenkins up and running
  • source code configured in GitHub or any SCM

Create Jenkinsfile first

Please follow the link above to understand how to create Declarative pipeline - Jenkinsfile.

How to create multibranch pipeline?

 Go to Jenkins. Create a new Item. give a name like myMultiBranchPipelineJob

Click ok

Click branch source,  Add source, Add git.

Give your repo URL which has Jenkinsfile already.


Give your Git repo url, credentials. select credentials from the drop down.

Click apply and Save.

Now the pipeline job will automatically scan and creates pipeline per branch.

Tuesday, December 8, 2020

Deploy Python App Docker Container into Amazon EKS Cluster using Jenkins Pipeline | Containerize Python App and Deploy into EKS Cluster

We will learn how to automate Docker builds using Jenkins and Deploy into AWS EKS - Kubernetes Cluster. We will use Python based container application. I have already created a repo with source code + Dockerfile. The repo also have Jenkinsfile for automating the following:


- Automating builds using Jenkins
- Automating Docker image creation
- Automating Docker image upload into Docker registry
- Automating Deployments to Kubernetes Cluster





Pre-requisites:
1. Amazon EKS Cluster is setup and running. Click here to learn how to create Amazon EKS cluster.
3. Setup Jenkins slave, install docker in it.
4. Docker, Docker pipeline and Kubernetes Deploy plug-ins are installed in Jenkins



5. Docker hub account setup in https://cloud.docker.com
6. Install kubectl on your instance


Step #1 -Make sure Jenkins can run Docker builds after validating per pre-requisites

Step #2 - Create Credentials for Docker Hub
Go to Jenkins UI, click on Credentials -->


Click on Global credentials
Click on Add Credentials


Now Create an entry for your Docker Hub account. Make sure you enter the ID as dockerhub

Step #3 - Create Credentials for Kubernetes Cluster
Click on Add Credentials, use Kubernetes configuration from drop down.


execute the below command to get kubeconfig info, copy the entire content of the file:
sudo cat ~/.kube/config


Enter ID as K8S and choose enter directly and paste the above file content and save.

Step #4 - set a clusterrole as cluster-admin

By default, clusterrolebinding has system:anonymous set which blocks the cluster access. Execute the following command to set a clusterrole as cluster-admin which will give you the required access.

kubectl create clusterrolebinding cluster-system-anonymous --clusterrole=cluster-admin --user=system:anonymous

Step # 5 - Create a pipeline in Jenkins
Create a new pipeline job.


Step # 6 - Copy the pipeline code from below
Make sure you change red highlighted values below:
Your docker user id should be updated.
your registry credentials ID from Jenkins from step # 1 should be copied

pipeline {
     agent {
         label 'myslave'
     }
        environment {
        //once you sign up for Docker hub, use that user_id here
        registry = "your_docker_hub_user_id/mypython-app"
        //- update your credentials ID after creating credentials for connecting to Docker Hub
        registryCredential = 'dockerhub'
        dockerImage = ''
    }
    stages {

        stage ('checkout') {
            steps {
            checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[url: 'https://github.com/akannan1087/myPythonDockerRepo']]])
            }
        }
       
        stage ('Build docker image') {
            steps {
                script {
                dockerImage = docker.build registry
                }
            }
        }
       
         // Uploading Docker images into Docker Hub
    stage('Upload Image') {
     steps{   
         script {
            docker.withRegistry( '', registryCredential ) {
            dockerImage.push()
            }
        }
      }
    }
   
    stage ('K8S Deploy') {
        steps {
            script {
                kubernetesDeploy(
                    configs: 'k8s-deployment.yaml',
                    kubeconfigId: 'K8S',
                    enableConfigSubstitution: true
                    )           
               
            }
        }
    }
  
    }  
}

Step # 7 - Build the pipeline
Once you create the pipeline and changes values per your Docker user id and credentials ID, click on 

Step # 8 - Verify deployments to K8S

kubectl get pods


kubectl get deployments
kubectl get services

Steps # 9 - Access Python App in K8S cluster
Once build is successful, go to browser and load balance url along with port number mentioned above
http://load_balancer_url:port_no_from_above

You should see page like below:



Master DevSecOps and Multi Cloud Computing Course by Coach AK | DevSecOps and Cloud Computing Online Classes | Sep 2025 Schedule

  Master DevSecOps and cloud Computing Bootcamp Schedule for Sep 2025 Are you ready to  supercharge your career  in  DevSecOps ? Whether you...