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

2024-04-19

我是从这个帖子来到这里的在 Jenkins Pipeline 的 shell 脚本部分定义变量 https://stackoverflow.com/questions/51407976/defining-a-variable-in-shell-script-portion-of-jenkins-pipeline

我的情况如下:如果生成的文件发生更改(它们每几周或更短时间更改一次),我有一个管道正在更新一些文件并在我的存储库中生成 PR。

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

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

它看起来像这样,但当然它不起作用。

#!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 的回复https://stackoverflow.com/a/64572833/5685482 https://stackoverflow.com/a/64572833/5685482和这个文档 https://e.printstacktrace.blog/jenkins-pipeline-environment-variables-the-definitive-guide/我会这样做:

#!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 变量不同的变量。)

This bash变量是代码中更新的内容。

一旦你的sh会话结束,bash进程被破坏,它的所有变量也被破坏。

整个过程对名为 Groovy 的变量没有任何影响WasThereAnUpdate这只是保持以前的样子。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