Jenkins File Syntax

Jenkins File Syntax

Hello Everyone in this blog I would like to explain what is pipeline job , basics of jenkins file synatx .

Need of Pipeline

Pipeline Job has much more advantages than a simple freestyle job.

Free style jobs are UI specific and we have to depend on multiple plugins the same can be done through code in pipeline job . It is difficult to share steps followed in free style job to other person but pipeline job can be easily shared.

In free style job each step is considered as a job and in pipeline job collection of multiple steps are considered as a job.

We have to chain multiple freestyle jobs to create a pipeline job if we are using freestyle jobs to create a pipeline job and it is difficult to manage all those chained jobs .

There are many limitations in free style job and so it is recommended to use pipeline job for complex work flows.

Creating our first pipeline in Jenkins

In this blog I will explain how many ways of writing pipeline and its syntax.

Firstly we can install jenkins as a container on host or normally on host through some commands . I have installed as a container as it is much easier.

Select New item and give a name to pipe line , select pipeline option and click OK.

Select Discard old builds give any number for days to keep builds and max builds to keep and it is completely up to you.

There are 2 ways of writing pipeline script

  1. Declarative

  2. Scripted

We can write pipeline script in the jenkins UI or else we can use the jenkins file from the project in git repository.

Jenkins uses groovy syntax for writing pipeline scripts which is similar to java.

Choosing pipeline script from git repository is recommended than writing in the UI itself.

Name of the Jenkins file can be anything but that name has to match with what ever you name the jenkins file in the git repository .

Jenkins file Syntax

Here I would like to explain basics on how to write declarative jenkins file script.

Pipeline job can have many stages all together considerd as a job.

This is how a simple jenkins file looks like.

pipeline{
agent any
  stages{

  stage('build'){
      steps{
        echo "Iam building stage"
          }
     }

stage('deploy'){
    steps {
      echo "Iam deploying stage"
         }
    }
 }
}

This script has 2 stages build and deploy. Depending on organization requirement these stages may vary.

  1. Pipeline block defines all the work done throughout your entire Pipeline.

  2. agent defines on which node your stages has to run this can be on other virtual machine or a docker container . If we specify any then stages run on any available node.

  3. All the steps related to any stage must be in steps block and all the stages must be in stages block.

Using build now option build will be scheduled. Then click on the scheduled build and click console output. Output for the build will be displayed.

Post attribute

After all stages are executed completely jenkins engine executes this block.

pipeline{
agent any
  stages{

     stage('build'){
        steps {
          echo "Iam building stage"
          }
       }

      }
   post{
    always{
     echo "I will always run regardless of build status"
    }
  success {
     echo "I will only run if the build was successful"
     }
    success {
     echo "I will only run if the build was unsuccessful"
     }
   }
  }

Evironment Variables

In Jenkins file we can use environment variables so that any secrets will not be exposed .

Using environment block we can use environment variables and using $ we can access it through any stage.

pipeline {

environment {
  SECRET="Iam Secret"  # This is how we can use environment variables 
                       # in Jenkins file 
  } 
 agent any
  stages {
    stage('build') {
      steps  {
        echo "Iam building this stage with this ${SECRET}"
      }
    }
  }

}

Tools

If we want to use the installed plugin in the pipeline then we have to specify that tool in tools block and we can use it in any stage.

Here I have installed docker using Docker Pipeline plugin and named as docker in tools section. Using this name I can use docker commands in my pipeline.

pipeline {
 tools {

 dockerTool 'docker' # dockerTool is the supported name by jenkins 
                      # I found it through pipeline syntax link we will 
                       # see more about that in a moment
  }
 agent any
  stages {
    stage('Docker') {
      steps  {
        sh "docker -v"  # Now I can use docker commands in my pipeline
      }
    }
  }

}

Parameters

We can use Parameters in our pipeline which means we can select/change the values before the build.

pipeline {
parameters {
 string (name :'version',defaultValue:'the newest version', description: '' )
  choice (name:'mychoice' , choices:['1.0','1.1','1.2'] )

 }
 agent any
  stages {
    stage('parameters') {
      steps  {
      echo "Iam ${params.version} ${params.mychoice}" 
            // This is how we can access parameters.
      } 
    }
  }

}

Valid parameter types are [booleanParam, choice, credentials, file, text, password, run, string]

In our first build we don't see build with parameters option after this script has successfully executed we can choose our parameters.

Conditionals

We can use conditional statements in the jenkins script like in any other programming language .

Using when and expression block we can use conditions like if else in other programming languages.


stage('condition'){

       when {
expression {
params.mychoice='1.1'   // If the value of mychoice is 1.1 
                       //   then only this stage will be executed 
       }
     }
 steps  {
  echo "Condition Successful"
        }
     }

How to use External groovy script

We can use external script in our jenkins file.

Let the name of external script be external.groovy

def Hello(){
echo "Hello Iam  from External groovy script"
}
return this;
pipeline{
    agent any


    stages{

stage('Use external script'){
    steps {
     script {
     def script= load "External.groovy" 
 echo script.Hello()
    }

    }
     }

    }

}

Pipeline script

While creating a pipeline at the bottom most we can see this option pipeline script . With the help of this option it becomes easy for us to write the script.

Pick a step you are interested in from the list, configure it, click Generate Pipeline Script, and you will see a Pipeline Script statement that would call the step with that configuration.i

Using this option from pipeline script I got to know how to use docker in the pipeline.

Credentials

We can use credentials in Jenkins through environment block if used like this credentials can be accessed by any stage or we can make credentials stage specific for that we have to use withCredentials plugin.

Credentials can be any type it can be username and password , secret file , secret text etc... . We can create credentials navigating to credentials page from manage jenkins .

Scope of credentials can be system or global . If it is system then credentials can be used in that node only where credentials are created. If it is global then credentials can be used in all the connected nodes.

Using Credentials Id we can use the specific credentials in our pipeline.

pipeline{
    agent any
 environment {
 docker_hub_credentials=credentials('DockerHubCred') 
                       # Name the Id of the Credentials 
 } 
    stages{

stage('Using Credentials as environment variable'){
    steps {
       echo "${docker_hub_credentials_USR} ,${docker_hub_credentials_PSW}"
     # docker hub username and password are printed on the console output
}

    }
    stage('Making Credentials stage specific') {
      steps   {
       withCredentials([usernamePassword(credentials:'DockerHubCred',
                 usernameVariable:'Username', passwordVariable:'Password')]){
             echo "${Username} ${Password}"
 # Using withCredentials  docker hub credentials are this stage specific and
 # username and password are collected in Username and Password variables.
          }      
      }
   }

}

I have used pipeline script for this syntax . It is pretty much helpful while writing jenkins script.

Thats it about the basics of how to write jenkins file .

I have included almost everything I learned. If I missed anything or you found anything wrong please let me know.

Thanks for reading my blog . Have a great day 🥳🥳.