在詹金斯管道的多个步骤中定义和访问变量

Define and access a variable in multiple steps of a jenkins pipeline

我就是从这里过来的post

我的情况如下我有一个管道,如果生成的文件发生变化(它们每隔几周或更短时间发生变化),就会更新一些文件并在我的回购中生成 PR。

在我的管道结束时,我有一个 post 操作通过电子邮件将结果发送给我们的团队连接器。

我想知道我是否可以以某种方式生成一个变量并将该变量包含在我的电子邮件中。

看起来像这样,但当然行不通。

#!groovy
String WasThereAnUpdate = '';

pipeline {
    agent any
    environment {
        GRADLE_OPTS = '-Dorg.gradle.java.home=$JAVA11_HOME'
    }
    stages {
        stage('File Update') {
            steps {
                sh './gradlew updateFiles -P updateEnabled'
            }
        }
        stage('Create PR') {
            steps {
                withCredentials(...) {
                    sh '''
                        if [ -n \"$(git status --porcelain)\" ]; then
                            WasThereAnUpdate=\"With Updates\"
                            ...
                        else
                            WasThereAnUpdate=\"Without updates\"
                        fi
                    '''
                }
            }    
        }
    }
    post {
        success {
            office365ConnectorSend(
                message: "Scheduler finished: " + WasThereAnUpdate,
                status: 'Success',
                color: '#1A5D1C',
                webhookUrl: 'https://outlook.office.com/webhook/1234'
            )
        }
    }
}

我试过以 ${} 等不同方式引用我的变量...但我很确定赋值不起作用。 我知道我可能可以使用脚本块来完成,但我不确定如何将脚本块放入 SH 本身,不确定这是否可行。

感谢 MaratC 的回复 and this documentation 我会这样做:

#!groovy
def date = new Date()
String newBranchName = 'protoUpdate_'+date.getTime()

pipeline {
    agent any
    stages {
        stage('ensure a diff') {
            steps {
                sh 'touch oneFile.txt'
            }
        }
        stage('AFTER') {
            steps {
                script {
                    env.STATUS2 = sh(script:'git status --porcelain', returnStdout: true).trim()
                }
            }
        }
    }
    post {
        success {
            office365ConnectorSend(
                message: "test ${env.STATUS2}",
                status: 'Success',
                color: '#1A5D1C',
                webhookUrl: 'https://outlook.office.com/webhook/1234'
            )
        }
}

在你的代码中

sh '''
    if [ -n \"$(git status --porcelain)\" ]; then
        WasThereAnUpdate=\"With Updates\"
        ...
    else
        WasThereAnUpdate=\"Without updates\"
    fi
'''

您的代码创建了一个 sh 会话(很可能是 bash)。该会话从启动它的进程 (Jenkins) 继承环境变量。一旦运行 git status,它就会设置一个 bash 变量 WasThereAnUpdate(与可能命名为 Groovy 的变量不同。)

这个 bash 变量是在您的代码中更新的变量。

一旦您的 sh 会话结束,bash 进程就会被销毁,它的所有变量也会被销毁。

整个过程对名为 WasThereAnUpdate 的 Groovy 变量没有任何影响,它只是保持以前的状态。