vrbharath reddy
vrbharath reddy

Reputation: 1

How to integrate Jenkins pipeline jobs and pass dynamic variables using Groovy?

I want to integrate Jenkins jobs using Groovy by passing dynamic variables based on the projects for which the job is triggered. Can anyone please suggest on how to proceed with this?

Upvotes: 0

Views: 406

Answers (1)

Mo Ziauddin
Mo Ziauddin

Reputation: 410

Looks like you would like to persist data between two jenkins jobs or two runs of the same jenkins job. In both cases, I was able to do this using files. you can use write file to do it using groovy or redirection operator (>) to just use bash.

In first job, you can write to the file like so.

node {
    // write to file
    writeFile(file: 'variables.txt', text: 'myVar:value')
    sh 'ls -l variables.txt'
}

In second job, you can read from that file and empty the contents after you read it.

stage('read file contents') {
    // read from the file    
    println readFile(file: 'variables.txt')
}

The file can be anywhere on the filesystem. Example with a file created in /tmp folder is as follows. You should be able to run this pipeline by copy-pasting.

node {
    def fileName = "/tmp/hello.txt"
    stage('Preparation') {
        sh 'pwd & rm -rf *'
    }

    stage('write to file') {
        writeFile(file: fileName, text: "myvar:hello", encoding: "UTF-8")
    }
    
    stage('read file contents') {
        println readFile(file: fileName)
    }
}

You could also use this file as a properties file and update a property that exists and append ones that don't . A quick sample code to do that looks like below.

node {
    def fileName = "/tmp/hello.txt"
    stage('Preparation') {
        sh 'pwd & rm -rf *'
    }

    stage('write to file') {
        writeFile(file: fileName, text: "myvar:hello", encoding: "UTF-8")
    }
    
    stage('read file contents') {
        println readFile(file: fileName)
    }
    
    // Add property
    stage('Add property') {
        if (fileExists(fileName)) {
            existingContents = readFile(fileName)
        }
        newProperty = "newvar:newValue"
        writeFile(file: fileName, text: existingContents + "\n" + newProperty)
        println readFile(file: fileName)
    }
}

You could easily delete a line that has a property if you would like to get rid of it

Upvotes: 1

Related Questions