从 Jenkins Groovy 脚本控制台写入文件

Write a File from Jenkins Groovy Script-Console

我正在尝试找到一种使用 Jenkins Groovy 脚本控制台将一些内容写入文件的方法。

用例:我们的 CI 使用在所有节点之间共享的卷(依次映射到 EFS)来管理一些状态机。然而 - 在我们的 CI groovy 共享库中发现错误后,我发现一些状态文件已损坏,需要向它们写入更正的值,同时修复错误。

我可以使用 ssh 连接来做到这一点,但是,因为我们正在抽象出工作人员,我们正试图从中退出并仅从脚本控制台管理我们自己 and/or ci 个职位。

我试了所有这些表格,都失败了:

"echo 'the text' > /mnt/efs-ci-state/path/to/the-state-file.txt".execute().text
"""
cat <<<EOF > /mnt/efs-ci-state/path/to/the-state-file.txt
the text
EOF
""".execute().text
"bash -c 'echo the text > /mnt/efs-ci-state/path/to/the-state-file.txt'".execute().text
"echo 'the text' | tee /mnt/efs-ci-state/path/to/the-state-file.txt"

有人能告诉我怎么做吗?

我也很想ci解释为什么上面的表格不起作用and/or关于如何执行包含管道的命令的提示and/orstdio脚本控制台。

谢谢:)

["bash", "echo the text > /mnt/efs-ci-state/path/to/the-state-file.txt"].execute().text

或使用普通 groovy:

new File('/mnt/efs-ci-state/path/to/the-state-file.txt').text = "echo the text"

为什么不工作:

  • 选项 1、2、4:回声和管道是 shell/bash 的一个特性 - 如果没有 bash

    ,它将无法工作
  • 选项 3 你有 c echo 并且 c 不是有效命令

  • 使用数组来执行复杂的命令,将bash与主体分开


如果你想捕获和验证我建议你使用这种代码stderr

["bash", 'echo my text > /222/12345.txt'].execute().with{proc->
    def out=new StringBuilder(), err=new StringBuilder()
    proc.waitForProcessOutput(out, err)
    assert !err.toString().trim()
    return out.toString()
}