简体   繁体   English

如何使用 Groovy 集成 Jenkins 管道作业并传递动态变量?

[英]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.我想通过基于触发作业的项目传递动态变量来使用 Groovy 集成 Jenkins 作业。 Can anyone please suggest on how to proceed with this?任何人都可以建议如何进行此操作吗?

Looks like you would like to persist data between two jenkins jobs or two runs of the same jenkins job.看起来您希望在两个 jenkins 作业或同一 jenkins 作业的两次运行之间保留数据。 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.您可以使用写入文件使用groovy或重定向运算符(>)来执行此操作,以仅使用 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./tmp文件夹中创建文件的示例如下。 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如果您想删除它,您可以轻松删除具有属性的行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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