简体   繁体   中英

Can I build stages with a function in a Jenkinsfile?

I'd like to use a function to build some of the stages of my Jenkinsfile. This is going to be a build with a number of repetitive stages/steps - I'd not like to generate everything manually.

I was wondering if it's possible to do something like this:

_make_stage() {
    stage("xx") {
        step("A") {
            echo "A"
        }

        step("B") {
            echo "B"
        }
    }
}

_make_stages() {
    stages {
        _make_stage()
    }
}

// pipeline starts here!
pipeline {
    agent any
    _make_stages()
}

Unfortunately Jenkins doesn't like this - when I run I get the error:

WorkflowScript: 24: Undefined section "_make_stages" @ line 24, column 5.
       _make_stages()
       ^

WorkflowScript: 22: Missing required section "stages" @ line 22, column 1.
   pipeline {
   ^

So what's going wrong here? The function _make_stages() really looks like it returns whatever the stages object returns. Why does it matter whether I put that in a function call or just inline it into the pipeline definition?

As explained here , Pipeline "scripts" are not simple Groovy scripts, they are heavily transformed before running, some parts on master, some parts on slaves, with their state (variable values) serialized and passed to the next step. As such, every Groovy feature is not supported, and what you see as simple functions really is not.

It does not mean what you want to achieve is impossible. You can create stages programmatically, but apparently not with the declarative syntax. See also this question for good suggestions.

You can define a declarative pipeline in a shared library, for example:

// vars/evenOrOdd.groovy
def call(int buildNumber) {
  if (buildNumber % 2 == 0) {
    pipeline {
      agent any
      stages {
        stage('Even Stage') {
          steps {
            echo "The build number is even"
          }
        }
      }
    }
  } else {
    pipeline {
      agent any
      stages {
        stage('Odd Stage') {
          steps {
            echo "The build number is odd"
          }
        }
      }
    }
  }
}
// Jenkinsfile
@Library('my-shared-library') _

evenOrOdd(currentBuild.getNumber())

See Defining Declarative Pipelines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM