2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

今あるGCP環境をTerraform化するときにやったことメモ

Last updated at Posted at 2022-02-17

前提

  • terraform 初心者

背景

  • 今あるGCP環境をTerraform化したい
  • 環境は以下のような感じ

やったこと

terraformer

  • terraformer というツールを使うと、既存のGCP環境をtfファイルに落としてくれるらしいので、これを使った
  • 結論からいうと非常に役立った。ただ、複数環境構築などをしたい場合、インポートしたそのままでは使えないので、環境依存の項目値は適宜variablesに切り出す、などが必要だった。
  • あと、cloud runなどは一部対応していないサービスもあった

terraform import

  • terraformerが対応していないものは、terraformコマンドで、terraform importというものがあるのでこれを使用した
  • ただしこれはtfファイルではなく、tfstateファイルを吐き出すので、そのままでは使えない
  • 参考にするだけ

state管理どうするか

  • 調べた感じ以下のようなパターンがあった
    • GitLab Managed
    • Terraform Cloud
    • GCS
    • Git
  • Terraform Cloudが一番とりあえず楽そうな感じだったので、それを採用

ディレクトリ構成

  • 以下のような構成にした(ちょっとぼかしてます)。調査したがおおむねの構成はみんな似てるものの、最適解はチーム毎に違いそうということなので、対象のサービスでやりやすい単位で組むのがよさそう
envs
  - develop
  - staging
  - production
modules
  - loadbalancer
  - api
  - gcs
    - bucket1
    - bucket2
  - iam
  • envsの配下が環境毎に分かれていれば、terraform cloud側でワークスペースを分けて管理できて便利

実際の落とし込み

  • ひたすらちまちまtfコードかいて、少しずつ動作確認して・・を繰り返していく
  • terraformerなどを使用したとはいえ、かなり地道で時間がかかった

その他

terraformのバージョンとproviderのバージョンは別である

  • terraformが最新のバージョンだったので、自分は最新版でterraformしてるつもりだったが、providerが古かった。現時点(2022/01/28)の最新版である4.8.0にした。tfファイルを修正してから、terraform init -upgrade することで解消。
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "4.8.0" # 3.5.0になってたのを修正
    }
  }
}
terraform init -upgrade

gcpのロードバランサをどう書くかわからない

  • 調べてみると、複数のサービスに分かれているとのこと
  • このあたりが関係してくる。iamあたり絡めるともっといろいろ設定があるかも。
    • google_compute_backend_bucket
    • google_compute_backend_service
    • google_compute_global_address
    • google_compute_global_forwarding_rule
    • google_compute_target_https_proxy
    • google_compute_target_http_proxy
    • google_compute_url_map
    • google_compute_region_network_endpoint_group

terraformでどこまでできるのか

  • gcpプロジェクト作成とかもできるので、ほぼなんでもできる
  • ただterraformの権限がデカくなりすぎるので、けっこう怖い
    • iam全部消すとかもできちゃうし、他のプロジェクト消すとかもできそう。

gcloudとの分担

  • terraform用のサービスアカウントというものは必ず必要になる

  • 事故を防ぐために対象プロジェクトに対してのみterraformを実行させたい

    • 誤って別プロジェクトに対して操作してしまうとか恐ろしすぎる
  • つまりgcloudコマンドは必ず実行することになる(コンソールポチポチしてもいいけど)

    • あとAPIの有効化周りはterraformではちょっとやりづらい
  • gcloudのスクリプトで最初のプロジェクト作成と、terraform用のサービスアカウント作成、APIの有効化をやらせることにした

感想

  • 結構大変だったけど、GCP環境が全部コード化されて管理下におかれるのはなんか楽しさがある
  • アプリばかり開発してきたけど、こういうのはわりと面白いなと感じた
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?