Sunday, November 24, 2024
HomeDevOpsHow to write a Jenkinsfile

How to write a Jenkinsfile

Creating a Jenkinsfile, which is checked into source control, provides a number of immediate benefits:

  • Code review/iteration on the Pipeline
  • Audit trail for the Pipeline
  • Single source of truth for the Pipeline, which can be viewed and edited by multiple members of the project.

Pipeline supports two syntaxes, Declarative (introduced in Pipeline 2.5) and Scripted Pipeline. Both of which support building continuous delivery pipelines. Both may be used to define a Pipeline in either the web UI or with a Jenkinsfile, though it’s generally considered a best practice to create a Jenkinsfile and check the file into the source control repository.

Creating a Jenkinsfile

The current Jenkinsfile has two ways of writing, and pipeline if it is the root, it is called Declarative Pipeline. In this case, you cannot write the Groovy script directly, and if you want to write Groovy you script need to use the directive. This article mainly deals here.

Pipeline If that does not start from, say Scripted Pipeline, to this case also write directly Groovy script, node() arrow stage(), such as, can also be written Pipeline Steps method. Although it seems convenient, degrees of freedom are too high and tend to be craftsmen code.

Writing Declarative Pipeline

Jenkins file implements by directing directive for each specific condition. The order of appearance of directives is the following order. You can not write stages, agent for example just below.

pipeline  {
    // 1 line comment
    / *
     * Multi-line comment
     * /
    agent  {  ...  }
    environment  {  ...  }
    options  {
        buildDiscarder (...)
        disableConcurrentBuilds (...)
        skipDefaultCheckout (...)
        timeout (...)
        retry (...)
        timestamps ()
    }
    parameters  {
        string (...)
        booleanParam (...)
        choice (...)
    }
    tools  {
        maven  '...'
        jdk  '...'
        gradle  '...'
    }
    triggers  {
        cron (...)
        PollSCM (...)
    }
    Stages  {
        Stage  {
            agent  {  ...  }
            environment  {  ...  }
            tools  {  ...  }
            the when  {  ...  }
            Steps  {
                // Pipeline Steps Reference reference
                echo  'help'
                sh  'ls'
                script  {
                    // any Groovy script
                }
            }
        }
    }
    steps  {
        // see Pipeline Steps Reference
    }
    post  {
        always  {  ...  }
        success  { ...  }
        failure  {  ...  }
        ...
    }
}

Steps If only you steps can describe what you write directly.

echo  'help'
sh  'ls'

node () When a steps child block appears in a directive like that, you steps can write the same as the directive in that block.

steps  {
    node ( 'slave1' ) {
        sh  'ls'
        dir ( 'output' ) {
            sh  'ls'
        }
    }
}

Individual case

How to write a stage

stage() If you use, you can display the progress separately, but there are two types of writing on the Internet. Stage Things written by itself are old and are not recommended.

stage 'first'
sh 'ls'

stage 'second'
sh 'pwd'

Now it is supposed to take a block, this is recommended.

stage ( 'first' ) {
    sh  'ls'
}
stage ( 'second' ) {
    sh  'pwd'
}

Restrict the nodes to build

Agent Specify a label with a directive.

agent  {
    label  'slave1'
}

Or use a block with a steps directive node.

steps  {
    node ( 'slave1' ) {
    }
}

Set environment variable

Environment If directives are available, write in them. Here, it credentials() can be used only as a constant .

environment  {
    GOPATH  =  '/ home / jenkins / go'
}

Or use a block in a steps directive withEnv. WithEnv Environment variables are effective only in.

steps  {
    withEnv ([ "GOPATH = $ {env. WORKSPACE}" ])  {
    }
}

When you want to control more finely using Groovy. Steps Since script directives cannot write Groovy directly, use directives.

steps  {
    script  {
        // from here Groovy
        env . GOPATH  =  env . WORKSPACE
    }
}

Install the tool

There is Global Tools Configuration in the administration menu of Jenkins, and if you define the version and name of Maven, Go compiler etc. beforehand, tools it can be installed automatically by directive.

pipeline  {
    tools  {
        go  'go1.10'
    }
}

The code generated automatically by Pipeline Syntax tool name: ‘go1.9’, type: ‘go’ is output like this, but if you write it as a Declarative Pipeline you get an error. $type ‘$name’ It is necessary to replace and write as.

Read More: Continuous integration with Jenkins – Tutorial

Make it a parameterized build

Parameters Writing something on it will be treated as a build with parameters. params.name.

