【问题标题】:How to use result of command to decide if a Jenkins stage should execute or not?如何使用命令结果来决定 Jenkins 阶段是否应该执行?
【发布时间】:2022-06-10 19:59:08
【问题描述】:

我有一个非常简单的声明性 Jenkins 文件,它使用 cURL 从 API 检索配置文件,然后使用 diff 命令查看它们是否与存储库中的相同配置文件不同。如果检索到的配置文件不同,我想替换旧文件并提交新文件。

我似乎不知道如何存储一个值(例如 $CONFIG_CHANGED = YES)并在下一阶段/步骤中使用它。理想情况下,如果配置没有更改,我想跳过几个阶段,但我不知道如何在管道中重用变量。我已经google了很多,但似乎环境变量是不可变的,不能在管道中更改。也许有一个我没有看到的非常简单的方法?我会很感激一些正确方向的指示。

【问题讨论】:

  • 有多种方法可以做到这一点。请分享您已经尝试过的内容,以便我们为您的具体用例提供帮助。

标签: jenkins jenkins-pipeline jenkins-groovy cicd


【解决方案1】:

有多种方法可以做到这一点。我将列出其中的一些。

  1. 执行脚本并读取标准。请注意,您写入 STDOUT 的任何内容都将被附加并返回。
                res = sh (script: '''
                # DO what ever you want here
                CONFIG_SET="YES"
                echo "1234"
                echo $CONFIG_SET''', returnStdout: true).trim()
                echo "$res"
  1. 返回退出状态。在这里,您可以返回退出代码,而不是返回 STDOUT。您可以创建一个 shell 脚本以检查参数并返回正确的退出状态。
                res2 = sh (script: '''
                # DO what ever you want here
                CONFIG_SET="NO"
                if [ $CONFIG_SET == "YES" ]
                then
                   exit 0
                else
                    echo "1111"    
                    exit 1
                fi
                ''', returnStatus: true) == 0
                echo "$res2"
  1. 写入文件和读取文件。
                sh (script: '''
                # DO what ever you want here
                CONFIG_SET="NO"
                echo $CONFIG_SET > output
                ''')
                res3 = readFile('output').trim()
                echo "$res3"

以下是完整的管道。

pipeline {
    agent any

    stages {
        stage('Hello') {
            steps {
                script {
                res = sh (script: '''
                # DO what ever you want here
                CONFIG_SET="YES"
                echo "1234"
                echo $CONFIG_SET''', returnStdout: true).trim()
                echo "$res"
                
                res2 = sh (script: '''
                # DO what ever you want here
                CONFIG_SET="NO"
                if [ $CONFIG_SET == "YES" ]
                then
                   exit 0
                else
                    echo "1111"    
                    exit 1
                fi
                ''', returnStatus: true) == 0
                echo "$res2"
                
                
                sh (script: '''
                # DO what ever you want here
                CONFIG_SET="NO"
                echo $CONFIG_SET > output
                ''')
                res3 = readFile('output').trim()
                echo "$res3"
            }
        }
    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多