LoginSignup
19

More than 5 years have passed since last update.

TerraformでGCPのIAMをちょっとだけ上手に管理する

Last updated at Posted at 2019-01-10

背景

権限を付与する google_project_iam_member のリソースの role が配列を持てないので、複数の role を一度に設定することができません。
したがって、複数の role をあるアカウントに付与するためにはツラツラ書く必要があって、少し辛いところがあります。

old_serviceaccount.tf
# create account
resource "google_service_account" "sample_app_user" {
  account_id   = "app-mgr"
  display_name = "app-mgr"
}

# add role1
resource "google_project_iam_member" "sample_app_user_1" {
  role   = "roles/cloudsql.client"
  member = "serviceAccount:${google_service_account.sample_app_user.email}"
}

# add role2
resource "google_project_iam_member" "sample_app_user_2" {
  role   = "roles/storage.objectViewer"
  member = "serviceAccount:${google_service_account.sample_app_user.email}"
}

# add role3
resource "google_project_iam_member" "sample_app_user_3" {
  role   = "roles/bigquery.user"
  member = "serviceAccount:${google_service_account.sample_app_user.email}"
}

# add roleN(このペースで追加するのは辛い..)
# ...

対応

Terraformの count 機能を導入することで上手く構造化が可能です。
count に別途変数で切った配列長を設定し、 count.index で配列アクセスすることで動的に展開して実行してくれます。
role を編集したいときは、 sample_app_roles の値を編集すればOK。

new_serviceaccount.tf
# create account(ここは変化せず)
resource "google_service_account" "sample_app_user" {
  account_id   = "app-mgr"
  display_name = "app-mgr"
}

# add roles(countとリストアクセスを活用)
resource "google_project_iam_member" "sample_app_user" {
  count = "${length(var.sample_app_roles)}"
  role   = "${element(var.sample_app_roles, count.index)}"
  member = "serviceAccount:${google_service_account.sample_app_user.email}"
}

# 別途変数化
variable "sample_app_roles" {
  default = [
    "roles/cloudsql.client",
    "roles/storage.objectViewer",
    "roles/bigquery.user",
    "..."
  ]
}

variableを別ファイルで管理すれば、メンテナンス性やレビュー上もお得にできそうです。

まとめ

  • Terraformのcount機能は強力

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
19