Tuesday, November 23, 2021

Jenkins Basic


Jenkins
CI/CD

CI - Develop- github-sonarqube-maven-Java/gradle-android/ant-.net
CD- Ansible - deployment

JOB-1 Develop- github-sonarqube-maven-Java/gradle-android/ant-.net
JOB-2 - if 1st job success - Ansible - deploy build in production

Devops guy task
1.Devops guy should have knowledge about plugins
eg. plugin need for maven, gradle etc.

2. should know about how to create jobs, integration
single job, multi-job, connected to each other

3. Troubleshooting about jenkins server.
eg. if server goes down, jenkins should running in master, slave mode

4. should aware about access and delegation
structure way to create id pass, role assignment, access delegation, some job access we dont want give all users.

5. should aware about how to take backups

6. if code getting break, devops guy should aware about issue coming due to jerkins hardware limitation or something else.

 

 

How to Install Jenkins
Windows / Linux both supported

Platform
On prem
VM
Cloud
Container

256MB RAM 1 GB HDD
container

1gb ram, 10gb HDD, 1cpu
VM

In prod generally
32gb ram, 1TB 8cpu

Jenkins default port - 8080
how to change Jenkins port?

1. Start by opening the Jenkins configuration file with:
sudo nano /etc/default/jenkins
2. Scroll down until you find the following lines:
# port for HTTP connector (default 8080; disable with -1)
HTTP_PORT=8080
3. Edit the second line to include the port number you want to specify. For instance:
HTTP_PORT=8081
sudo systemctl restart jenkins

 

Install Jenkins on Linux

yum update -y

yum install java* -y 
go to jenkins.io website, download Jenkins from there.
yum install url -y

systemctl start jenkins

systemclt enable jenkins

now go to browser access with publicip:8080

Unlock Jenkins, find Auth pass from the path shows on jenkins_web_url:8080

now customize install suggested plugins 

create username / password for login 

Now you are logged in

 

video 3

Install jenkins on windows.

 

How we able to access Jenkins console?

video 4
Jenkins installation on docker

Requirement of installing jenkins on docker
When we have multiple project and only jenkins setup we need to do


yum update -y
yum install docker* -y

systemctl start docker
systemctl enable docker

go to jenkins website.
click on docker option
it will take to docker hub

docker pull jenkins/jenkins

Docker is need to install 1st
docker container ls
docker container run -itd -p 8081:8080 jenkins

docker container exec -it container_name /bin/bash
cd /var/jenkins_home/secrets/
cat initialAdminPassword

Install Suggest Plugins

Video 5

How to integrate git to Jenkins?
Copy Jenkins server ip and port
go to git webhook and update in webhook.



Payload URL
http://34.203.75.12:8080/github-webhook/

Content type
application/json


Secret
118e5a86bc7da6d4fc36fcaa504e253       
this token we have generated in jenkins




go to jenkins click on username for Secret create token over there. 



And paste this token in git hub when you configure in webhook.

git repo URL need to paste in
Job - General - Source Code Managment

Make sure you have installed git in Jenkins server.
paste git source code repo in Jenkins - save.

so now if you build it will pick the code from github
Build now 

 

Lab 1
1.setup a EC2 machine.
2.install git on that.
3.install java on it.
4.install jenkins on it.
5.start all service.
6.integrate git in jenkins(General, Source Code Managment)
7.test build now.

8.Or in case if you have configured job trigger,
it will run the job accordingly.



Job are also call projects

job trigger
1. Build now, - Manual
2. Trigger builds remotely
3. Build after other Projects are build
eg Job2 will run after Job1 one is done
4. Build Periodically    (cron is set for evr 5min, build will create evr 5 min)
5. Poll SCM (cron is set for evr 5min, so it will go to git, and check if any new commit receive, it will run only if new commit receive.)
6. Git HUB hook trigger for GITScm Polling (It will run only when new comit comes in git) - this is most used way with git

Video - 6
Create Project on Jenkins
Git - Jenkins - Ansible    (git integration with jenkins )



Lab Project

1.Developer-Machine
2.Jenkins-Server
3.Ansible-Server
4.Web-Server
    |
    |
    |
      website
5. git


2.Jenkins-server
go to jenkins website
https://www.jenkins.io/doc/book/installing/linux/#red-hat-centos,

sudo wget -O /etc/yum.repos.d/jenkins.repo \
    https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
sudo yum upgrade
sudo yum install epel-release java-11-openjdk-devel
sudo yum install jenkins
sudo systemctl daemon-reload

