jenkinsci / bitbucket-push-and-pull-request-plugin

Plugin for Jenkins v2.138.2 or later, that triggers job builds on Bitbucket's push and pull request events.
https://plugins.jenkins.io/bitbucket-push-and-pull-request
MIT License
46 stars 50 forks source link

Triggers are not configured. #288

Open sumitsharma16 opened 1 year ago

sumitsharma16 commented 1 year ago

HI Team

After creating the pull request the Jenkins is recognizing the pull request creation but the build is not triggering. We are getting the below logs :

Jenkins global logs

Received POST request over Bitbucket hook Nov 01, 2022 11:22:37 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.processor.BitBucketPPRPayloadProcessorFactory createProcessor Create BitBucketPPRRepositoryCloudPayloadProcessor Nov 01, 2022 11:22:37 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.processor.BitBucketPPRRepositoryCloudPayloadProcessor buildActionForJobs Instantiate BitBucketPPRRepositoryAction Nov 01, 2022 11:22:37 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.action.BitBucketPPRRepositoryAction Received commit hook notification for branch: ecosystemPlaybooks Nov 01, 2022 11:22:37 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.action.BitBucketPPRRepositoryAction Received commit hook type: branch Nov 01, 2022 11:22:37 AM WARNING io.jenkins.plugins.bitbucketpushandpullrequest.BitBucketPPRTrigger onPost Triggers are not configured. Nov 01, 2022 11:22:51 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.receiver.BitBucketPPRHookReceiver doIndex Received POST request over Bitbucket hook Nov 01, 2022 11:22:51 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.processor.BitBucketPPRPayloadProcessorFactory createProcessor Create BitBucketPPRPullRequestCloudPayloadProcessor Nov 01, 2022 11:22:51 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.common.BitBucketPPRUtils lambda$matches$2 Matched branch: :^(?!(origin/prefix)). Nov 01, 2022 11:22:51 AM INFO io.jenkins.plugins.bitbucketpushandpullrequest.common.BitBucketPPRUtils lambda$matches$2 Matched branch: :^(?!(origin/prefix)).

Jenkins Code

node('jenkins_slave_node_1'){

properties([[$class: 'JobLocalConfiguration', changeReasonComment: ''], pipelineTriggers([bitBucketTrigger(credentialsId: 'builddlt', triggers: [[$class: 'BitBucketPPRPullRequestTriggerFilter', actionFilter: [$class: 'BitBucketPPRPullRequestCreatedActionFilter', allowedBranches: '*/master', isToApprove: false]]])])])

    cleanWs()
    stage('Checkout'){

           checkout([$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, 
           extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'builddlt', 
           url: '<URL>']]])
        }  

stage('echo'){
    echo "Executed Successfully"
    echo 'Env vars for cloud pull request...'
    echo "BITBUCKET_SOURCE_BRANCH ${env.BITBUCKET_SOURCE_BRANCH}"
    echo "BITBUCKET_TARGET_BRANCH ${env.BITBUCKET_TARGET_BRANCH}"
    echo "BITBUCKET_PULL_REQUEST_LINK ${env.BITBUCKET_PULL_REQUEST_LINK}"
    echo "BITBUCKET_PULL_REQUEST_ID ${env.BITBUCKET_PULL_REQUEST_ID}"
    echo "BITBUCKET_PAYLOAD ${env.BITBUCKET_PAYLOAD}"
}

}

JOB console output:

