Search code examples
jenkinsjenkins-pipelinejenkins-groovy

Conditional step in pipeline executed only based on output of a previous setp


sorry I'm not an expert in Jenkins pipelines but maybe someone can point me in the correct direction

I am trying to do something similar to this posts but I have yet to figure it out.

Conditional step in a pipeline

How to run a conditional step in Jenkins only when a previous step fails

https://www.jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

So what I want to achieve is the following.

I have a script that fetches some files and stores them in my project I want at a second stage run it so that I create a PR if there are some changes in the files that were fetch. The idea is run this pipeline daily/weekly

So I'm trying to do something like this:

#!groovy

pipeline {
  stages {
    stage('Definitions updated') {
      steps {
        sh "./gradlew updateDefinitions"
        gitStatus = sh(returnStdout: true, script: 'git status').trim()
        ## how to expose gitStatus to the outside
      }
    }
    stage ('Create PR') {
      when {
        // Only say hello if a "status returned something"
        ## how to use the gitStatus to check against a certain output
        expression { SOMETHING == 'SOMETHING'' }
      }
      steps {
        sh "git add ."
        etc...
      }
    }
  }
}

Some I'm not really sure how can I for example store something out of my sh command into my environment variables so that I could use it later in the condition of the next step.

I also don't know exactly if I understood correctly that this will run in parallel or not, I hope all stages are sequential but I'm not 100% sure.

Is there any example I could figure out something similar to out to store output of a sh into an environment variable?

Thank you for any feedback


Solution

  • you can declare the gitStatus outside the pipeline block as below

    def gitStatus
    
    pipeline {
      stages {
        stage('Definitions updated') {
          steps {
            sh "./gradlew updateDefinitions"
            gitStatus = sh(returnStdout: true, script: 'git status').trim()
            ## how to expose gitStatus to the outside
          }
        }
        stage ('Create PR') {
          when {
            // Only say hello if a "status returned something"
            ## how to use the gitStatus to check against a certain output
            expression { gitStatus == 'SOMETHING'' }
          }
          steps {
            sh "git add ."
            etc...
          }
        }
      }
    }