Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load bash script in Jenkins pipeline?

We have some complex bash script which is now in our managed files section in Jenkins. We try to migrate the job to a pipeline but we don't know enough to translate the bash script to groovy so we want to keep this in bash. We have a jenkins-shared-library in Git in which we store our pipeline templates. Inside the job we add the right environment variables.

We want to keep our bash script in git instead of in the managed files. What is the right way to load this script in the pipeline and execute it? We tried some stuff with libraryResource, but we didn't manage to make it work. Where do we have to put the test.sh script in git and how can we call it? (or is it completely wrong to run a shell script here)

def call(body) {
    // evaluate the body block, and collect configuration into the object
    def pipelineParams= [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = pipelineParams
    body()

    pipeline {
        agent any

        options {
            buildDiscarder(logRotator(numToKeepStr: '3'))
        }

        stages {

            stage ('ExecuteTestScript') {
                steps {
                    def script = libraryResource 'loadtestscript?'

                    script {
                        sh './test.sh'
                    }
                }
            }

        }

        post {
            always {
                cleanWs()
            }

        }

    }
}
like image 884
DenCowboy Avatar asked Nov 23 '17 12:11

DenCowboy


People also ask

How do I run a shell script in Jenkins pipeline?

These are the steps to execute a shell script in Jenkins: In the main page of Jenkins select New Item. Enter an item name like "my shell script job" and chose Freestyle project. Press OK.

Does Jenkins use sh or Bash?

Jenkins by default looks for sh in the PATH environment variable, however the result (e.g. /bin/sh ) may point to different shells. For example, on Ubuntu 6.10 or later, /bin/sh is a symlink to Dash.


1 Answers

In my company we also have complex bash scripts in our CI and libraryResource was a better solution. Following your script, you can perform some changes in order to use a bash script stored into libraryResource:

stages {
    stage ('ExecuteTestScript') {
        steps {
            // Load script from library with package path
            def script_bash = libraryResource 'com/example/loadtestscript'

            // create a file with script_bash content
            writeFile file: './test.sh', text: script_bash

            // Run it!
            sh 'bash ./test.sh'
        }
    }
}
like image 129
Barizon Avatar answered Oct 23 '22 02:10

Barizon