Env vars for cloud pull request... [Pipeline] echo BITBUCKET_SOURCE_BRANCH null [Pipeline] echo BITBUCKET_TARGET_BRANCH null [Pipeline] echo BITBUCKET_PULL_REQUEST_LINK null [Pipeline] echo BITBUCKET_PULL_REQUEST_ID null [Pipeline] echo BITBUCKET_PAYLOAD null [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline Finished: SUCCESS

Kindly help us on that, we have stuck because of that. The same thing is working for freestyle job. Thanks

martens-d commented 1 year ago

I struggled with it too. You HAVE TO specify the git remote url:

In a free style-job:

In a pipeline job:

sumitsharma16 commented 1 year ago

@martens-d Still getting the same log

Triggers are not configured.

and in the jenkins Last BitBucket Push Polling has not run yet.

I have tried pipeline script from scm with the same repository bit no luck it is the same log is generating and build is not getting triggered

martens-d commented 1 year ago

Well, I use Declarative Pipeline but the beginning should be the same. Here is my pipeline:

import groovy.json.JsonOutput;
import groovy.json.JsonSlurperClassic;
import java.text.SimpleDateFormat;

properties([
  pipelineTriggers([
    [
      $class: 'BitBucketPPRTrigger',
      triggers : [
        [          
          $class: 'BitBucketPPRPullRequestServerTriggerFilter',
          actionFilter: [
            $class: 'BitBucketPPRPullRequestServerCreatedActionFilter',
          ]
        ],
        [
          $class: 'BitBucketPPRPullRequestServerTriggerFilter',
          actionFilter: [
            $class: 'BitBucketPPRPullRequestServerApprovedActionFilter',
          ]
        ],
        [
          $class: 'BitBucketPPRPullRequestServerTriggerFilter',
          actionFilter: [
            $class: 'BitBucketPPRPullRequestServerDeclinedActionFilter',
          ]
        ],
        [
          $class: 'BitBucketPPRPullRequestServerTriggerFilter',
          actionFilter: [
            $class: 'BitBucketPPRPullRequestServerMergedActionFilter',
          ]
        ]
      ]
    ]
  ])
])

pipeline
{
  agent any

  stages
  {
    stage ('Teams')
    {
      steps
      {
        echo "stage Teams #####################################"
        script
        {
          if (env.BITBUCKET_PULL_REQUEST_ID != null) 
          {
            def pretty = parseJsonToMap(env.BITBUCKET_PAYLOAD);

            prId = pretty.pullRequest.id;
            slug = pretty.pullRequest.fromRef.repository.slug;
            key  = pretty.pullRequest.fromRef.repository.project.key;

            withCredentials([usernameColonPassword(credentialsId: 'XYZ', variable: "API_TOKEN")]) {
              response = sh(script: " \"C:\\Program Files\\curl\\bin\\\\\"curl -u ${API_TOKEN} -H \"Content-Type: application/json\" https://bitbucket/rest/api/1.0/projects/${key}/repos/${slug}/pull-requests/${prId} ", returnStdout: true)
            }

            def json = parseJsonToMap(response);
            def state = json.state;
            def prinfo = 'from ' + json.fromRef.displayId + ' to ' + json.toRef.displayId;

            if (state == "OPEN")
            {
               ...
            }

            if (state == "MERGED")
            {
              ...
            }
          }
        }
      }
    }
  }
}

@NonCPS
def parseJsonToMap(String json) {
  final slurper = new JsonSlurperClassic()
  return new HashMap<>(slurper.parseText(json))
}

What I noticed you have pipelineTriggers bitBucketTrigger but shouldn't it be BitBucketPPRTrigger? Also run the pipeline first be hand, that seems to set up the trigger.

nikitin-dev commented 1 year ago

@martens-d, сould you tell me how you set up credentials in Jenkins? I need to set "approve" on PR if pipeline build successful and else set "request changes" I've created OAuth consumer in bitbucket, there key and secret. https://plugins.jenkins.io/bitbucket-push-and-pull-request/#plugin-content-authentication-for-state-notification-and-generally-when-using-the-bitbucket-rest-api says that we should use Secret Text type. Secret Text has only one field, we need to pass the key or secret?

And one more question.. Is it enough to check Let Jenkins approve or unapprove the pull request on BitBucket, or we should do smth programmatically?

martens-d commented 1 year ago

In my example, I use curl to retrieve more info. This plugin doesn't have enough. I simply use username/password. (configure Jenkins --> Security, Manage Credentials [(http://JENKINS_URL/credentials)] --> click on "global" --> add credentials)

For the plugin itself you set up a webhook in bitbucket with: http://JENKINS_URL/bitbucket-hook/ and when it should be fired. No password or user required. The webhook can be set to more than you need and in the individual pipelines you select which event the pipeline should run at (different pipelines for different events).

I don't use "Jenkins approve or unapprove the pull request on BitBucket", that requires the plugin to talk back, witch I can't get to work, because Jenkins runs on a Windows Server and that alone was tricky. There seems to be a small problem with the reverse proxy.

I would use a curl request like in my example, with username/password. Look here: https://docs.atlassian.com/bitbucket-server/rest/5.16.0/bitbucket-rest.html#idm8297609456

pratimamaiti13 commented 11 months ago

Hi @martens-d , I have tried as you suggested(I am using bitbucket-cloud), pipeline was triggered as well. But after every some time it's again started giving the same issue "Triggers are not configured". To be more specific whenever I am adding some other triggers like "merge" along with "approve". It's giving issues. Even triggering the pipeline manually is not solving the issue at that time. Can you please suggest?

martens-d commented 11 months ago

Hi @pratimamaiti13, I actually switched to generic Triggers, because I found out, that I get a response there too. And I don't have the limitations for the jobs. You add a webhook to the repo with an url like this: http://jenkinsurl:8080/generic-webhook-trigger/invoke?token=PullRequest

pipeline
{
  agent any

  environment {
    // Filter
    REPO = 'repositoryname'
    PROJECT = 'projectname'
  }

  triggers {
    GenericTrigger (
      genericVariables: [
        [ key: "response", value: "\$" ] // the variable in witch the response is in
      ],
      token: "PullRequest", // Token in the url of bitbucket
      printContributedVariables: false,
      printPostContent: false
    )
  }

  stages
  {
    stage ('Teams')
    {
      steps
      {
        echo "stage Teams #####################################"
        script
        {
          def json = parseJsonToMap(response);

          if (debug) {
            println response

            println "Project: " + json.pullRequest.toRef.repository.project.key.toString();
            println "Repo   : " + json.pullRequest.toRef.repository.slug.toString();
          }
          if ((json.pullRequest.toRef.repository.project.key.toString() == PROJECT) && (json.pullRequest.toRef.repository.slug.toString() == REPO))
          {
            // PR from to
            def prinfo = json.pullRequest.fromRef.displayId.minus("feature/") + ' nach ' + json.pullRequest.toRef.displayId.minus("feature/");
            // get the event
            def event = json.eventKey;
            // get date from JSON and parse to Format
            def datum = new SimpleDateFormat("dd.MM.yyyy - HH:mm").format(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(json.date));

            // get actor
            def actor = "**" + parseName(json.actor.displayName) + "**";

            // react to event
            switch (event) {            
              case "pr:opened":
                println "Pull Request opened"; 
                break; 
              case "pr:modified": 
                println "Pull Request modified"; 
                break; 
              case "pr:reviewer:updated":
                println "Pull Request reviewer updated"; 
                break; 
              case "pr:reviewer:approved": 
                println "Pull Request approved"; 
                break; 
              case "pr:reveiwer:unapproved": 
                println "Pull Request not approved"; 
                break; 
              case "pr:merged": 
                println "Pull Request merged"; 
                break; 
              case "pr:declined": 
                println "Pull Request declined"; 
                break; 
              case "pr:deleted": 
                println "Pull Request deleted"; 
                break; 
              default: 
                println "nothing to do"; 
                break; 
            }
          }
        }
      }
    }
  }

}

In your case: I think you have to add in the class 'BitBucketPPRTrigger' the triggers for "merge" and "approve" (BitBucketPPRPullRequestServerMergedActionFilter and BitBucketPPRPullRequestServerApprovedActionFilter).

And you need to run the pipeline once manually after you added them. Only than are they set to active in the list of triggers for that pipeline in the plugin. Maybe that is your issue.