How can I use `def` in jenkins pipeline

jenkins pipeline define variable
jenkins pipeline parallel
jenkins pipeline variables between stages
jenkins pipeline set variable from shell
jenkins pipeline groovy variables
jenkinsfile credentials
jenkins pipeline cron
jenkinsfile checkout scm

I am learning jenkins pipeline, and I tried to follow this pipeline code. But my jenkins always complain that def is not legal. I am wondering did I miss any plugins? I already installed groovy, job-dsl, but doesn't work.


As @Rob said, There are 2 types of pipelines: scripted and declarative. It is like imperative vs declarative. def is only allowed in scripted pipeline or wrapped in script {}.

Scripted pipeline (Imperative)

Start with node, and def or if is allowed, like below. It is traditional way. node { stage('Example') { if (env.BRANCH_NAME == 'master') { echo 'I only execute on the master branch' } else { echo 'I execute elsewhere' } } }

Declarative pipeline (Preferred)

Start with pipeline, and def or if is NOT allowed, unless it is wrapped in script {...}. Declarative pipeline make a lot things easy to write and read.

time trigger
pipeline {
    agent any
    triggers {
        cron('H 4/* 0 0 1-5')
    }
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
}
when
pipeline {
    agent any
    stages {
        stage('Example Build') {
            steps {
                echo 'Hello World'
            }
        }
        stage('Example Deploy') {
            when {
                branch 'production'
            }
            steps {
                echo 'Deploying'
            }
        }
    }
}
Parallel
pipeline {
    agent any
    stages {
        stage('Non-Parallel Stage') {
            steps {
                echo 'This stage will be executed first.'
            }
        }
        stage('Parallel Stage') {
            when {
                branch 'master'
            }
            failFast true
            parallel {
                stage('Branch A') {
                    agent {
                        label "for-branch-a"
                    }
                    steps {
                        echo "On Branch A"
                    }
                }
                stage('Branch B') {
                    agent {
                        label "for-branch-b"
                    }
                    steps {
                        echo "On Branch B"
                    }
                }
            }
        }
    }
}
embedded with scripted code
pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'

                script {
                    def browsers = ['chrome', 'firefox']
                    for (int i = 0; i < browsers.size(); ++i) {
                        echo "Testing the ${browsers[i]} browser"
                    }
                }
            }
        }
    }
}

To read more declarative pipeline grammar, please refer the official doc here

How can I use `def` in jenkins pipeline, master to atomic commands that are sent to the agents. Variables in a Jenkinsfile can be defined by using the def keyword. Such variables should be defined before the pipeline block starts. When variable is defined, it can be called from the Jenkins declarative pipeline using $ {} syntax. Cool Tip: Define conditional variables in a Jenkins pipeline!


You can use def with a declarative pipeline, just not inside it eg

def agentLabel
if (BRANCH_NAME =~ /^(staging|master)$/)  {
    agentLabel = "prod"
} else {
    agentLabel = "master"
}

pipeline {
  agent { node { label agentLabel } } 
..

Jenkins Pipeline Tutorial: JenkinsFile EXAMPLE, You can also use environment block to inject an environment variable. (Side note​: sh is not needed for echo) pipeline { agent none environment {  The definition of a Jenkins Pipeline is written into a text file (called a Jenkinsfile) which in turn can be committed to a project’s source control repository. [ 2 ] This is the foundation of "Pipeline-as-code"; treating the CD pipeline a part of the application to be versioned and reviewed like any other code.


You can use def by using node like below:

node {
stage('Example') {
    if (env.BRANCH_NAME == 'master') {
        echo 'I only execute on the master branch'
    } else {
        echo 'I execute elsewhere'
    }
}

Another way : by using script{..}

    stage ('jon'){
steps{
script{                                                                                              
    def imageLine = 'chiducaff/user_containers:sonnginx'
}
    writeFile file: 'anchore_images', text: imageLine
    anchore name: 'anchore_images'
                           }}

Main differences between Freestyle, In Groovy, we can use scopes to define Collections or Arrays. def arg = ["Groovy",​"Java","Python",”nodeJS”] println arg.class. The  Using Jenkins 2.126 Pipeline: API Plugin that defines Pipeline API. 2.27 Pipeline: Job Defines a new job type for pipelines and provides their generic user interface. 2.21 Pipeline: SCM Step Adds a Pipeline step to check out or update working sources from various SCMs (version control).


Pipeline, Why Use Jenkin's Pipeline? Jenkins is an open continuous integration server which has the ability to support the automation of software  // in this array we'll place the jobs that we wish to run def branches = [:] //running the job 4 times concurrently //the dummy parameter is for preventing mutation of the parameter before the execution of the closure. //we have to assign it outside the closure or it will run the job multiple times with the same parameter "4" //and jenkins will unite them into a single run of the job for (int i = 0; i < 4; i++) { def index = i //if we tried to use i below, it would equal 4 in each job


Using a Jenkinsfile, In declarative pipeline syntax, you do this in an environment block in the pipeline definition (Jenkinsfile). You can do this: at the top level, to define environment  Browse other questions tagged jenkins groovy jenkins-pipeline jenkins-groovy jenkins-declarative-pipeline or ask your own question. The Overflow Blog The Overflow #25: New tools for new times


Pipeline Examples, After the Jenkins Scripted Pipeline, this blog post covers the This directive allows you to define a list of parameters to be used in the script. The following plugin provides functionality available through Pipeline-compatible steps. Read more about how to integrate steps into your Pipeline in the Steps section of the Pipeline Syntax page. For a list of other such plugins, see the Pipeline Steps Reference page.