Terraform Quickstart: Part 4 – GitHub Terraform Provider Setup
Learn to Configure the GitHub Terraform Provider and Manage Repositories as Code
Introduction
Now that you’ve written your first basic Terraform configuration, it’s time to work with actual infrastructure. In this chapter, we’ll connect Terraform to GitHub and use it to manage a GitHub repository.
You will learn about providers and resources, how to authenticate with GitHub, and how Terraform uses this information to create and manage those resources.
Let’s get started!
Setting Up the GitHub Provider
What you need:
A GitHub personal access token.
Follow these steps to create the token:
Go to your GitHub settings → Developer settings → Personal access tokens.
Click “Fine-grained tokens” or “Tokens (classic)”.
Select the necessary scopes:
For this chapter:
repo
(read/write access to repositories)
Copy the token to a safe place (you won’t see it again).
Writing the Configuration
Create a new folder for this project:
$ mkdir terraform-github
$ cd terraform-github
Create a file called main.tf
and paste this configuration:
terraform {
required_providers {
github = {
source = "integrations/github"
version = "~> 5.0"
}
}
}
provider "github" {
token = var.github_token
owner = var.github_owner
}
resource "github_repository" "demo" {
name = "terraform-demo-repo"
description = "Created with Terraform"
visibility = "public"
}
This code creates a public repository called “terraform-demo-repo
“ with a custom description - "Created with Terraform".
Passing in Your Token Securely
To avoid hardcoding your token, use Terraform variables.
Create a new file: variables.tf
variable "github_token" {
description = "GitHub personal access token"
sensitive = true
}
variable "github_owner" {
description = "GitHub username or organization"
}
Create a file named terraform.tfvars
(this is not committed to version control):
github_token = "your-token-here"
github_owner = "your-github-username"
It’s a best practice to add terraform.tfvars
to your .gitignore
. You don’t want to expose sensitive data such as your token!
Create a file called output.tf
to display the repo URL when the apply
command finishes:
output "html_url" {
value = github_repository.demo.html_url
description = "URL to the repository on the web."
}
Run the Terraform Workflow
Keep reading with a 7-day free trial
Subscribe to Curious Devs Corner to keep reading this post and get 7 days of free access to the full post archives.