Jenkins Cheat Sheet

Jenkins Cheat Sheet

1. Basic Jenkins Commands

  • Start Jenkins:

      sudo service jenkins start
    
  • Stop Jenkins:

      sudo service jenkins stop
    
  • Restart Jenkins:

      sudo service jenkins restart
    

2. Jenkinsfile Basics

  • Declarative Pipeline Syntax:

      pipeline {
          agent any
          stages {
              stage('Build') {
                  steps {
                      echo 'Building...'
                  }
              }
              stage('Test') {
                  steps {
                      echo 'Testing...'
                  }
              }
              stage('Deploy') {
                  steps {
                      echo 'Deploying...'
                  }
              }
          }
      }
    
  • Scripted Pipeline Syntax:

      node {
          stage('Build') {
              sh 'mvn clean install'
          }
          stage('Test') {
              sh 'mvn test'
          }
          stage('Deploy') {
              sh 'deploy.sh'
          }
      }
    

3. Key Pipeline Features

  • Parallel Stages:

      stage('Parallel Tests') {
          parallel {
              stage('Unit Tests') {
                  steps { echo 'Running unit tests...' }
              }
              stage('Integration Tests') {
                  steps { echo 'Running integration tests...' }
              }
          }
      }
    
  • Post Actions:

      post {
          success {
              echo 'Build succeeded'
          }
          failure {
              echo 'Build failed'
          }
      }
    

4. Environment Variables

  • Defining Environment Variables:

      environment {
          APP_VERSION = '1.0.0'
      }
    
  • Using Environment Variables:

      echo "Deploying version ${APP_VERSION}"
    

5. Jenkins CLI Commands

  • Install Plugin:

      java -jar jenkins-cli.jar -s http://your_jenkins_url/ install-plugin plugin-name
    
  • Restart Jenkins via CLI:

      java -jar jenkins-cli.jar -s http://your_jenkins_url/ safe-restart
    

6. Triggering Builds

  • Manual Trigger: Click Build Now in the Jenkins UI.

  • Git Trigger: Set up webhooks in GitHub/Bitbucket to trigger builds on code pushes.

7. Common Jenkinsfile Conditions

  • Branch Condition:

      stage('Deploy to Prod') {
          when {
              branch 'main'
          }
          steps {
              echo 'Deploying to production'
          }
      }
    

8. Jenkins Blue Ocean

  • Install Blue Ocean: Navigate to Manage Jenkins > Manage Plugins and install Blue Ocean for a modern UI.

9. Jenkins Plugins

  • Key Plugins:

    • Git: For source control integration.

    • Docker: To build and run Docker containers.

    • Pipeline: For defining Jenkins pipelines as code.

    • Credentials Binding: For securely handling secrets.

10. Backup Jenkins

  • Backup Configurations: Backup /var/lib/jenkins directory for all job configurations, plugins, and settings.