How to read GitHub payload in groovy Jenkinsfile?

515 views Asked by At

I have a web hook configured in my GitHub org that triggers a Jenkins pipeline every time a new repo is created. What I am trying to do is get some of the values from the payload which triggers the job and use them in a script within the pipeline. One such example would be the repo name, for instance the payload looks something like this:

{
"action": "created",
"repository": {
    "name": "my-new-repo"
    [...]
  }
[...]
}

I tried assigning the repository["name"] value to a variable in the Jenkinsfile but that did not seem to work:

pipeline{
  environment {
    REPO_NAME = $.repository.name
  }
[...]
}

Also tried it with quotes and some other ways in formatting but still could not get it to be assigned to the REPO_NAME variable.

1

There are 1 answers

0
ycr On

Here is an example of how to Read different attributes from the Webhook request.

pipeline {
  agent any
  triggers {
    GenericTrigger(
     genericVariables: [
      [key: 'REPO_NAME', value: '$.repository.name', defaultValue: 'null'],
      [key: 'PR_TYPE', value: '$.pullrequest.type', defaultValue: 'null']
     ],
     causeString: 'Triggered By Github',
     token: '12345678',
     tokenCredentialId: '',
     printContributedVariables: true,
     printPostContent: true,
     silentResponse: false
    )
  }
  stages {
    stage('ProcessWebHook') {
      steps {
          script {
            echo "Received a Webhook Request from Guthub."
            echo "RepoName: $REPO_NAME"
            
          }
      }
    }
  }
}