Applying GitHub repo settings with Terraform from CI

I never bothered using Terraform in personal projects, but now that I find myself coding a lot, configuration as code makes sense. This is how I set up terraform with github’s workflows and HashiCorps’s HCP

TL;DR

  • The repo settings are in Terraform files (“configuration as code”). That way they can be reviewed, and I can easily copy them across repos
  • Terraform needs a state; this can be your local machine or some CI magic. Another alternative is to use HCP Terraform’s free tier. Risky (who knows what HashiCorp is planning with their free tier) but for personal projects the the convenience makes it acceptable
  • A bunch of new tokens and env variables need to be created manually, both in HCP and github
  • Github workflows plan on pull requests, apply when the PR merges to main.
  • Set the HCP workspace to Local execution mode, or it will fail in a confusing way.

Why bother

When I create new repos I pretty much use the same settings: squash merges only, a protected main with rulesets, some illegal branch names. It’s tedious to do manually. And if I learn something new I want to apply to my existing repos it becomes tricky.

The two problems with CI

  • State. Terraform remembers what it created in a state file. On a laptop that is a local file. A CI runner starts empty every run, so it would try to create everything again.
  • Credentials. The GITHUB_TOKEN that Actions gives every job cannot change repo administration or rulesets.

Set up HCP Terraform for the state

HCP Terraform is HashiCorp’s hosted service (it used to be called Terraform Cloud). Here it only stores state.

  1. Sign up at app.terraform.io. The free plan is enough for “500 resources”, which works out roughly 100 repos (source).
  2. Create an organization. The name will become your repo variable TF_CLOUD_ORGANIZATION.
  3. Create a workspace named after your repo, type CLI-driven workflow. The name is your TF_WORKSPACE.
  4. In the workspace, Settings → General → Execution Mode: choose Custom → Local.
  5. Create an API token (account settings, Tokens). This becomes the TF_API_TOKEN secret. Make a note of it because it’s shown only once

Why Local: otherwise HCP runs Terraform on its own machines. They have no GitHub token, so the run fails. With Local, HCP stores the state and the GitHub runner does the work.

Why one workspace for repo: you could use one workspace for all your repos, but since your repos are indipendent projects they will overwrite the single terraform state all the time.

Create the GitHub token

  • Go to https://github.com/settings/personal-access-tokens/new
  • Under Repository access, choose Only select repositories and pick your repo.
  • Under Repository permissions, set Administration to Read and write.
  • Set an expiry, and put the date in a calendar. It will stop working one day.

Put the settings in the repo

Variables hold the names, secrets hold the tokens. This is a one off job done by hand; sadly it’s a chicken-and-egg situation, you need the variables to be set if you want Terraform to set the variables. So that won’t work, you have to do it manually. With gh:

gh variable set TF_CLOUD_ORGANIZATION --body "<org>"
gh variable set TF_WORKSPACE --body "<workspace>"
read -rs -p "HCP token: " T && gh secret set TF_API_TOKEN --body "$T"; unset T
read -rs -p "GitHub token: " T && gh secret set TF_GITHUB_TOKEN --body "$T"; unset T

The read lines keep the tokens out of your shell history. It’s a lovely bash command that allows to create setup scripts without leaking secrets to the bash history.

read
a bash builtin that reads one line from the keyboard into a variable
-r
raw: reads all characters as they are, don't interpolate them
-s
silent: don't echo what was typed to the terminal (that's the whole point!)
-p "HCP token:"
prompt: use the string as prompt
T
save what the user typed into $T
&&
If that command worked, start another one
gh
use github's gh cli program
secret set TF_GITHUB_TOKEN
create a secret in the repo called "TF_GITHUB_TOKEN"
--body "$T"
set the content of the secret to whatever you saved earlier into $T
&&
If that command worked, start another one
unset T
now clear $T so that it doesn't get leaked to the CLI by mistake

T show up in the repo under Settings → Secrets and variables → Actions. Secret values are never shown again.

Point Terraform at HCP

An empty cloud block is enough. The organization and workspace come from environment variables, so nothing about your account is committed.

terraform {
  cloud {}
}

The workflow

  • On a pull request that touches terraform/: format check, init, validate, plan. The plan goes in the run summary.
  • On a push to main: apply.
  • One run at a time, and never cancel a running apply.

The shape of it:

on:
  pull_request:
    paths: ["terraform/**"] # or whatever name you used for the folder
  push:
    branches: [main]
    paths: ["terraform/**"]

concurrency:
  group: terraform-github
  cancel-in-progress: false

env:
  TF_CLOUD_ORGANIZATION: ${{ vars.TF_CLOUD_ORGANIZATION }}
  TF_WORKSPACE: ${{ vars.TF_WORKSPACE }}
  GITHUB_TOKEN: ${{ secrets.TF_GITHUB_TOKEN }}

An example file is in this repo

Gotchas

  • The first apply adopts what exists. An import block per existing resource makes the plan show changes instead of creations.
  • A protected main blocks you too. Once the ruleset is on, even the owner cannot push to main. Everything goes through a PR. That is the point.
  • Pin a lock file. Commit .terraform.lock.hcl so CI and your laptop use the same provider version.

Got thoughts on this post? Join the conversation on Mastodon!