Can I import a groovy script from a relative directory into a Jenkinsfile?

前端 未结 1 1841
-上瘾入骨i
-上瘾入骨i 2021-01-02 09:56

I\'ve got a project structured like this:

/
/ Jenkinsfile 
/ build_tools /
              / pipeline.groovy # Functions which define the pipeline
                     


        
相关标签:
1条回答
  • 2021-01-02 10:37

    The best-supported way to load shared groovy code is through shared libraries.

    If you have a shared library like this:

    simplest-jenkins-shared-library master % cat src/org/foo/Bar.groovy
    package org.foo;
    
    def awesomePrintingFunction() {
      println "hello world"
    }
    

    Shove it into source control, configure it in your jenkins job or even globally (this is one of the only things you do through the Jenkins UI when using pipeline), like in this screenshot:

    and then use it, for example, like this:

    pipeline {
      agent { label 'docker' }
      stages {
        stage('build') {
          steps {
            script {
              @Library('simplest-jenkins-shared-library')
              def bar = new org.foo.Bar()
              bar.awesomePrintingFunction()
            }
          }
        }
      }
    }
    

    Output from the console log for this build would of course include:

    hello world
    

    There are lots of other ways to write shared libraries (like using classes) and to use them (like defining vars so you can use them in Jenkinsfiles in super-slick ways). You can even load non-groovy files as resources. Check out the shared library docs for these extended use-cases.

    0 讨论(0)
提交回复
热议问题