yum install git* -y


3. go to Ansible-server
yum install ansible2

vim /etc/ansible/hosts
...
[web]
webserver_ip

4. go to webserver

yum install httpd -y
systemctl start httpd
systemctl enable httpd

password less connection b/w ansible and webserver
vim /etc/ssh/sshd_config
PermitRootLogin yes
PasswordAuthentication yes
:wq

systemctl restart sshd

3. go to Ansible server

ssh-keygen
ssh-copy-id -i root@webserver_ip

for testing purpose create 1 playbook and run
mkdir /sourcecode
cd /sourcecode
vim playbook.yml
- hosts: all
  tasks:
     - copy:
          src: /opt/index.html
          dest: /var/www/html

git
create a new repo

integrate git with jenkins

Copy Jenkins server_ip and port
go to git webhook and update in webhook.


Payload URL
http://34.203.75.12:8080/github-webhook/

Content type
application/json


Secret
118e5a86bc7da6d4fc36fcaa504e253       
this token we have generated in jenkins




go to jenkins click on username for Secret create token over there. 


And paste this token in git hub when you configure in webhook.

git repo URL need to paste in
Job - General - Source Code Managment

Make sure you have installed git in Jenkins server.
paste git source code repo in Jenkins - save.


Need to install plugin in jenkins
use case

when jenkins build, and output will put in ansible server,
then need ssh connection b/w jenkins and ansible server.
Publish over ssh


 

go to Manage Jenkins - Configure System

scroll to bottom you will see SSH Server





now if you test the connection, if its get failed, means, on jenkins server, root password not enable,
 

vim /etc/ssh/sshd_config
PasswordAuthentication yes
:wq

systemctl restart sshd

Now check again if test success

after that for build file need to push ansible,
configuration in jenkins for the same.

 


Now if you build, it will pull file from git, and it will build, and then push to ansible server.
 

Now after build, if you want to do post build action
For Send build artifacts over SSH

1st Add new connection from Jenkins - configuration



Now you can test once, if its getting success, if its fail, check passwordauthentication is yes in sshd.config file on ansible server

 

Now go to Jenkins - Job(demo-project)
Send build artifacts over SSH
you will be able to see Ansible in drop down.


 

 Now build it. the code should be go and deploy the webserver.

you can go to developer system, now commit new code its should get deploy automatically now on webserver.

Video 7

Deploy a website on docker container with jenkins help.


create 3 machine
1.Jenkins
2.Ansible
3.Docker-host

On Jenkins server

install Jenkins go to below website and download jenkins
https://www.jenkins.io/doc/book/installing/linux/#red-hat-centos,

OR

sudo wget -O /etc/yum.repos.d/jenkins.repo \
    https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
sudo yum upgrade -y
sudo yum install epel-release java-11-openjdk-devel -y
sudo yum install jenkins
sudo systemctl daemon-reload
 

install git
yum install git -y


set root password
vim /etc/ssh/sshd_config
PermitRootLogin yes
PasswordAuthentication yes
restart sshd service


create ssh-keygen
make copy ssh-keygen to ansible server
ssh-copy-id -i root@ansible_ip


install Public Over SSH plugin on jenkins
go to Manage Jenkins - Configure System - In bottom SSH there
Click on Add button in SSH
1st add jenkins
name
private ip_add
username-
Click on Advance - Click user pass auth.
pass - test config



2nd add Ansible
name
private ip_add
username-
Click on Advance - Click user pass auth.
pass - test config

On Ansible server

install ansible service
yum install ansible -y

