GitHub Plugin for Jenkins

repository·master·Indexed 43 days ago

https://github.com/jenkinsci/github-plugin

Integrates Jenkins with GitHub to enable hyperlink decoration, automated build triggers via webhooks, and build status reporting. Supports manual and automatic webhook modes, API request caching, and the GitHubCommitStatusSetter pipeline step. Provides developer tools for custom triggers and WebMethods using @GHRepoName, @GHEventHeader, and @GHEventPayload annotations, including SHA-256 and SHA-1 payload signature verification.

Tokens
2.7K
Snippets
7
Records
13
Agent score
54%

What's inside GitHub Plugin for Jenkins

  1. Configure GitHub Hyperlinks in Jenkins

    master

    The GitHub plugin decorates Jenkins 'Changes' pages with links to GitHub commit and issue pages, and adds a sidebar link to the GitHub project page.

    To enable this, ensure your job is configured to connect to Git. In the 'GitHub project' field, use the format git@github.com:Person/Project.git. In the 'Source Code Management' section, select Git and use the same URL: git@github.com:Person/Project.git.

    git@github.com:Person/Project.git
  2. Use Manual Mode for GitHub Webhooks

    master

    In Manual Mode, you are responsible for manually registering webhook URLs in your GitHub repositories.

    1. Find your Jenkins webhook URL by navigating to Manage Jenkins > Configure System > GitHub. Click the help icon to see the URL.
    2. The URL typically follows the pattern: $JENKINS_BASE_URL/github-webhook/ (e.g., https://ci.example.com/jenkins/github-webhook/).
    3. Add this URL as a webhook in your relevant GitHub repositories.
  3. Use Automatic Mode for GitHub Webhooks

    master

    In Automatic Mode, Jenkins automatically manages (adds/removes) webhook URLs in GitHub for your projects. This requires a GitHub OAuth token with admin:org_hook scope.

    Step 1: Global Configuration Go to the global configuration and add a GitHub Server Config.

    Step 2: Token Setup

    1. Create a personal access token in GitHub. You can use the plugin's helper: Advanced > Manage Additional GitHub Actions > Convert Login and Password to token. Note: This does not work with GitHub 2FA. For 2FA, manually create 'Secret text' credentials using your token.
    2. Select the created 'Secret Text' credentials in the Jenkins configuration.
    3. (Optional) For GitHub Enterprise, check Custom GitHub API URL and provide the URL.

    Step 3: Job Configuration In the configuration of each job you want to trigger, check GitHub hook trigger for GITScm polling under 'Build Triggers'.

  4. Install the GitHub Plugin

    master

    To install the plugin manually:

    1. Build the plugin using mvn hpi:hpi to generate the .hpi file in the target/ directory.
    2. Copy the .hpi file to your $JENKINS_HOME/plugins directory.
    3. Restart Jenkins.

    Alternatively, use the Jenkins Plugin Management Console to upload the .hpi file directly, then restart Jenkins.

    mvn hpi:hpi
  5. Webhook Signature Verification Requirements

    master

    When configuring GitHub webhooks to trigger Jenkins jobs, the plugin can enforce payload signature verification to ensure requests originate from GitHub.

    Signature Algorithms

    • SHA-256 (Recommended): Uses the X-Hub-Signature-256 header. This is the preferred method for enhanced security.
    • SHA-1 (Legacy): Uses the X-Hub-Signature header. This is supported for backward compatibility but is considered deprecated.

    Verification Logic

    1. Secret Configuration: Verification only occurs if a hook secret is configured in the GitHub Plugin settings. If no secret is provided, signatures are ignored.
    2. Payload Handling: The plugin validates the signature against the raw payload. For application/json content types, the raw JSON string is used. For application/x-www-form-urlencoded, the payload is URL-encoded with a payload= prefix before hashing.
    3. Validation Failure: If a signature is missing or invalid, the webhook request will return a 400 Bad Request error.
  6. Configure GitHub API Request Cache

    master

    Each GitHub Server Config uses a GitHub client that can cache API responses to reduce rate-limiting and speed up data fetching.

    • Default Limit: 20MB.
    • Customization: You can change this limit in the Advanced section of the GitHub Server Config.
    • Disable Cache: Set the limit to 0 to disable caching for that specific configuration.
  7. Contribute GitHub repository names to Jenkins jobs

    master

    To ensure Jenkins jobs are correctly associated with GitHub repositories (for purposes like SCM polling or metadata), implementers of GitHubTrigger can provide a list of monitored repositories via getGitHubRepositories().

    For modern implementations, it is recommended to implement GitHubRepositoryNameContributor instead of relying on the deprecated getGitHubRepositories() method. The GitHubRepositoryNameContributorImpl extension automatically scans ParameterizedJob items for any GitHubTrigger implementations to collect associated repository names.

  8. Troubleshoot GitHub Webhook Triggers

    master

    If builds are not being triggered by GitHub pushes, follow these steps:

    1. Verify Hooks in GitHub: Click the 'admin' button on the GitHub repository to ensure post-receive hooks are present. If they are missing, check your Jenkins system configuration credentials.
    2. Test Payload: Use the 'Test hook' button in the GitHub UI to see if Jenkins receives a payload.
    3. Enable Logging: Enable debug logging for the following classes to see the installation attempts:
      • com.cloudbees.jenkins.GitHubPushTrigger
      • org.jenkinsci.plugins.github.webhook.WebhookManager
      • com.cloudbees.jenkins.GitHubWebHook
  9. Set GitHub Commit Status in Pipeline

    master

    You can use the GitHubCommitStatusSetter step in a Jenkins Pipeline to report build results back to GitHub as Commit Statuses.

    Basic Example: Manually specify the repository, context, and status results.

    Advanced Example: Dynamically retrieve the repository URL and commit SHA from the local Git configuration to update the status for the current build.

    void setBuildStatus(String message, String state) {
      step([
          $class: "GitHubCommitStatusSetter",
          reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/my-org/my-repo"],
          contextSource: [$class: "ManuallyEnteredCommitContextSource", context: "ci/jenkins/build-status"],
          errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
          statusResultSource: [ $class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]] ]
      ]);
    }
    
    setBuildStatus("Build complete", "SUCCESS");
  10. Use @GHEventHeader to inject GitHub event types into WebMethods

    master

    When developing custom Jenkins WebMethods (Stapler-based endpoints) that need to respond to GitHub webhooks, you can use the @GHEventHeader annotation on method parameters. This annotation automatically extracts the X-GitHub-Event header from the incoming request and parses it into a GHEvent enum object.

    Requirements:

    • The annotated parameter must be of type org.kohsuke.github.GHEvent.
    • The endpoint must be a valid Jenkins WebMethod.

    If the X-GitHub-Event header is missing or contains an unknown event type, the parameter will be injected as null.

    import org.jenkinsci.plugins.github.webhook.GHEventHeader;
    import org.kohsuke.github.GHEvent;
    import org.kohsuke.stapler.WebMethod;
    
    public class MyGitHubWebhookHandler extends StaplerRequest2 {
        
        @WebMethod
        public void handleWebhook(@GHEventHeader GHEvent event) {
            if (event == null) {
                // Handle missing or unknown event
                return;
            }
            
            if (event == GHEvent.PUSH) {
                // Logic for push events
            }
        }
    }
  11. Use @GHEventPayload to handle GitHub webhook payloads in WebMethods

    master

    When implementing a Jenkins WebMethod to receive GitHub webhooks, you can use the @GHEventPayload annotation on method parameters. This annotation automatically handles the extraction of the webhook payload from the incoming StaplerRequest2 based on the Content-Type header.

    Supported Content-Types:

    • application/json: The payload is extracted from the request input stream using UTF-8 encoding.
    • application/x-www-form-urlencoded: The payload is extracted from the payload request parameter.

    Note: If the request contains the header defined by GitHubWebHook.URL_VALIDATION_HEADER, the parser returns null (this is used for self-tests of custom hook URLs).

    @GET
    @Path("/my-webhook")
    public void handleWebhook(@GHEventPayload String payload) {
        // 'payload' will contain the raw JSON or form-encoded string
        System.out.println("Received payload: " + payload);
    }
  12. Use @GHRepoName to inject GitHub repository names into WebMethods

    master

    When developing Jenkins WebMethods (Stapler actions) that need to handle GitHub repository names from form submissions, use the @GHRepoName annotation on the method parameter. This annotation automatically extracts the repository URL from the request parameter and converts it into a GitHubRepositoryName object.

    To use it, ensure the parameter name in your WebMethod matches the name of the parameter being submitted in the HTTP request.

    @GET
    @FormSubmission
    public void myWebMethod(@GHRepoName String repoUrl) {
        // repoUrl is now a GitHubRepositoryName object
        // extracted from the request parameter matching the argument name
    }