github-branch-protector is a simple Azure Function (PowerShell Core) that listens for GitHub organization events to know when a repository has been created. When a repo is created, the function automates the protection of the master branch. A notification with an @mention in an issue within the repository outlines the protections that were added.
- This is a GitHub action to build and deploy the Function to Azure. See pipeline.yml.
A function's project directory contains the files host.json and local.settings.json, along with subfolders that contain the code for individual functions. In this project we have 1 function called GitHubEvent trigger. It contains function.json that holds the configuration metadata for the function, and a single script file run.ps1 that contains the function code.
The function is triggered by an HTTP request from a GitHub webhook. When the function is triggered, it then executes run.ps1. Run.ps1 contains the logic to look for a new repository creation from the webhook, if so, invoke GitHub branch API to update master branch's protection, then invoke GitHub issues API to create new issue containing response from adding protection. If event is not creation of new repository, the script does nothing. Upon completion, a response is sent back to the GitHub webhook with the results.
- Clone repo to Visual Studio Code workspace
- Sign in to Azure using Visual Studio Code
- Publish the project to Azure
- Add App Settings to Azure Functions:
- GITHUB_ORGANIZATION: Set the value to name of organization
- PAT: Create and set value of GitHub personal access token
- GITHUB_WEBHOOKUSER: Set value to name of user who creates webhook in step 5 below
- Create a GitHub webwook in the organization you'd like to protect. When creating the webhook scope it to repository events only. The payload url should be configured to point to the Azure Function trigger url that will look like: https://NAMEOFFUNCTION.azurewebsites.net/api/NAMEOFTRIGGER?code=*******
- Create a new repository to test