简体   繁体   English

用于检查命令输出并根据参数失败或通过 jenkins 构建的脚本

[英]Script to check output of a command and fail or pass jenkins build based on a parameter

I have a Jenkins job that runs a policy check on yaml files and returns a deny message if there is and error.我有一个 Jenkins 作业,它对 yaml 文件运行策略检查,如果存在错误,则返回拒绝消息。 I want to write a script for the job to fail if a deny message is returned.如果返回拒绝消息,我想编写一个脚本以使作业失败。

This is the command:这是命令:

opa exec "/var/lib/jenkins/workspace/open-policy-agent-test/" --config-file=/home/isw_user/opa-conf.yaml --decision /rules

This is the result of the command:这是命令的结果:

    {
  "result": [
    {
      "path": "/var/lib/jenkins/workspace/open-policy-agent-test/atlantis.yaml",
      "result": {
        "deny": []
      }
    },
    {
      "path": "/var/lib/jenkins/workspace/open-policy-agent-test/manifest/samplefour.yaml",
      "result": {
        "deny": []
      }
    },
    {
      "path": "/var/lib/jenkins/workspace/open-policy-agent-test/test.yaml",
      "result": {
        "deny": [
          "Wrong"
        ]
      }
    }
  ]
}

So if the deny command contains any message I want the build to fail.因此,如果拒绝命令包含任何我希望构建失败的消息。

Is there a way to do this?有没有办法做到这一点?

Yes, you can simply execute a command and return the STDOUT .是的,您可以简单地执行命令并返回STDOUT If you are returning a JSON, you can even parse the Json and extract whatever value you want and validate.如果您要返回 JSON,您甚至可以解析 Json 并提取您想要的任何值并进行验证。 Please refer to the following sample.请参考以下示例。 Please note the returnStdout: true to return the output of the command.请注意returnStdout: true返回命令的输出。

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                script {
                    def output = sh(returnStdout: true, script: "opa exec "/var/lib/jenkins/workspace/open-policy-agent-test/" --config-file=/home/isw_user/opa-conf.yaml --decision /rules").trim()
                    if (output != "") { // Do any validation here
                        error "Build Has Errors, Failing" 
                    }
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM