DEV Community

Cover image for Solved: Auto-Assign GitHub Issues to Developers based on Labels using Actions
Darian Vance
Darian Vance

Posted on • Originally published at wp.me

Solved: Auto-Assign GitHub Issues to Developers based on Labels using Actions

🚀 Executive Summary

TL;DR: Manual GitHub issue assignment leads to significant overhead and unbalanced workloads. This guide provides a GitHub Action solution to automatically assign issues to specific developers based on their labels, streamlining the development workflow and ensuring prompt attention.

🎯 Key Takeaways

  • GitHub Actions workflows, defined in YAML files, can be triggered by issue events (opened, labeled) to automate tasks.
  • The core automation logic involves an embedded JavaScript assigneesMap within the workflow, linking issue labels to specific GitHub usernames.
  • The workflow requires permissions: issues: write to authorize the GitHub Action to modify issues by calling the github.rest.issues.addAssignees API endpoint.

Auto-Assign GitHub Issues to Developers based on Labels using Actions

As a DevOps Engineer, you know the value of automation. Manual processes are not only time-consuming but also prone to human error, creating bottlenecks in even the most streamlined workflows. One common scenario in software development is the manual assignment of GitHub issues. When a new bug report comes in, or a feature request is logged, someone has to read it, determine its type, and then assign it to the appropriate developer.

This seemingly small task can accumulate into significant overhead, especially for active projects or larger teams. Developers might pick up issues randomly, leading to an unbalanced workload, or critical issues might sit unassigned for too long. Imagine a world where issues, upon creation or label addition, are automatically routed to the right team member, ensuring prompt attention and fair distribution.

This is where GitHub Actions comes in. In this comprehensive tutorial, we will walk you through the process of setting up a GitHub Action that automatically assigns issues to specific developers based on the labels applied to the issue. This automation will free up your team’s time, reduce triaging overhead, and keep your development pipeline moving smoothly and efficiently.

Prerequisites

Before we dive into the implementation, make sure you have the following:

  • A GitHub Repository: You’ll need an active GitHub repository where you have at least write access to configure workflows.
  • GitHub Admin/Write Permissions: To create and manage GitHub Actions workflows, you need appropriate permissions on the repository.
  • Basic GitHub Actions Knowledge: While we will explain each step, a fundamental understanding of what GitHub Actions are and how they operate (e.g., workflow files, events, jobs, steps) will be beneficial.
  • GitHub Usernames: You should know the GitHub usernames of the developers you wish to assign issues to.
  • Defined Labels: Have a clear understanding of the labels you use in your repository and which developer should be associated with each.

Step-by-Step Guide: Auto-Assigning Issues

Step 1: Define Your Label-to-Developer Mappings

The core of our automation relies on a mapping between issue labels and GitHub usernames. This mapping will tell our GitHub Action which developer to assign an issue to when a specific label is present. For simplicity, we’ll embed this mapping directly within our workflow file using a JavaScript object. For more complex scenarios, you might consider externalizing this (e.g., as a repository secret or a separate configuration file), but for most cases, embedding is sufficient and easier to manage.

Consider a mapping like this, where the keys are your GitHub issue labels and the values are the GitHub usernames:

            const assigneesMap = {
              'bug': 'octocat',        // Issues with 'bug' label go to 'octocat'
              'feature': 'monalisa',  // Issues with 'feature' label go to 'monalisa'
              'enhancement': 'octocat',
              'docs': 'monalisa',
              'critical': 'devops-guru'
            };
Enter fullscreen mode Exit fullscreen mode

Replace 'octocat', 'monalisa', and 'devops-guru' with the actual GitHub usernames of your team members.

Step 2: Create the GitHub Workflow File

GitHub Actions workflows are defined in YAML files located in the .github/workflows/ directory of your repository. Create a new file, for example, .github/workflows/auto-assign.yml. This file will contain the instructions for our automation.

The workflow needs to be triggered whenever an issue is opened or when labels are applied to an existing issue. We also need to grant the workflow specific permissions to be able to modify issues (i.e., assign them).

Here’s the basic structure of our workflow file:

name: Auto-Assign Issue based on Labels

on:
  issues:
    types: [opened, labeled] # Trigger on new issues or when labels are added/changed

permissions:
  issues: write # IMPORTANT: Grant permission to write issues for assignment

jobs:
  auto-assign:
    runs-on: ubuntu-latest
    steps:
      - name: Auto-Assign Issue
        # We will add the logic for assignment here in Step 3
Enter fullscreen mode Exit fullscreen mode

The on: issues: types: [opened, labeled] block ensures our workflow runs whenever a new issue is created or when labels are modified on an issue. The permissions: issues: write line is crucial; without it, the GitHub Action would not have the necessary authorization to assign issues.

Step 3: Implement the Assignment Logic

Now, let’s add the JavaScript logic that reads the issue’s labels, compares them against our mapping, and performs the assignment using the GitHub API. We’ll use the actions/github-script action, which allows us to write inline JavaScript that interacts directly with the GitHub API.

Insert the following code into the steps: section of your auto-assign.yml file from Step 2:

name: Auto-Assign Issue based on Labels

on:
  issues:
    types: [opened, labeled]

permissions:
  issues: write # Grant permission to write issues for assignment

