update jenkins timezone

There many ways to update jenkins timezone

Verify:

cat /etc/timezone
cat ls -ltr /etc/localtime
date

Centos/Redhat:

#update /etc/sysconfig/jenkins

#JENKINS_JAVA_OPTIONS="-Dorg.apache.commons.jelly.tags.fmt.timeZone=Asia/Calcutta"
#JENKINS_JAVA_OPTIONS="-Duser.timezone=Asia/Calcutta"

Debian/ubuntu :

#update /etc/default/jenkins

JAVA_ARGS="-Dorg.apache.commons.jelly.tags.fmt.timeZone=Asia/Calcutta"
JAVA_ARGS="-Duser.timezone=Asia/Calcutta"

Jenkins script console:


System.setProperty('user.timezone', 'Asia/Calcutta')
System.setProperty('org.apache.commons.jelly.tags.fmt.timeZone', 'Asia/Calcutta')

Jenkins skip stages using git branch name regex


def git_url = 'https://github.com/initedit/simple-storage-solution.git'
def git_branch = 'master'

pipeline
{
    agent
    {
        label 'master'
    }

    stages
    {
        stage('skip1')
        {
            when {
            expression {
                        echo git_branch
                        isDev = !(git_branch =~ /^dev*([a-zA-Z0-9]*)/)
                        return isDev
                       }
            }
            steps{
                   echo "if dev branch it will skip"
               }
        
        }
    }
}

Regex:
^dev*([a-zA-Z0-9]* = Start with dev
dev*([a-zA-Z0-9]* = contains dev

More : https://e.printstacktrace.blog/groovy-regular-expressions-the-definitive-guide/

Jenkins pipeline timeout and buildDiscarder – best practice

1. Add timeout – To stop pipeline run in infinitely
2. Add build Discard – To stop build to consume disk space

pipeline 
{

    agent { label 'master' }

    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
        timeout(time: 10, unit: 'SECONDS')
        timestamps()
    }

    stages {
        stage('sleep'){
            steps {
                    sh '''
                    echo sleeping
                    sleep 60
                    '''
                }
            }        
        }
    }

run jenkins with docker-compose

jenkins.yml

version: '3'
services:
  jenkins:
    image: jenkins/jenkins
    user: root:root
    restart: always
    container_name: jenkins
    environment:
      TZ: "Asia/Kolkata"
    volumes:
      - /opt/docker/jenkins:/var/jenkins_home
    ports:
      - 8080:8080

start : docker-compose -f jenkins.yml up -d
stop : docker-compose -f jenkins.yml down

user mapping : https://dev.to/acro5piano/specifying-user-and-group-in-docker-i2e

nohup alternative for windows in Jenkins

1.Run windows batch command in background using start

pipeline
{
    agent {
        label 'master'
    }
    stages{
		stage ('windows-nohup')
		{
			steps
			{
				
				bat """set JENKINS_NODE_COOKIE=dontKillMe && start /min COMMAND_TO_RUN """
				
			}
		}
    }
}

2.Run windows batch command in background with logs in jenkins workspace with batch and powershell

pipeline
{

    agent {
        label 'master'
    }

    stages{
        
    stage ('windows-nohup')
    {

        steps
        {
            //copy the command to test.bat file
            bat """echo COMMAND_TO_RUN REPLACE COMMAND.log > test.bat"""
			//replace the REPLACE with append symbol(>)
            powershell 'Get-Content test.bat | ForEach-Object { $_ -replace "REPLACE", " > " } | Set-Content test2.bat'
			//run the test2.bat in background
            bat 'set JENKINS_NODE_COOKIE=dontKillMe && start /min test2.bat ^& exit'
			//logs will be available at workspace COMMAND.log
			
			
			//Example
			/*
			bat """echo C:\\java8\\bin\\java -jar core.jar --config=test.json REPLACE java.log > test.bat"""
            powershell 'Get-Content test.bat | ForEach-Object { $_ -replace "REPLACE", " > " } | Set-Content test2.bat'
            bat 'more test2.bat'
            bat 'set JENKINS_NODE_COOKIE=dontKillMe && start /min test2.bat ^& exit'
			*/
        }
    }
    }
}

Skip stages in Jenkins

stages {

def skip_stage = 'skip'
pipeline
{
agent {
    label 'master'
}
parameters {
string(name: 'skip_stage', description: 'skip stage', defaultValue: 'skip')
}
  stages
{
  stage("test") {
     when {
        expression { skip_stage != "skip" }
     }
     steps {
        echo 'This will never run'
     }
  }
}
}

More when condition : https://gist.github.com/merikan/228cdb1893fca91f0663bab7b095757c

Jenkins build id and name with git commit message

  1. Install build-name-setter plugin https://plugins.jenkins.io/build-name-setter/
pipeline
{
    agent any
    stages
    {
        stage('Git-checkout')
        {
            steps
            {
                sh '''
                rm  -rf simple-storage-solution 2>&1
                git clone https://github.com/initedit-project/simple-storage-solution.git
                cd simple-storage-solution
                git log -1 --pretty=format:"%s" > ../gitcommitmsg.txt
                
            '''
            script
            {
                def gitcommitmsg = readFile(file: 'gitcommitmsg.txt')
                buildDescription gitcommitmsg
            }
            }
            
        }
        
    }
}

Output:

Jenkins pipeline using secret credentials and password


pipeline
{
    agent { label 'master' }
    stages
    {
        
        stage('check_credentials')
        {
            steps
            {
            
              withCredentials([usernamePassword(credentialsId: 'c1', usernameVariable: 'uname', passwordVariable: 'upass' )]) 
              {
                sh '''
                   echo "usernamePassword = $uname $upass" > test.txt
                '''
              }
               
              withCredentials([usernameColonPassword(credentialsId: 'c1', variable: 'uname')]) 
               {
                sh '''
                  echo "usernameColonPassword = $uname" >> test.txt
                '''
              }
              withCredentials([string(credentialsId: 't1', variable: 'TOKEN')]) 
              {
                sh '''
                  echo "string = $TOKEN" >> test.txt
                '''
              }
              sh 'cat test.txt'
            }
        }
        
        
    }
}