Jenkinsfile

A scripted pipeline that goes into your repository (like Dockerfile).

Pipeline Syntax

Declarative

CODE_CHANGES = getGitChanges() // You can also define your own variables to use
// getGitChanges() would be a Groovy script that checks if the code changed

pipeline { // "pipeline" must be top-level
    agent any // Where to run the build (agent is a Jenkins agent which can be a node, executor on the node, etc.)
                        // agent example: agent to run linux, agent to run windows
                        // "any" means any next available agent
    // NOTE: You must always have pipeline and agent 

    stages { // where the actual work happens
        stage('Build') {
            steps {
                echo 'Building..'
            }
        }
        stage('Test') {
              when { // When you only want to run the test on a certain branch
                  expression {
                          // boolean expressions go here
                            // Jenkins has an environment variable called BRANCH_NAME that represents the current branch
                            BRANCH_NAME == 'dev' || BRANCH_NAME == 'master' && CODE_CHANGES == true
                } // if this block is true, the stage will proceed, if this block is false, rest of stage skipped
            }
            steps {
                echo 'Testing..'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying....'
            }
        }
    }

  // POST ACTIONS
  post {
    always { // execute something after the stages have been executed no matter the outcome of these stages
      // ex. send an email to developers about info
    }
    success { // execute something ONLY if the build succeeded

    }
    failure { // execute something ONLY if the build failed

    }
  }
}

Scripted

  • Uses groovy engine

Environment Variables

Variables available in Jenkins

You can see them at <jenkins_url>/env-vars.html

How to define them:

Accessing Build Tools

In projects, you have multiple builds such as Maven Build or Gradle build. So you would need a line like sh "maven build" in the stages. How do we access this?

Note: Jenkins only supports 3 builds tools: gradle, maven, and jdk. yarn and npm cannot be done this way,

Parameterize your Build

You may want external configurations for your Jenkinsfile. For example, you want to select which version of the application you want to deploy. You can do this with parameters.

To choose the paraeters, they will show up in Build (Build in Jenkins becomes Build with Parameters).

External Groovy Scripts

Last updated

Was this helpful?