如何在jenkins管道构建日志中禁用命令输出

Vas*_*man 24 jenkins jenkins-pipeline jenkinsfile

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

有没有办法在构建日志中禁用已执行的shell命令的打印?

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

node{
  stage ("Example") {
    sh('echo shellscript.sh arg1 arg2')
    sh('echo shellscript.sh arg3 arg4')        
  }
}
Run Code Online (Sandbox Code Playgroud)

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

[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
Run Code Online (Sandbox Code Playgroud)

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

+ echo shellscript.sh arg1 arg2
+ echo shellscript.sh arg3 arg4
Run Code Online (Sandbox Code Playgroud)

izz*_*kil 43

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

  1. 调用set +x脚本的正文.
  2. 通过定制shebang线没有-x:sh('#!/bin/sh -e\n' + 'echo shellscript.sh arg1 arg2')

对于第二个选项,您可以为方便起见定义包装函数,该函数将在脚本前添加自定义shebang然后调用 sh

def mysh(cmd) {
    sh('#!/bin/sh -e\n' + cmd)
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在 Jenkins 为您提供的新“蓝海”视图中,这些环境变量在 UI 中仍然可见。我们通过将命令写入文件(使用 writefile 管道步骤)然后执行该文件来解决这个问题。 (3认同)
  • 这适用于为 windows => output = bat(returnStdout: true, script: '<SOME_COMMAND>') 工作的任何人 (2认同)

upH*_*ler 7

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

例如

def output = printWithNoTrace("ping -c 1 $FQDN | grep PING).trim()
Run Code Online (Sandbox Code Playgroud)

包装函数

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

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