LoginSignup
3
0

More than 3 years have passed since last update.

TerraformでGithubのRepositoryをマネージしてみる

Posted at

なぜ

GithubのRepositoryの管理権限をマニュアルに管理していると各リポジトリの管理者権限をだれが持ってるのかが見えない (どっかの権限をいじれば、管理者がだれなのかを見せることができるのかもしれないがそんな機能があったら教えていただきたいです)

コード化

Github のTerraform providerがあるのでGithubのRepositoryとRepositoryの権限をコード化すれば情報が透明化できるし、確認もしやすくなるのでは?

GithubをTerraformでマネージする準備 (Terraform Cloud)

  1. backend.tf (今回はTerraform Cloud) と provider.tfを作成

    backend.tf
    terraform {
      backend "remote" {
        hostname     = "app.terraform.io"
        organization = "naka" # 自分のTerraform Cloudのアカウント名
    
        workspaces {
          name = "github" # 自分のアカウントの中のWorkspace名 任意で名前をつけられる
        }
      }
    }
    
    provider.tf
    terraform {
      required_providers {
        github = {
          source  = "integrations/github"
          version = "~> 4.0"
        }
      }
    }
    
    provider "github" {
      owner = "nakamasato" # 自分のGithubのアカウント名 例: https://github.com/nakamasato
    }
    
  2. バックエンドへのアクセスをできるようにしておく

    1. バックエンドがTerraform Cloudの場合はterraform loginしておく
    2. バックエンドがローカルの場合は不要
    3. バックエンドがS3などの場合はRead/Writeアクセス権を付与
  3. terraform initを実行

    1. Terraform Cloudの場合は、Workspaceが作成される
  4. Github Tokenを生成して環境変数に設定する (一旦 repodelete_repo の権限を付与。管理するリソースの必要に応じて変更。)

    1. Terraform Cloudの場合、UIから環境変数を設定Screen Shot 2021-07-08 at 10.04.57.png
    2. それ以外の場合は、Terraformの変数で渡すか、 ローカルのGITHUB_TOKEN 環境変数をセット (https://registry.terraform.io/providers/integrations/github/latest/docs)

      provider "github" {
        token = var.token # or `GITHUB_TOKEN`
      }
      

これで基本は自分の書きたいリソースをtf ファイルに書いてApplyすれば良くなる。準備完了

Terraformでリソース作成する

Repository

repository.tf
resource "github_repository" "terraform-github-template" {
  name        = "terraform-github-template"
  description = "template repository create by terraform"

  visibility = "public"
}

Repositoryのbranch protection

branch_protection.tf
resource "github_branch_protection" "terraform-github-template-main" {
  repository_id = github_repository.terraform-github-template.node_id

  pattern          = "main"
  enforce_admins   = true
  allows_deletions = false
}

Applyの自動化 (上記の準備でTerraform Cloudにした場合)

  1. Terraform Cloudでコードがマージされたら自動でApplyしたい場合は、 Version Controlを設定して、Auto applyにチェックを入れる。
  2. Version Controlで設定したRepoに、初PRを作成してTerraform Cloudが動いているか確認する
  3. マージして自動でApplyされる

既存リソースのImport

例では、https://github.com/nakamasato/eks をインポート

  1. tfファイルを用意

    import.tf
    resource "github_repository" "eks" {
      name                 = "eks"
    
      visibility = "public"
    }
    
  2. インポート terraform import github_repository.terraform terraform (Terraform Cloudでは terraform loginしてる必要あり)

    1. terraform import github_repository.eks eks
  3. (Optional) tfファイルの修正

    1. terraform plan すると自分で作成したtfとimportしたstateにDiffがある場合があるので、Planして No changes. Your infrastructure matches the configuration. になるまで直す
    2. 例 最終的にはこんな感じ
    import.tf
    resource "github_repository" "eks" {
      name                 = "eks"
      description          = "Manage EKS cluster with Terraform (development purpose only)"
      allow_merge_commit   = false
      allow_rebase_merge   = false
      has_downloads        = true
      has_issues           = true
      has_projects         = true
      has_wiki             = true
      vulnerability_alerts = true
      topics = [
      ]
    
      visibility = "public"
    }
    
  4. コードプッシュ (Terraform Cloudも変更なし)

注意:

Terraform CloudにGITHUB_TOKENを環境変数で設定していても、importするときは、ローカルでも GITHUB_TOKEN を設定しておかないと以下のエラーが出る

terraform import github_repository.python-sample python-sample            
Acquiring state lock. This may take a few moments...
╷
│ Error: Cannot import non-existent remote object
│ 
│ While attempting to import an existing object to "github_repository.python-sample", the provider detected that no object exists with the given id. Only pre-existing
│ objects can be imported; check that the id is correct and that it is associated with the provider's configured region or endpoint, or use "terraform apply" to
│ create a new remote object for this resource.

GITHUB_TOKENを設定:

export GITHUB_TOKEN=xxxxx

再度挑戦:

terraform import github_repository.python-sample python-sample
Acquiring state lock. This may take a few moments...

Import successful!

The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.

まとめ

Githubのレポやブランチ権限をTerraformで管理してみた。レポへの管理権限や誰がマージ権限を持つかなどは管理できそうで、誰が管理・マージ権限もってるかの情報がオープンにできそう。

参考

ToDo

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0