GitHub App Installation for OpenTofu

Nikita Barskov,2 min read

This guide outlines transitioning from PATs to GitHub App Installation when managing GitHub resources with OpenTofu.

Motivation

Using a PAT with my personal GitHub account has been my norm. However, I find GitHub Apps more efficient for managing GitHub resources within organizations.

Prerequisites

Ensure the following are in place before proceeding:

Implementation

Follow these steps to set up the GitHub App.

Create a GitHub Application

Refer to GitHub's documentation on "Installing your own GitHub App" (opens in a new tab) for detailed instructions.

Provide the following information:

Configuring permissions for GitHub App

Depending on your OpenTofu configuration scope, your GitHub App requires different permissions. Review the most used permissions in GitHub's documentation "Endpoints available for GitHub App installation access tokens" (opens in a new tab).

Grant administration: write and metadata: read for repository permissions. You can manage permissions in your GitHub App settings.

Install the application in your organization

Once created, navigate to: https://github.com/organizations/<change-me-org-name>/settings/apps/<change-me-org-name>/installations, click Install, and follow the prompts.

Configure GitHub OpenTofu Provider

Configure Spacelift environment variables

Follow the official documentation on "integrations/github GitHub App Installation" (opens in a new tab) to set up the provider.

Obtain GitHub App ID and GitHub Installation ID from the App settings page. Create environment variables in your Spacelift Stack:

  1. Create TF_VAR_github_app_id variable and set your GitHub App ID
  2. Create TF_VAR_github_app_installation_id variable and set your GitHub App installation ID
  3. Create a PEM Key, encode it using base64, and set it as a secret in TF_VAR_github_app_pem_file.

Add and configure OpenTofu GitHub provider

Update terraform.required_providers in versions.tf:

github = {
  source  = "integrations/github"
  version = "~> 6.0"
}

Configure providers.tf:

provider "github" {
  owner = "change-me-github-organisation-name"
  app_auth {
    id              = var.github_app_id
    installation_id = var.github_app_installation_id
    pem_file        = base64decode(var.github_app_pem_file)
  }
}

Create a PR to import existing repository

As an example, I've imported skov-bar/platform repository using Spacelift and OpenTofu in this PR (opens in a new tab).