Jenkins
Creating your first job
Executing your first job
Execute shell with variable
Executing bash script from jenkins
#!/bin/bash
FIRSTNAME=$1
LASTNAME=$2
echo "welcome $FIRSTNAME $LASTNAME"
./myscript.sh pulkit pushkarna
FIRSTNAME=Pulkit
LASTNAME=Pushkarna
/Users/pulkitpushkarna/test-dir/myscript.sh $FIRSTNAME $LASTNAME
Build with parameters
Adding choice and boolean parameters
#!/bin/bash
FIRSTNAME=$1
LASTNAME=$2
DESIGNATION=$3
SHOW=$4
if $SHOW
then
echo "Welcome $FIRSTNAME $LASTNAME $DESIGNATION"
else
echo "Show parameter set to false"
fi
/Users/pulkitpushkarna/test-dir/myscript.sh $FIRSTNAME $LASTNAME $DESIGNATION $SHOW
Exercise 1
Integration with Gradle
git remote add origin <git-hub-url>
deploy.sh
#!/bin/bash
export BUILD_ID=dontKillMe
app_id=$(ps -ef | grep 'jenkins-maven-0.0.1-SNAPSHOT.jar' | grep -v 'grep' | awk '{ printf $2 }')
kill -9 $app_id
nohup java -jar ./build/libs/basic-app-0.0.1-SNAPSHOT.jar &
Deploy Spring Boot App using Jenkins
Trigger build and deploy job on push to master
Webhook Trigger
Create proxy for jenkins github webhook by using the command below
relay forward --bucket github-jenkins http://localhost:8080/github-webhook/
Forwarding:
https://0mu5u7hnaddxwio6oebtae.hooks.webhookrelay.com -> http://localhost:8080/github-webhook/
Starting webhook relay agent...
2022-01-20 19:33:59.164 INFO using standard transport...
Now go to you git repo in the setting tabs select the webhook and in the webhook payload URL enter the url generated by relay and in the Content Type select application/json.
Now if you push any changes in master branch the build will trigger automatically and latest code will be deployed.
Deploy maven app using jenkins
Setting up maven
Give the maven installation and name it maven job
Create a job to build and deploy maven project
Set up the build steps
Now run the job and you will see that you are able to deploy the app.
Exercise 2
Jenkins DSL
In the Build Triggers section go to build and select the build step Process Job DSLs
Now you can start writing DSL to generate new job
Create job with description
Now build this job and you will be able to see tha a new job with the name job-dsl-example is created.
job("job-dsl-example"){
description("This job is generated by seed job")
parameters{
stringParam("Name",defaultValue="Pulkit",description="This is the world")
booleanParam("Post Graduate",false)
choiceParam("Designation",["SE","SSE","ATL"])
}
scm{
git("https://github.com/pulkitpushkarna/spring-gradle-project-for-jenkins","master")
}
steps{
gradle{
tasks("test")
}
gradle{
tasks("bootJar")
}
shell("deploy.sh")
}
}
Seed job for a gradle project
jenkinsfile
Create a new job for pipeline
Configure pipeline job by introducing declarative script in pipeline
pipeline {
agent any
stages {
stage('Test') {
steps {
git 'git@github.com:pulkitpushkarna/spring-gradle-project-for-jenkins.git'
sh './gradlew test'
}
}
stage('Build') {
steps {
sh './gradlew bootJar'
}
}
stage('Deploy') {
steps {
sh "kill -9 \$(ps -ef | grep 'basic-app-0.0.1-SNAPSHOT.jar' | grep -v 'grep' | awk '{ printf \$2 }')"
withEnv(['JENKINS_NODE_COOKIE=dontkill']) {
sh 'nohup java -jar ./build/libs/basic-app-0.0.1-SNAPSHOT.jar &'
}
}
}
}
}
Exercise 3
Integration email
Create a String app with following files
package com.jenkins.pipeline.demo.jenkinspipelinedemo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
@RestController
public class JenkinsPipelineDemoApplication {
@Value("${app.version}")
String appVersion;
@Value("${app.env}")
String appEnv;
@GetMapping("/")
public Map<String,String> index(){
Map<String,String> map= new HashMap<>();
map.put("appVersion",appVersion);
map.put("appEnv",appEnv);
return map;
}
public static void main(String[] args) {
SpringApplication.run(JenkinsPipelineDemoApplication.class, args);
}
}
application.properties
server.port=8611
app.version=v1
app.env=stage
Dockerfile
FROM tomcat:8.5.50-jdk8-openjdk
RUN apt-get update
WORKDIR /usr/local/bin
COPY ./build/libs/jenkins-pipeline-demo-0.0.1-SNAPSHOT.jar .
EXPOSE 8080
CMD ["java","-jar","jenkins-pipeline-demo-0.0.1-SNAPSHOT.jar"]
Test cases
package com.jenkins.pipeline.demo.jenkinspipelinedemo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.Assert;
@SpringBootTest
class JenkinsPipelineDemoApplicationTests {
@Test
void test1() {
Assert.isTrue(true,"Canary Test Failed");
}
@Test
void test2() {
Assert.isInstanceOf(String.class,"String");
}
@Test
void test3() {
Assert.isNull(null,"Object is not Null");
}
}
Create a private github repo and push the code to the remote repo
Generate Github API token
Go to Developer Settings
Go to Personal access tokens
Generate Token
Check repo, admin:org and user checkboxes, add the Note and generate token
Create a pipeline job
Provide the git hub private repo http url
Add the github token in jenkins
For password enter the github token
Generate the script
Add the script to jenkins pipeline
Run the job to check whether the pull is working properly
Add test and build stages in pipeline
pipeline {
agent any
stages {
stage('Pull') {
steps {
git credentialsId: 'git-token', url: 'https://github.com/pulkitpushkarna/jenkins-pipeline-demo.git'
}
}
stage('Test') {
steps {
sh './gradlew test'
}
}
stage('Build') {
steps {
sh './gradlew bootJar'
}
}
}
}
Exercise 1
Add Build, Push and Deploy docker image steps in pipeline
pipeline {
agent any
stages {
stage('Pull') {
steps {
git credentialsId: 'git-token', url: 'https://github.com/pulkitpushkarna/jenkins-pipeline-demo.git'
}
}
stage('Test') {
steps {
sh './gradlew test'
}
}
stage('Build') {
steps {
sh './gradlew bootJar'
}
}
stage('Create Image') {
steps{
sh '/usr/local/bin/docker image build -t pulkitpushkarna/jenkins-pipeline-demo .'
}
}
stage('Push Image') {
steps{
sh '/usr/local/bin/docker push pulkitpushkarna/jenkins-pipeline-demo'
}
}
stage('Deploy') {
steps{
sh '/usr/local/bin/docker stop jenkins-pipeline-demo || true && /usr/local/bin/docker rm jenkins-pipeline-demo || true'
sh '/usr/local/bin/docker container run -p 8612:8611 -d --name jenkins-pipeline-demo pulkitpushkarna/jenkins-pipeline-demo'
}
}
}
}
Send Failure and Success Mails post build
pipeline {
agent any
stages {
stage('Pull') {
steps {
git credentialsId: 'git-token', url: 'https://github.com/pulkitpushkarna/jenkins-pipeline-demo.git'
}
}
stage('Test') {
steps {
sh './gradlew test'
}
}
stage('Build') {
steps {
sh './gradlew bootJar'
}
}
stage('Create Image') {
steps{
sh '/usr/local/bin/docker image build -t pulkitpushkarna/jenkins-pipeline-demo .'
}
}
stage('Push Image') {
steps{
sh '/usr/local/bin/docker push pulkitpushkarna/jenkins-pipeline-demo'
}
}
stage('Deploy') {
steps{
sh '/usr/local/bin/docker stop jekins-pipeline-demo || true && /usr/local/bin/docker rm jekins-pipeline-demo || true'
sh '/usr/local/bin/docker container run -p 8612:8611 -d --name jekins-pipeline-demo pulkitpushkarna/jenkins-pipeline-demo'
}
}
}
post {
always {
echo 'This will always run'
}
success {
mail bcc: 'pulkit.pushkarna@gmail.com', body: "Project: ${env.JOB_NAME} Build Number: ${env.BUILD_NUMBER} URL de build: ${env.BUILD_URL}", cc: 'pulkit.pushkarna@gmail.com', from: 'pulkit.pushkarna@gmail.com', replyTo: '', subject: "Success CI: Project name -> ${env.JOB_NAME}", to: 'pulkit.pushkarna@gmail.com'
}
failure {
mail bcc: 'pulkit.pushkarna@gmail.com', body: "Project: ${env.JOB_NAME} Build Number: ${env.BUILD_NUMBER} URL de build: ${env.BUILD_URL}", cc: 'pulkit.pushkarna@gmail.com', from: 'pulkit.pushkarna@gmail.com', replyTo: '', subject: "Failed CI: Project name -> ${env.JOB_NAME}", to: 'pulkit.pushkarna@gmail.com'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
}
}
}
Trigger jenkins pipeline or git commit
Introduce Parameter for Image version in docker
pipeline {
agent any
stages {
stage('Pull') {
steps {
git credentialsId: 'git-token', url: 'https://github.com/pulkitpushkarna/jenkins-pipeline-demo.git'
}
}
stage('Test') {
steps {
sh './gradlew test'
}
}
stage('Build') {
steps {
sh './gradlew bootJar'
}
}
stage('Create Image') {
steps{
sh '/usr/local/bin/docker image build -t pulkitpushkarna/jenkins-pipeline-demo:$imageVersion .'
}
}
stage('Push Image') {
steps{
sh '/usr/local/bin/docker push pulkitpushkarna/jenkins-pipeline-demo:$imageVersion'
}
}
stage('Deploy') {
steps{
sh '/usr/local/bin/docker stop jekins-pipeline-demo || true && /usr/local/bin/docker rm jekins-pipeline-demo || true'
sh '/usr/local/bin/docker container run -p 8612:8611 -d --name jekins-pipeline-demo pulkitpushkarna/jenkins-pipeline-demo:$imageVersion'
}
}
}
post {
always {
echo 'This will always run'
}
success {
mail bcc: 'pulkit.pushkarna@gmail.com', body: "Project: ${env.JOB_NAME} Build Number: ${env.BUILD_NUMBER} URL de build: ${env.BUILD_URL}", cc: 'pulkit.pushkarna@gmail.com', from: 'pulkit.pushkarna@gmail.com', replyTo: '', subject: "Success CI: Project name -> ${env.JOB_NAME}", to: 'pulkit.pushkarna@gmail.com'
}
failure {
mail bcc: 'pulkit.pushkarna@gmail.com', body: "Project: ${env.JOB_NAME} Build Number: ${env.BUILD_NUMBER} URL de build: ${env.BUILD_URL}", cc: 'pulkit.pushkarna@gmail.com', from: 'pulkit.pushkarna@gmail.com', replyTo: '', subject: "Failed CI: Project name -> ${env.JOB_NAME}", to: 'pulkit.pushkarna@gmail.com'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
}
}
}
Exercise 2
Ansible
Control machine − Machine from where we can manage other machines.
Remote machine − Machines which are handled/controlled by control machine.
Playbook Example
---
name: install and configure DB
hosts: testServer
become: yes
vars:
oracle_db_port_value : 1521
tasks:
-name: Install the Oracle DB
yum: <code to install the DB>
-name: Ensure the installed service is enabled and running
service:
name: <your service name>
Create an ansible playbook
---
- name: "Ansible Basic"
hosts: localhost
connection: local
tasks:
- name: "just execute a ls -lrt command"
command: ls -lrt
register: "output"
- debug: var=output.stdout_lines
first.yaml
Run the playbook
ansible-playbook first.yaml
Create ansible file for deployment for running docker image
run-image.yaml
---
- name: "Ansible with docker image"
hosts: localhost
connection: local
tasks:
- name: "Run docker image"
command: docker container run -p 8613:8611 -d --name jekins-pipeline-demo-2 pulkitpushkarna/jenkins-pipeline-demo
register: "output"
- debug: var=output.stdout_lines
Run the playbook
ansible-playbook run-image.yaml
Integrating Ansible with Jenkins
Make sure that ansible plugin is installed
Pipeline for runnning ansible from docker
pipeline {
agent any
stages {
stage('Test Ansible') {
steps {
sh '/usr/local/bin/ansible-playbook /Users/pulkitpushkarna/projects/ansible-yaml-files/first.yaml'
}
}
}
}
run-image.yaml
---
- name: "Ansible with docker image"
hosts: localhost
connection: local
tasks:
- name: "Run docker image"
command: /usr/local/bin/docker container run -p 8612:8611 -d --name jenkins-pipeline-demo pulkitpushkarna/jenkins-pipeline-demo
register: "output"
- debug: var=output.stdout_lines
jenkins pipeline to using ansible for deployment
pipeline {
agent any
stages {
stage('Pull') {
steps {
git credentialsId: 'git-token', url: 'https://github.com/pulkitpushkarna/jenkins-pipeline-demo.git'
}
}
stage('Test') {
steps {
sh './gradlew test'
}
}
stage('Build') {
steps {
sh './gradlew bootJar'
}
}
stage('Create Image') {
steps{
sh '/usr/local/bin/docker image build -t pulkitpushkarna/jenkins-pipeline-demo:$imageVersion .'
}
}
stage('Push Image') {
steps{
sh '/usr/local/bin/docker push pulkitpushkarna/jenkins-pipeline-demo:$imageVersion'
}
}
stage('Deploy') {
steps{
sh '/usr/local/bin/docker stop jenkins-pipeline-demo || true && /usr/local/bin/docker rm jenkins-pipeline-demo || true'
// sh '/usr/local/bin/docker container run -p 8612:8611 -d --name jekins-pipeline-demo pulkitpushkarna/jenkins-pipeline-demo:$imageVersion'
sh '/usr/local/bin/ansible-playbook /Users/pulkitpushkarna/projects/ansible-yaml-files/run-image.yaml'
}
}
}
post {
always {
echo 'This will always run'
}
success {
mail bcc: 'pulkit.pushkarna@gmail.com', body: "Project: ${env.JOB_NAME} Build Number: ${env.BUILD_NUMBER} URL de build: ${env.BUILD_URL}", cc: 'pulkit.pushkarna@gmail.com', from: 'pulkit.pushkarna@gmail.com', replyTo: '', subject: "Success CI: Project name -> ${env.JOB_NAME}", to: 'pulkit.pushkarna@gmail.com'
}
failure {
mail bcc: 'pulkit.pushkarna@gmail.com', body: "Project: ${env.JOB_NAME} Build Number: ${env.BUILD_NUMBER} URL de build: ${env.BUILD_URL}", cc: 'pulkit.pushkarna@gmail.com', from: 'pulkit.pushkarna@gmail.com', replyTo: '', subject: "Failed CI: Project name -> ${env.JOB_NAME}", to: 'pulkit.pushkarna@gmail.com'
}
changed {
echo 'This will run only if the state of the Pipeline has changed'
}
}
}
Deploy on remote machine with ansible
pipeline {
agent any
stages {
stage('Hello') {
steps {
sh '/usr/local/bin/ansible-playbook /Users/pulkitpushkarna/projects/ansible-yaml-files/remote-deploy.yaml --key-file /Users/pulkitpushkarna/projects/ansible-yaml-files/demo-instance.pem --user ubuntu'
}
}
}
}
job pipeline
Entry for the host