Anna
Anna

Reputation: 369

Create new Jenkins jobs using Pipeline Job and Groovy script

I have Jenkins pipeline Job with parameters (name, group, taskNumber)

I need to write pipeline script which will call groovy script (this one?: https://github.com/peterjenkins1/jenkins-scripts/blob/master/add-job.groovy)

I want to create new job (with name name_group_taskNamber) every times when I build main Pipeline Job.

I don't understand: Where do I need to put may groovy script ? How does Pipeline script should look like? :

node{
    stage('Build'){
        def pipeline = load "CreateJob.groovy"
        pipeline.run()
    }
}

Upvotes: 1

Views: 6090

Answers (2)

lvthillo
lvthillo

Reputation: 30723

You can use and configure a shared library like here (a git repo): https://github.com/lvthillo/shared-library . You need to configure this in your Jenkins global configuration.

It contains a folder vars/. Here you can manage pipelines and groovy scripts like my slackNotifier.groovy. The script is just a groovy script to print the build result in Slack.

In the jenkins pipeline job we will import our shared library:

@Library('name-of-shared-pipeline-library')_

mavenPipeline {
  //define parameters
}

In the case above also the pipeline is in the shared library but this isn't necessary.

You can just write your pipeline in the job itself and call only the function from the pipeline like this: This is the script in the shared library:

// vars/sayHello.groovy
def call(String name = 'human') {
    echo "Hello, ${name}."
}

And in your pipeline:

final Lib= library('my-shared-library')

...
  stage('stage name'){
    echo "output"
    Lib.sayHello.groovy('Peter')
  }
...

EDIT: In new declarative pipelines you can use:

pipeline {
    agent { node { label 'xxx' } }

    options {
        buildDiscarder(logRotator(numToKeepStr: '3', artifactNumToKeepStr: '1'))
    }

    stages {
        stage('test') {
            steps {
                sh 'echo "execute say hello script:"'
                sayHello("Peter")
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}

def sayHello(String name = 'human') {
    echo "Hello, ${name}."
}

output:

[test] Running shell script
+ echo 'execute say hello script:'
execute say hello script:
[Pipeline] echo
Hello, Peter.
[Pipeline] }
[Pipeline] // stage

Upvotes: 1

Ashokekumar S
Ashokekumar S

Reputation: 361

We do it by using the https://wiki.jenkins.io/display/JENKINS/Jobcopy+Builder+plugin, try build another step in pipeline script and pass the parms which are to be considered

Upvotes: 0

Related Questions