jobs:
  auto-assign:
    runs-on: ubuntu-latest
    steps:
      - name: Auto-Assign Issue
        uses: actions/github-script@v7 # Use the GitHub Script action
        with:
          script: |
            // Define your label-to-developer mapping here
            const assigneesMap = {
              'bug': 'octocat',        // Example: 'bug' label assigns to 'octocat'
              'feature': 'monalisa',  // Example: 'feature' label assigns to 'monalisa'
              'enhancement': 'octocat',
              'docs': 'monalisa',
              'critical': 'devops-guru'
            };

            const issue = context.payload.issue;
            if (!issue) {
              console.log('No issue payload found. Exiting.');
              return;
            }

            // Extract label names from the issue
            const issueLabels = issue.labels.map(label => label.name);
            console.log(`Issue Labels: ${issueLabels.join(', ')}`);

            let assigneesToAdd = [];

            // Iterate through the issue's labels and check for matches in our map
            for (const label of issueLabels) {
              if (assigneesMap[label]) {
                const assignee = assigneesMap[label];
                // Ensure we don't add the same assignee multiple times
                if (!assigneesToAdd.includes(assignee)) {
                  assigneesToAdd.push(assignee);
                  console.log(`Found mapping for label "${label}". Assigning to: ${assignee}`);
                }
              }
            }

            // If we found any assignees, perform the assignment
            if (assigneesToAdd.length > 0) {
              try {
                await github.rest.issues.addAssignees({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: issue.number,
                  assignees: assigneesToAdd,
                });
                console.log(`Successfully assigned issue #${issue.number} to: ${assigneesToAdd.join(', ')}`);
              } catch (error) {
                console.error('Failed to add assignees:', error);
                throw error; // Re-throw to fail the action if assignment fails
              }
            } else {
              console.log('No matching labels found for assignment. Issue will remain unassigned.');
            }
Enter fullscreen mode Exit fullscreen mode

Logic Explanation:

  • We start by defining assigneesMap, which is our lookup table.
  • The script retrieves the current issue details from the context.payload.issue object.
  • It then extracts all label names from the issue.
  • It iterates over these labels. If a label matches a key in our assigneesMap, the corresponding developer’s username is added to the assigneesToAdd array. We include a check to avoid adding the same assignee multiple times if an issue has several relevant labels.
  • Finally, if assigneesToAdd is not empty, it calls github.rest.issues.addAssignees, which is the GitHub API endpoint for assigning issues. This function takes the repository owner, name, issue number, and the list of assignees.
  • Error handling is included to catch potential API failures.

Step 4: Test Your Workflow

With the workflow file committed to your repository’s main or master branch, it’s time to test it:

  1. Open a New Issue: Go to your GitHub repository and create a brand new issue.
  2. Apply a Label: Add one of the labels defined in your assigneesMap (e.g., bug, feature, critical) to this new issue. You can apply the label during issue creation or afterwards.
  3. Check Actions Tab: Navigate to the “Actions” tab in your repository. You should see a new workflow run for “Auto-Assign Issue based on Labels”.
  4. Verify Assignment: Once the workflow completes (it should be very quick), go back to your issue. You should see that it has been automatically assigned to the developer specified in your mapping.

If the workflow fails, examine the logs in the “Actions” tab for details on what went wrong.

Common Pitfalls

Even with a well-designed workflow, issues can arise. Here are a couple of common pitfalls and how to address them:

  • Incorrect Permissions: If your workflow fails with an “Unauthorized” or “Resource not accessible by integration” error, double-check that you have included permissions: issues: write at the job level or globally in your workflow file. Without this, the GitHub Action cannot modify issues.
  • Non-existent Users or Labels: Ensure that the GitHub usernames in your assigneesMap are correct and correspond to actual collaborators in your repository. Similarly, ensure the labels in your map exactly match the labels in your repository (case-sensitive). If an assignee is not a collaborator, GitHub might silently ignore the assignment or the action might fail.
  • Rate Limiting: For most typical usage, this workflow won’t hit GitHub API rate limits. However, if you have an extremely high volume of issues or very complex workflows making many API calls, you might encounter rate limiting. The github-script action generally handles this gracefully, but be aware it’s a possibility. Simplify your logic or consider optimizing API calls if this becomes an issue.

Conclusion

Automating issue assignment based on labels using GitHub Actions is a powerful way to streamline your development workflow. It reduces manual overhead, ensures consistent triaging, and helps balance the workload across your team. By following these steps, you’ve successfully implemented a smart automation that frees up your team to focus on what they do best: building great software.

This is just the beginning of what you can achieve with GitHub Actions. Consider these next steps to further enhance your automation:

  • More Sophisticated Mapping: Explore using GitHub repository secrets to store your label-to-developer map, making it easier to update without modifying the workflow file directly.
  • Round-Robin Assignment: For generic labels like ‘help-wanted’, implement a round-robin system to distribute issues evenly among a pool of developers.
  • Project Board Integration: Automatically add newly assigned issues to specific GitHub Project boards or columns.
  • Multiple Assignees: Modify the logic to assign issues to multiple developers if certain conditions are met (e.g., a ‘critical’ bug needing attention from both a backend and a QA engineer).
  • Comment on Assignment: Add an automatic comment to the issue when it’s assigned, informing the assignee or the original reporter.

Embrace automation, and let GitHub Actions handle the repetitive tasks, so your team can dedicate their energy to innovation.


Darian Vance

👉 Read the original article on TechResolve.blog


☕ Support my work

If this article helped you, you can buy me a coffee:

👉 https://buymeacoffee.com/darianvance

Top comments (0)