Create GitHub Environments using PowerShell

GitHub deployment environments are used to describe a general deployment target such as development or production. Currently, there are two ways to manage environments – using (see Settings > Environments) or using the GitHub REST API. If you would like to automate the management of environments, such as within a PowerShell script, the best approach is to use GitHub REST API. In this post, I will demonstrate how to create environments using PowerShell.

Authenticate with GitHub

In order to create an environment, you will first need to authenticate with GitHub and obtain an access token. The simplest approach is to use the GitHub CLI. If you need to install the GitHub CLI, follow these instructions. Once installed, authenticate with GitHub using the following command:

gh auth login

Once authenticated you can obtain an access token using the following command:

gh auth token

Create an environment

The simplest way to interact with the GitHub REST API from PowerShell is to use the Invoke-WebRequest utility. Create an environment using the following commands:

$owner = "JasonTaylorDev"   # The account owner of the repository
$repo = "RapidBlazor"       # The name of the repository
$envName = "Development"    # The name of the environment

$uri = "$owner/$repo/environments/$envName"
$header = @{"Authorization" = "token $(gh auth token)"}

Invoke-WebRequest -Method PUT -Header $header -ContentType $contentType -Uri $uri

The Deployment environments API provides the capability to create, configure, and delete deployment environments. Review the GitHub docs to learn more.

Next Steps

In this post, I demonstrated the simplest way to create a GitHub environment using PowerShell. The GitHub CLI was used to obtain an access token and the GitHub REST API was used to create the environment. In the future, it would be ideal if environments could be managed using the GitHub CLI. If you would like to learn more, review the following resources:

Thanks for reading, please feel free to post any questions or comments below.