Integrate Git on Jenkins
go to git create repo
Paste code   
FROM centos:latest
#MAINTAINER: sanjay.dahiya332@gmail.com
RUN yum install -y httpd \
zip \
unzip
ADD https://www.free-css.com/assets/files/free-css-templates/download/page247/kindle.zip /var/www/html
WORKDIR /var/www/html
RUN unzip kindle.zip
RUN cp -rvf markups-kindle/* .
RUN rm -rf __MACOSX markups-kindle kindle.zip
CMD ["/usr/sbin/httpd", "-D", "FOREGROUND"]
EXPOSE 80

go to webhooks

Payload URL - http://3.17.131.251:8080/github-webhook/
Content type - application/json
Secret - 11f46d2a103add56aff0c80d5cf5c0b2cd- paste token generated in jenkins

Now create job
General - Git - Repository URL - 



Build
Send files or executed commands over SSH
Name - Jenkins
Transfers - Exec commands -
rysnc -avh /var/lib/jenkins/workspace/cloudknowledge-job/Dockerfile root@172.31.21.99:/opt



Build - Add build step -
Send files or executed commands over SSH
Name - Ansible
Transfers - Exec commands -
cd /opt
docker image build -t $JOB_NAME:v1.$BUILD_ID .
docker image tag $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.$BUILD_ID
docker image tag $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:latest
docker image push manjeetyadav19/$JOB_NAME:v1.$BUILD_ID
docker image push manjeetyadav19/$JOB_NAME:latest
docker image rmi $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:latest



Post Build Actions - Add post-build action
Send build artifacts over SSH
SSH Server
Name - Ansible
Exec command - ansible-playbooks /sourcecode/docker.yml    



Build Now


go to ansible hosts file
/etc/ansible/hosts
[dockerhost]
private_ip

 
set-root password
copy ssh-keygen to docker server
install docker
start docker service
login docker private repo on docker hub
 

go to cd /opt
mkdir /sourcecode
cd /sourcecode
vim docker.yml
- hosts: all
  tasks:
     - name: stop container
       shell: docker container stop cloudknowledge-container
     - name: remove container
       shell: docker container rm cloudknowledge-container
     - name: stop docker image
       shell: docker image rm  manjeetyadav19/cloudknowledge-job
     - name: create container
       shell: docker container run -itd --name cloudknowledge-container -p 9000:80 manjeetyadav19/cloudknowledge-job

On docker host server

install docker and start service

vim /etc/ssh/sshd_config
PermitRootLogin yes
PasswordAuthentication yes

restart sshd service
install docker service
start docker service

video - 8

deployment jenkins with kubernetes.

Kubernetes Cluster setup through kops
Create IAM Role- full access - EC2,ROUTE53,S3,

Create 1 EC2
tag - controller Machine
attach IAM role - lunch EC2

Login in EC2
aws configure
aws acess key id:
aws secret access key:
Default region name: ap-south-1

install Kops & kubectl
reference:
https://kubernetes.io/docs/setup/production-environment/tools/kops/

Install kubectl on Linux
curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

Install kubectl
reference:
https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/

#sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
sudo install -o root -g root -m 0755 kubectl /bin/kubectl

#chmod +x kubectl
chmod +x ./kubectl

#mkdir -p ~/.local/bin/kubectl
#mkdir -p /bin/kubectl

#mv ./kubectl ~/.local/bin/kubectl
mv ./kubectl /bin/kubectl

kubectl version --client

Install kops
curl -LO https://github.com/kubernetes/kops/releases/download/$(curl -s https://api.github.com/repos/kubernetes/kops/releases/latest | grep tag_name | cut -d '"' -f 4)/kops-linux-amd64

chmod +x kops-linux-amd64
sudo mv kops-linux-amd64 /bin/kops

Create a route53 domain for your cluster
Go to Route53
create domain
name - cloudknowledges.in
Private hosted zone
Region
VPC ID
Create hosted zone

Create an S3 bucket to store your cluster state
aws s3 mb s3://clusters.cloudknowledges.in        domain here should be same you created in route53
export KOPS_STATE_STORE=s3://clusters.cloudknowledges.in

ssh-keygen

Build your cluster configuration
kops create cluster --cloud=aws --zones=us-east-1c --name=clusters.cloudknowledges.in --dns-zone=cloudknowledges.in --dns private


 

now its store the states in S3 bucket, and it will give 1 cmd to run
kops update cluster --name cloudindia.cloudknowledges.in --yes

Now it will take around 10 minutes to create cluster


Once its create, it will show you the cluster
run
kubectl get nodes
And if you go to the AWS EC2 interface you will see the EC2 instances also.



Now create 2 VM
1. Ansible Server
2. Jenkins Server

 

Jenkins server

install Jenkins go to below website and download jenkins
https://www.jenkins.io/doc/book/installing/linux/#red-hat-centos,

OR

sudo wget -O /etc/yum.repos.d/jenkins.repo \
    https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
sudo yum upgrade -y
sudo yum install epel-release java-11-openjdk-devel -y
sudo yum install jenkins
sudo systemctl daemon-reload
 

install git
yum install git -y


set root password
vim /etc/ssh/sshd_config
PermitRootLogin yes
PasswordAuthentication yes
restart sshd service


create ssh-keygen
make copy ssh-keygen to ansible server
ssh-copy-id -i root@ansible_ip


install Public Over SSH plugin on jenkins
go to Manage Jenkins - Configure System - In bottom SSH there
Click on Add button in SSH
1st add jenkins
name
private ip_add
username-
Click on Advance - Click user pass auth.
pass - test config



2nd add Ansible
name
private ip_add
username-
Click on Advance - Click user pass auth.
pass - test config

 On Ansible server

install ansible service
yum install ansible -y

install git service
yum install git -y

Make connection b/w Ansible and Kubernetes cluster
two ways
1. paste ssh-key to controller machine
2. paste ssh-key to master-node

if do with controller machine, we will run the command via controller only then

go to jenkins machine
copy key from .ssh/id_rsa.pub

go to controller machine
paste key to .ssh/authorized_keys

Install docker on ansible
yum install docker -y

systemctl start docker
systemctl enable docker

Password less connection b/w Jenkins and Ansible

go to jenkins machine
copy key from .ssh/id_rsa.pub

go to Ansible machine
paste key to .ssh/authorized_keys

docker login also required on ansible server for push image to dockerhub

create playbook
cd /opt
vi ansible.yml
- hosts: all
  become: true
 
  tasks:
  - name: create service
    command: kubectl apply -f /opt/deployment.yml

  - name: create service
    command: kubectl apply -f /opt/service.yml

add controller machine ip in ansible host file
vim /etc/ansible/hosts
..
[kube]
controller_ip


go to controller machine and create below files
deployment.yml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: cloudknowledges
spec:
  selector:
    matchLabels:
      app: cloudknowledges
    replicas: 2
    strategy:
      type: RollingUpdate
      rollingUpdate:
        maxSurge: 1
        maxUnavailable: 1
  template:
    metadata:
      labels:
        apps: cloudknowledges
    spec:
      containers:
      - name: cloudknowledges
        image: manjeetyadav19/kubernetesproject
        imagePullPolicy: Always
        ports:
        - containerPort: 80

service.yml
apiVersion: v1
kind: Service
metadata:
  name: cloudknowledges
  labels:
    app: cloudknowledges
spec:
  selector:
    app: cloudknowledges
  type: LoadBalancer
  ports:
    - port:8080
      targetPort: 80
      nodePort: 31200
 


create repo on git
manjeetyadav19/kubernetesproject
 

Dockerfile
go to git create repo
Paste code   
FROM centos:latest
#MAINTAINER: sanjay.dahiya332@gmail.com
RUN yum install -y httpd \
zip \
unzip
ADD https://www.free-css.com/assets/files/free-css-templates/download/page247/kindle.zip /var/www/html
WORKDIR /var/www/html
RUN unzip kindle.zip
RUN cp -rvf markups-kindle/* .
RUN rm -rf __MACOSX markups-kindle kindle.zip
CMD ["/usr/sbin/httpd", "-D", "FOREGROUND"]
EXPOSE 80

Integrate git with Jenkins

go to webhooks

Payload URL - http://3.17.131.251:8080/github-webhook/
Content type - application/json
Secret - 11f46d2a103add56aff0c80d5cf5c0b2cd- paste token generated in jenkins

Now create job - kubernetesporject
General - Git - Repository URL - 
 

Add build step - 

Send files or execute commands over SSH - For Jenkins

rsync -avh /var/lib/jenkins/workspace/kubenetesproject/* root@ansible_ip/opt


 

Add build step - 

Send files or execute commands over SSH - For Ansible

cd /opt
docker image build -t $JOB_NAME:v1.$BUILD_ID .
docker image tag $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.$BUILD_ID
docker image tag $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:latest
docker image push manjeetyadav19/$JOB_NAME:v1.$BUILD_ID
docker image push manjeetyadav19/$JOB_NAME:latest
docker image rmi $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:latest


Post-Build Actions

Send Build artifacts over SSH

ansible-playbook /opt/ansible.yml


Now Build. - 1st time it will deply the website on Kubernetes cluster.

If you build again, it will not change anything now, so if you want to change another website.

Please change in ansible playbook.

vi ansible.yml
- hosts: all
  become: true
 
  tasks:
  - name: delete old deployment
    command: kubectl delete -f /opt/deployment.yml

  - name: create service
    command: kubectl delete -f /opt/service.yml

  - name: create service
    command: kubectl apply -f /opt/deployment.yml

  - name: create service
    command: kubectl apply -f /opt/service.yml

Now build again, it will do the changes

Video 9


In above projects we done CI/CD in 1-Job.
Now in this project we create CI JOb, and CD - Job seprately.
and if CI-Job complete, then CD-JOb will start.


Create CI job



Integrate Git

define build trigger

Build

Add build step

Send files or execute connections over SSH


rsync -avh /var/lib/jenkins/workspace/ci* root@ansible_ip:/opt


 

Post-build actions

Send build artifacts over SSH

Send files or execute commands over SSH - For Ansible

cd /opt
docker image build -t $JOB_NAME:v1.$BUILD_ID .
docker image tag $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.$BUILD_ID
docker image tag $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:latest
docker image push manjeetyadav19/$JOB_NAME:v1.$BUILD_ID
docker image push manjeetyadav19/$JOB_NAME:latest
docker image rmi $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:latest


 

Create CD job

 

 
We need to mention in CD job
once CI complete then only CD job should run.
 

Post Build actions
 



We are continuing the video 8 project, so please change image name in deployment.yml like
manjeetyadav19/ci
 
Now for testing purpose, Run ci job only build manually, cd job will start automatically once CI job finish 

For checking on controller
kubectl get all
 

check again in browser now.

Now if you change in git code (dockerfile) and commit, it will run and trigger automatically.

Video 10

In industry, mostly work happen from groovy script pipeline script, and majorly from declarative pipeline script.

Until now we were using plugins method, that is really use very less in the market.

How we create groovy script pipeline?
 

Difference b/w Freestyle and Pipeline
In Pipeline - Organizing complex activity that do not easily fit in free-style job type.


When we call pipeline?
when we connect multiple job together we called it Pipeline.

How to connect multiple jobs together?
Using plugins, like Public Over SSH etc.

But if we are able to create pipeline using plugins, so why groovy script required?
Benefits of groovy script

why we create multiple jobs, if we can do build, test, QA, deploy in 1 job.
Becz we want to separate each task, like build, test, QA deploy.
We want to put test task in test job
build task in build job. etc.

And if have requirement to run 50 or 200 jobs in 1 pipeline,
and demand is that each task need to keep separate, that's why we need to create 200 jobs,
Now suppose if we had 20-40 task in each job, but now got requirement to keep each task separately, so need to create so many jobs.
And now if we try to integrate each job with each other, technically its will be very tough and challenging.
and Maintenance is also very difficult.
 
if we using groovy script do we still need to create 200 jobs as per requirement?
we create single job -1st time from jenkins UI, and then we create - multiple stage for each task.

Benefit of groovy script
1. you can write script on UI also.
2. you can write script any remote system also, if you using groovy declarative method


3. if we need to skip temporary any task(job)/(stage we called in groovy) we can do it in groovy.
4. in groovy we have idempotency, but in plugin pipeline we dont have, means suppose in plugin pipeline if we have 4 task there, three completed, but 4th have issue, so once we fix it, it will start again from starting 1st task.
But if using groovy, it will start only from 4th job where we got issue.
Use case, suppose we have 100 task/jobs/stage it will take so much time if we start again build. but if we using groovy, its start from where we got failed last-time.
5. we can use conditions/loops in groovy script
e.g. some job should run only if we have specified config. infra only.

6. when we have multiple jenkins server, 1 master, 2 slave, mostly in plugin pipeline, jobs run on slave node only if master is down.
but in groovy, we have concept of load sharing as well, so we dont want to put load on master node, we can use groovy script method.




We have 2 method in groovy script
1. scripted pipeline
2. declarative pipeline

scripted
node{
    stage('build'){
    echo "welcome to build stage"
    }
    
    stage('Test'){
    echo "welcome to test stage"
    }
    
    stage('QA'){
    echo "welcome to QA stage"
    }
    
    stage('deploy'){
    echo "welcom to deploy stage"
    }
 
Declarative

pipeline{
        agent any
        stages{
              stage('build'){
                   steps{
                          echo "welcome to build"
                   }
              }
              stage('Test'){
                   step{
                        echo "Welcome to test stage"
                   }
              }
        }
}


benefit of declarative pipeline over scripted
1. Restart functionality.
2. Skip stage
3. loop/condition
4. remote script creation, updation/edit option, after 1st job created.
5. idempotent, if something failed in scripted, it will run again in scripted, in declarative it will check syntax 1st, if syntax issue it will not run at all.


Video 11


two server required
1. Jenkins
2. docker-host

Create a pipeline
scripted-pipeline-demo


There is 2 option in pipeline
1.Pipeline script - scripted
2.Pipeline script from SCM - declarative


if you know the syntax you can type in script area.
But if you dont know the proper syntax,
Click on Pipeline syntax


eg.
if want to know git integration script


now copy this code, and paste it in pipeline script.


Now you can run and test this pipeline.

So once you run its show on 1 page, it will show logs also on same page.


Now build 2nd stage

stage("Build Docker File"){
sh 'docker image build -t $JOB_NAME:v1.$BUILD_ID' .'
sh 'docker image tag $JOB_NAME:v1.$BUILD_ID' manjeetyadav19/$JOB_NAME:v1.$BUILD_ID'
sh 'docker image tag $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.latest'
}

now build again.

 

becz Docker is not installed on jenkins server.

after install docker build again

Now you get error regarding docker user did not login. so need to login also to docker hub.

Now in stage three we push image to docker hub
stage("Push Image To Docker HUB"){
sh 'docker login -u manjeetyadav19 -p manjeetyadav@123'
}

but its not secure, we cant expose our password.

so go to Pipeline syntax
Sample Step:
withCredentials: Find credentials to variables

create script code for hide credentials:





Now put that script in stage three

stage("Push Image To Docker HUB"){
withCredentials([string(credentialsId: 'dockerhubpassword', variable: 'dockerpassword.........'})
//some block
sh 'docker login -u manjeetyadav19 -p $(dockerpassword)'
sh 'docker image push manjeetyadav19/$JOB_NAME:v1.$BUILD_ID'
sh 'docker image push manjeetyadav19/$JOB_NAME:latest'
sh 'docker image rmi $JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:v1.$BUILD_ID manjeetyadav19/$JOB_NAME:latest'

}

Now save and run


Now save and build.



Stage 4,
Deployment of docker container, on remote machine,
For this you need connection to remote machine.
you need to check in plugins if you have Public Over SSH plugin there.
If yes then good, if now, install 1st

Now search again in syntax pipeline, you will able to see the plugin
sshagent: SSH Agent


 





after paste this code, how to check we ssh to remote machine, see below snap, we can click on question mark in syntax pipeline portal it will show you.



stage("Deployment of Docker container"){
{
def dockerrun = 'docker run -p 8000:80 -d --name cloudknowledges manjeetyadav19/scripted-pipeline-demo:latest'
sshagent([dockerhostpassword]){
//some block
sh "ssh -o StrictHostKeyChecking=no ec2-user@172.31.14.200 ${dockerrun}"
}
}
}

Build now,

Now you can get error regarding docker not installed on remote host
and error regarding folder permission /var/run/docker.sock

After that check on host public ip with port the website got deployed now.

after 1st deployment, if developer want to change another website.

but when its run again, it got error container already exist in use



Build again, now its build without any error, but still new deployment not visible on website link.
Becz, in docker container, it build again from local image on docker host, it did not go to docker hub,
so sol. we need to delete image also.

stage("Deployment of Docker container"){
{
def dockerrun = 'docker run -p 8000:80 -d --name cloudknowledges manjeetyadav19/scripted-pipeline-demo:latest'
def dockerrm = 'docker container rm -f cloudknowledges'
def dockerimagerm = 'docker image rmi manjeetyadav19/scripted-pipeline-demo'
sshagent([dockerhostpassword]){
//some block
sh "ssh -o StrictHostKeyChecking=no ec2-user@172.31.14.200 ${dockerrm}"
sh "ssh -o StrictHostKeyChecking=no ec2-user@172.31.14.200 ${dockerimagerm}"
sh "ssh -o StrictHostKeyChecking=no ec2-user@172.31.14.200 ${dockerrun}"
}
}
}


--------------------------------------

Jenkins installation on aws

sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key
amazon-linux-extras install epel -y
amazon-linux-extras install java-openjdk11 -y
yum install jenkins.noarch -y
systemctl start jenkins.service

----------------------------------------

Jenkins Declarative Pipeline

pipeline {
    agent any
    stages {
        stage ("hello"){
            steps{
                echo "Welcome to jenkins pipeline"
            }
    
        }
    }
    stages{
        stage ("Test"){
            steps{
                echo "git"
            }
        }
        
    }
    stages {
        stage ("Deploy"){
             steps {
                echo "Hello World!"
                sh "echo Hello from the shell"
                sh "hostname"
                sh "uptime"
            }
    
        }
    }
    post
    {
        always
        failure
        {
            emailext body: 'Summary', subject: 'Pipeline status', to: 'manjeetyadav19@gmail.com'
        }
    }
}


No comments:

Post a Comment