🥬

GitHubリポジトリをTerraformで作成してみた

に公開

なんの記事?

Terraform = AWSなどクラウドのイメージが強いかと思います。
GitHubの各種設定もTerraformで書けそうだったので試してみました。

GitHub Provider

https://registry.terraform.io/providers/integrations/github/latest/docs

ハンズオン

リポジトリの設定

  • リポジトリの初期設定 & 初回コミット
  • 流動的な設定はTerraformで取り扱わない
repository.tf
resource "github_repository" "repository" {
  name         = "リポジトリ名"
  description  = "リポジトリの説明"
  visibility   = "public" # or private
  has_issues   = true
  has_wiki     = true
  has_projects = false
  auto_init    = true
  topics       = ["terraform", "github", "sandbox"]
}

# first commit
resource "github_repository_file" "initial_commit" {
  repository     = github_repository.repository.name
  file           = "README.md"
  content        = "This is initial commit in repository."
  commit_message = "Initial commit"
}

ブランチの設定

  • デフォルトブランチの指定とルール設定
  • mainブランチに対する直接のPushを禁止し、PRを介するように制限を設ける
branch.tf
resource "github_branch_default" "main" {
  repository = github_repository.repository.name
  branch     = "main"
}


resource "github_repository_ruleset" "main_branch_protection" {
  name        = "Main Branch Protection"
  repository  = github_repository.repository.name
  target      = "branch"
  enforcement = "active"

  conditions {
    ref_name {
      include = ["~DEFAULT_BRANCH"]
      exclude = []
    }
  }

  rules {
    required_linear_history = true

    pull_request {
      require_code_owner_review = true
    }
  }

  bypass_actors {
    actor_type = "RepositoryRole"
    actor_id = 5
    bypass_mode = "always"
  }
}

terraformブロック

  • Terraformのversionと利用するプロバイダの設定 ( required_providers )
  • state管理は試すだけなのでローカル (本番利用時はリモートにしてください)
  • GitHub への認証には provider "github" を使用し環境変数から取得する
config.tf
terraform {
  required_version = ">= 1.3.0"
  required_providers {
    github = {
      source  = "integrations/github"
      version = "~> 6.6.0"
    }
  }
  backend "local" {
    path = "terraform.tfstate"
  }
}

provider "github" {
  token = var.github_token
  owner = var.github_owner
}

Terraform は、環境変数の接頭辞が TF_VAR_ のものを自動でマッピングしてくれる

.env
export TF_VAR_github_owner="GitHubのアカウント名"
export TF_VAR_github_token="GitHubから発行したトークン"

所感

リポジトリごとの設定作業が簡単になりそう!

  • 他リポジトリとの設定を見比べたり
  • 今の設定どうなってるんだっけ… ⇒ どこの画面に設定ある???

反面、運用が返って複雑になる可能性🤔

  • どのresourceが何に依存するのか。 module として分け方を考える
  • どこまでをTerraformの管理下にするかを明確にする (例: ブランチ作成はTF必須?)
  • ※これはどのIaC導入も考える必要がありそう

Discussion