pipeline  {
    parameters  {
        string ( name:  'TARGET' ,  defaultValue:  'Tests' ,  description:  'description' )
        choice ( name:  'STAGE' ,  choices:  'staging \ nproduction' ,  description:  'description' )
    }
    stages  {
        stage ( 'build' ) {
            sh  "./make.bash $ {params.TARGET}"
        }
    }
}

Build using slave in GitHub Organization Folder Plugin environment

Essentially the plugin clones without doing anything, but by default it is (probably) cloned to the Jenkins Master workspace. Therefore, if the build node is not the master, the source code to be built does not exist in the slave workspace.

Steps If checkout you use with directive clone will be done to slave’s workspace.

steps  {
    checkout  scm
}

Or agent if you specify a label with a directive from the beginning, it will be cloned by the target slave.

pipeline  {
    agent  {
        label  'slave1'
    }
    steps  {
        sh  'ls'
    }
}

Clone to a specific directory

dir() You can change the current directory by using, checkout scm you can do it after moving . If there is no moving directory, it will be created automatically.

stage ( 'chekout' ) {
    steps  {
        dir ( "src / v2" ) {
            checkout  scm
        }
    }
}

Change checkout behavior with GitHub Organization Folder Plugin

How to Customize According to Checkout for Pipeline Multi branch checkout scm ,

checkout ([
    $ class :  'GitSCM' ,
    branches:  scm . branches ,
    extensions:  scm . extensions ,
    userRemoteConfigs:  scm . userRemoteConfigs
])

It seems that it is a short form of. If you change the directory to be cloned like Shallow clone scm.extensions, add an array option to.

Checkout ([
    $ Class :  'GitSCM' ,
    Branches:  Scm . Branches ,
    Extensions:  Scm . Extensions  Tasu  [
        [
            $ Class :  'RelativeTargetDirectory' ,
            RelativeTargetDir:  "Src / V2"
        ]
    ],
    UserRemoteConfigs:  Scm . UserRemoteConfigs
])

Clear workspace before checkout

checkout scm deleteDir Use before.

stage ( 'clean' ) {
    steps  {
        deleteDir ()
    }
}
stage ( 'checkout' ) {
    steps  {
        checkout  scm
    }
}

Scripts not permitted to use method Error does not work

When I executed the code of Jenkinsfile,

RejectedAccessException: Scripts not permitted to use method (method name)

There is a case that it stops with an error saying. This is because it is dangerous to execute external code unconditionally, so it seems to be running sandbox by Script Security Plugin .

It is a function for restricting external code, so it can not be avoided with Jenkinsfile. After the error has occurred, there is a log requesting permission of the method that caused the error in the Jenkins management screen, so if you press the Approval button there, you can avoid the error from the next time. This file is located in $ JENKINS_HOME / scriptApproval.xml , so you can copy it.

Save deliverables

Post You can use the Archive Artifact Plugin in the section.

pipeline  {
    post  {
        success  {
            archiveArtifacts  artifacts:  bin / *,  fingerprint:  true
        }
    }
}

Restrict the number of deliverables

There are various ways of writing, but probably it options is easy to use directives.

pipeline  {
    options  {
        buildDiscarder ( logRotator ( numToKeepStr:  '5' ,  artifactNumToKeepStr:  '5' ))
    }
}

To build in parallel

Steps In parallel use.

steps  {
   parallel (
        linux:  {
            sh  './make.bash -t linux_amd64'
        },
        windows:  {
            sh  './make.bash -t windows_amd64'
        }
    )
}

In this example, ./make.bash -t linux_amd64 and ./make.bash -t windows_amd64 are executed in parallel.

Build another job

Build use.

Argument parameters pass the path to the folder where Jenkins is located. For a relative path, the directory of the calling job is current, and in the case of an absolute path, $ JENKINS_HOME / jobs is the root.

steps  {
    build  '../jobName1'
}

When calling a multi-branch project, the internal hierarchy is cut for each branch, so you need a branch name.

steps  {
    build  '../jobName1/master'
}

Since the jobs managed by GitHub Organization Folder are close to multi branches and jobs are created under Organization, they are as follows.

steps  {
    build  '/ organizationName / jobs / jobName / master'
}

Lets connect to ssh with Credential managed by Jenkins

Installing the ssh-agent plugin will make the sshagent block available. The command described in this block is ssh-agent executed with the secret key managed by Jenkins added, but it is in operation. So, in the account of Jenkins git push If you want to, write as follows.

RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments