【问题标题】:How to disable command output in jenkins pipeline build logs如何在詹金斯管道构建日志中禁用命令输出
【发布时间】:2017-02-14 23:00:30
【问题描述】:

我正在使用 Jenkinsfile 编写管道脚本。

有什么方法可以禁止在构建日志中打印已执行的 shell 命令?

这里只是一个简单的 jenkins 管道示例:

node{
  stage ("Example") {
    sh('echo shellscript.sh arg1 arg2')
    sh('echo shellscript.sh arg3 arg4')        
  }
}

在控制台日志中产生以下输出:

[Pipeline] node
Running on master in /var/lib/jenkins/workspace/testpipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] sh
[testpipeline] Running shell script
+ echo shellscript.sh arg1 arg2  
shellscript.sh arg1 arg2
[Pipeline] sh
[testpipeline] Running shell script
+ echo shellscript.sh arg3 arg4
shellscript.sh arg3 arg4
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

基本上我想禁用命令本身的打印。

+ echo shellscript.sh arg1 arg2
+ echo shellscript.sh arg3 arg4

【问题讨论】:

    标签: jenkins jenkins-pipeline jenkinsfile


    【解决方案1】:

    默认情况下,Jenkins 使用标志 -xe 启动 shell 脚本。 -x 启用额外的日志记录。 -e 如果内部的任何命令返回非零退出状态,则使脚本退出。要重置标志,我建议两个选项:

    1. 在脚本正文中调用 set +x
    2. 在没有-x的情况下通过自定义shebang行:sh('#!/bin/sh -e\n' + 'echo shellscript.sh arg1 arg2')

    至于第二个选项,您可以为方便定义一个包装函数,它会在脚本前面加上自定义 shebang,然后调用 sh

    def mysh(cmd) {
        sh('#!/bin/sh -e\n' + cmd)
    }
    

    【讨论】:

    • 这适用于为 windows 工作的任何人 => output = bat(returnStdout: true, script: '')
    • 正在为管道脚本中的每个 sh 打印“别名”列表。我没有弄清楚每个 sh 命令在哪里/如何调用“别名”。但是只使用 '-e' 而不是 '-x' 会导致别名列表不再显示。
    • 请注意,在 Jenkins 为您提供的新“蓝海”视图中,这些环境变量仍将在 UI 中可见。我们通过将命令写入文件(使用 writefile 管道步骤)然后执行文件来解决这个问题。
    【解决方案2】:

    适用于需要后期处理的情况。我扩展了此处提供的原始解决方案。

    例如

    def output = printWithNoTrace("ping -c 1 $FQDN | grep PING).trim()
    

    包装函数

    def printWithNoTrace(cmd) {
    steps.sh (script: '#!/bin/sh -e\n'+ cmd,returnStdout: true)
            }
    

    shell 输出返回到 trim() 并保存到“输出”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-06
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多