Search code examples
jenkinsjenkins-pipelinejenkins-groovyjenkins-job-dsl

Custom Groovy function with arguments doesn't work in Jenkins pipeline


I'm using a function to set environment variables in Jenkins pipeline. I've noticed that if I declare function without argument, it works, but if I declare function that accepts 1 string argument, Jenkins throws error No such DSL method 'get_metadata' found among steps while running my pipeline.

def get_metadata(String type) {
    switch(type) {
      case "env":
        return "environment name";
        break;
      case "domain":
        return "domain name";
        break;
      case "cloud":
        return "cloud name";
        break;
      default:
        return "none";
        break;
    }
}

pipeline {
  environment {
    PROJECT=get_metadata()
    CLOUD=get_metadata(type: "cloud")
    DOMAIN=get_metadata(type: "domain")
    ENVIRONMENT=get_metadata(type: "env")
  }
}

Function without argument works when I call it like get_metadata()

def get_metadata() {
<...>
}

Jenkins version is 2.289.2.


Solution

  • Your get_metadata does not define a default value for type and therefore the call to PROJECT=get_metadata() throws an error, as you can't use it as is without passing the type parameter.

    To solve it you can just add a default value to your function:

    def get_metadata(String type = '') {
       switch(type) {
         case "env":
            return "environment name";
         case "domain":
            return "domain name";
         case "cloud":
            return "cloud name";
         default:
            return "none";
       }
    }