Jenkinsfile. I want to use objects. How to run shell script from method of object?

36 Views Asked by At

In "commons" pipelines we can use sh(script...), but I want to use objects to map containars. But inside methods of object it is not possible to use sh(script...) - Jenkins throwing groovy.lang.MissingMethodException. I try many tricks, but all finished the same...

Here is part of exemplary Jenkinsfile. In Container.run() method I need to run script.

class Container {

    def run( containerName ) {
        //sh(script: "docker start ${containerName}")
    } 

}

pipeline {
    agent any

    environment {
        HUB_CONTAINER_NAME = 'hub'
    }

    
    stages {
        stage('Running container') {
            steps {
                script {
                    def container = new Container( HUB_CONTAINER_NAME )
                    hubContainer.run( )
                }
            }
        }

    }
}
1

There are 1 best solutions below

0
KamilCuk On BEST ANSWER

You have to pass that this global object. Typically, they call it script in plugins. TBH I do not understand it much, sometimes it is passed implicit, sometimes resolved globally, sometimes not. Usually it passed to the class constructor to have a reference at all times when needed.

class Container {
    def run(script, containerName) {
        script.sh("docker start ${containerName}")
    } 
}
pipeline {
    stages {
        stage('Running container') {
            steps {
                script {
                    new Container().run(this, "thename")
                }
            }
        }

    }
}

Example from docker jenkins plugin https://github.com/jenkinsci/docker-workflow-plugin/blob/dc3cf1327f1b8c9967a56aa0e1a1f3f0ff79b57c/src/main/resources/org/jenkinsci/plugins/docker/workflow/Docker.groovy#L33 . or see https://www.jenkins.io/doc/book/pipeline/shared-libraries/ at:

class Utilities {
  static def mvn(script, args) {
    script.sh "${script.tool 'Maven'}/bin/mvn -s ${script.env.HOME}/jenkins.xml -o ${args}"
  }
}