Simon Martineau
Simon Martineau

Reputation: 31

how to execute jenkins pipeline from config file

I have a generic multibranch project that I use on about 100 different git repos. The jenkins jobs are automatically generated and the only difference is the git repo.

Since they all build in the same way and I don't want to copy the same jenkins groovy file in all repos, I use "Build configuration -> mode -> by default jenkinsfile".

It breaks the rule to put the jenkinsfile in SCM as I would prefer to do. To minimize the impact, I would like that groovy file to only checkout the "real" jenkinsfile and execute it.

I use that script:

pipeline {
    agent {label 'docker'}
    stages {
        stage('jenkinsfile checkout') {
            steps {
               checkout([$class: 'GitSCM', 
                  branches: [[name: 'master']], 
                  doGenerateSubmoduleConfigurations: false, 
                  extensions: [[$class: 'RelativeTargetDirectory', 
                  relativeTargetDir: 'gipc_synthesis']], 
                  submoduleCfg: [], 
                  userRemoteConfigs: [[url: 'ssh://[email protected]:7999/mtlstash/mvt/gipc_synthesis.git']]]
               ) 
            }
        } 

        stage('Load user Jenkinsfile') {
           //agent any
           steps {
             load 'gipc_synthesis/jenkins/synthesis_job.groovy'
           }
        }
    }    
}

The problem I have with that is I can't have another pipeline in the groovy file I am loading. I don't want to define only functions but really the whole pipeline in that file. Any solution to that problem? I am also interested in solution that would completely avoid the whole issue.

Thank you.

Upvotes: 0

Views: 784

Answers (1)

MaratC
MaratC

Reputation: 6869

You can have a shared library with your pipeline inside:

// my-shared.git: vars/build.groovy
def call(String pathToGit) // and maybe additional params 
{
    pipeline {
        agent { ... }
        stages {
          stage('jenkinsfile checkout') {
            steps {
               checkout([$class: 'GitSCM', 
                  branches: [[name: 'master']], 
                  doGenerateSubmoduleConfigurations: false, 
                  extensions: [[$class: 'RelativeTargetDirectory', 
                  relativeTargetDir: 'gipc_synthesis']], 
                  submoduleCfg: [], 
                  userRemoteConfigs: [[url: pathToGit]]]
               ) 
            }
          } 
        }
    }
}

and use it in your Jenkinsfile e.g. like this:

#!groovy
@Library('my-shared') _

def pathToGit = 'ssh://[email protected]:7999/mtlstash/mvt/gipc_synthesis.git'

build(pathToGit)

Upvotes: 1

Related Questions