View as Markdown

Managing Mergify with Terraform

How to manage Mergify configuration declaratively with the official Terraform provider.


The official Mergify Terraform provider lets you manage your Mergify configuration as code, alongside the rest of your infrastructure.

  1. The Mergify GitHub App is installed on your repositories.

  2. A Mergify application key granted the permissions the resources below need. See Authentication below.

Declare the provider in your Terraform configuration:

hcl
terraform {
required_providers {
mergify = {
source = "Mergifyio/mergify"
version = "~> 0.1"
}
}
}
provider "mergify" {
# Token resolution order:
# 1. the `token` attribute set here
# 2. the MERGIFY_TOKEN environment variable
}

Then run:

Terminal windowbash
terraform init

The provider authenticates against the Mergify API with a bearer token, which is a Mergify application key.

Both resources below need a key granted Products at Read & write, and mergify_repository_products also needs Repositories at Read. The provider’s Slack notification resources and its Slack channel data source, listed on the Terraform Registry, need Slack at Read & write. A key granted Every resource at Read & write holds all of these. See Application key permissions. A key granted only CI Reporting is refused with 403. That is easy to hit, because MERGIFY_TOKEN is also the variable a CI pipeline carries its key in.

The token is read from, in priority order:

  1. The token attribute on the provider block.
  2. The MERGIFY_TOKEN environment variable.

A GitHub token is deprecated as a Mergify API credential. Some provider versions still fall back to the GITHUB_TOKEN environment variable; don’t rely on it. The built-in GITHUB_TOKEN secret of GitHub Actions is an installation token (ghs_*), which the Mergify API does not accept.

Manage which Mergify products are enabled on a single GitHub repository.

hcl
resource "mergify_repository_products" "hello_world" {
owner = "octo"
repository = "hello-world"
products = ["merge_queue", "merge_protections", "ci_insights", "workflow_automation"]
}

The products attribute is declarative: applying the resource sets the exact set of enabled products on the repository, removing any that are not listed.

mergify_organization_default_products

Section titled mergify_organization_default_products

Manage the default set of Mergify products enabled when a new repository of an organization is discovered by Mergify.

hcl
resource "mergify_organization_default_products" "defaults" {
organization = "octo"
products = ["merge_queue", "merge_protections"]
}

This only affects new repositories. Existing ones are managed via mergify_repository_products.

Was this page helpful?