Skip to content

Instantly share code, notes, and snippets.

@MuskanPaliwal
Last active September 22, 2023 10:30
Show Gist options
  • Save MuskanPaliwal/da40d8f981d7b2b087b913270aae3045 to your computer and use it in GitHub Desktop.
Save MuskanPaliwal/da40d8f981d7b2b087b913270aae3045 to your computer and use it in GitHub Desktop.
This Gist provides a code example and usage instructions for triggering a GitHub Action workflow using a GitHub App without relying on external libraries like Octokit. It offers a simple way to automate workflows in your repositories when specific events occur.
const fetch = require("node-fetch");
const fs = require("fs");

// Define your GitHub App's authentication information
const APP_ID = process.env.GITHUB_APP_ID;
const PRIVATE_KEY_PATH = "path/to/your/app-private-key.pem";
const WEBHOOK_SECRET = process.env.GITHUB_WEBHOOK_SECRET;
const INSTALLATION_ID = process.env.GITHUB_INSTALLATION_ID;

// Read the private key file
const PRIVATE_KEY = fs.readFileSync(PRIVATE_KEY_PATH, "utf8");

// Generate a JSON Web Token (JWT) for authenticating as the GitHub App
const { sign } = require("jsonwebtoken");
const now = Math.floor(Date.now() / 1000);
const payload = {
  iat: now,
  exp: now + 60,
  iss: APP_ID,
};
const jwt = sign(payload, PRIVATE_KEY, { algorithm: "RS256" });

// Define the GitHub Action workflow to trigger
const workflowId = "your-workflow-id";

// Define the repository and branch/commit to trigger the workflow on
const repoOwner = "your-repo-owner";
const repoName = "your-repo-name";
const ref = "main"; // Replace with the branch or commit ref you want to trigger on

// Create a JSON object with the request payload
const requestData = {
  ref,
  inputs: {
    // Define any input parameters for the workflow
    param1: "value1",
    param2: "value2",
  },
};

// Define the request headers, including JWT for authentication
const headers = {
  "User-Agent": "GitHub-App-Workflow-Trigger",
  Authorization: `Bearer ${jwt}`,
  Accept: "application/vnd.github.v3+json",
};

// Make a POST request to trigger the GitHub Action workflow
fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/actions/workflows/${workflowId}/dispatches`, {
  method: "POST",
  headers,
  body: JSON.stringify(requestData),
})
  .then((response) => {
    if (response.status === 204) {
      console.log("GitHub Action triggered successfully.");
    } else {
      console.error("Failed to trigger GitHub Action. Status:", response.status);
    }
  })
  .catch((error) => {
    console.error("Error occurred while triggering GitHub Action:", error.message);
  });

Usage Instructions:

  1. Prerequisites:

    • Ensure you have Node.js and the node-fetch library installed in your development environment.
    • A GitHub App with the required permissions and webhook events configured.
    • The GitHub App's private key stored securely (e.g., in a .pem file).
    • Knowledge of your GitHub App's ID, webhook secret, and installation ID (if known).
    • Details about the GitHub Action workflow you want to trigger, including its workflow ID, the repository, and the branch/commit to trigger it on.
  2. Configuration:

    • Update the following variables in the code:

      • APP_ID: Your GitHub App's ID.
      • PRIVATE_KEY_PATH: The path to your GitHub App's private key file (in PEM format).
      • WEBHOOK_SECRET: Your GitHub App's webhook secret.
      • INSTALLATION_ID: The installation ID of your GitHub App (if known).
      • workflowId: The ID of the GitHub Action workflow you want to trigger.
      • repoOwner and repoName: The owner and name of the repository where the workflow resides.
      • ref: The branch or commit ref where the workflow should be triggered.
      • inputs: Define any input parameters your workflow requires.
  3. Running the Script:

    • Open your terminal or command prompt.

    • Navigate to the code directory and create a file with .js extension and copy the content oftrigger-github-action.md file.

    • Run the script using Node.js:

      node trigger-github-action.js
  4. Review the Output:

    • Check the console output for the result of triggering the GitHub Action workflow.
  5. License:

    • This code example is provided under the MIT License. Feel free to use it as a starting point for automating GitHub Actions in your projects.

Happy automating!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment