created: 2022-06-05T02:49:08.646Z

GCP の Cloud Storage で公開用のバケットを用意する

公式ドキュメントによるとこんな按配。

resource "google_storage_bucket" "public_myapp_file" {
  name          = "public-myapp-file"
  storage_class = "STANDARD"
}

resource "google_storage_bucket_access_control" "public_rule" {
  bucket = google_storage_bucket.public_myapp_file.name
  role   = "READER"
  entity = "allUsers"
}

しかし、公式ドキュメントの通りだと 公開 URL のURLでは閲覧できず、 認証済み URL でのみアクセス可能になってしまう。

google_storage_bucket_iam_binding を利用する方法にすると公開 URL のURLで閲覧できた。

resource "google_storage_bucket_iam_binding" "public_myapp_file_iam_binding" {
  bucket = google_storage_bucket.public_myapp_file.name
  members = [
    "allUsers",
  ]
  # [Cloud Storageでファイルは公開 & 一覧ページは非公開にする権限設定](https://zenn.dev/catnose99/articles/18720e3af36d22)
  role = "roles/storage.legacyObjectReader"
}

website

アクセスされたパスに応じて index.html を返したり、404.html を返したりする場合は以下の設定。

  website {
    main_page_suffix = "index.html"
    not_found_page   = "404.html"
  }

cors

cors の制御が必要な場合も設定できる。

  cors {
    origin          = ["http://image-store.com"]
    method          = ["GET", "HEAD", "PUT", "POST", "DELETE"]
    response_header = ["*"]
    max_age_seconds = 3600
  }

アクセスログ

アクセスログも保持できる。

参考

子育てブレスト: その手があったか!67のなるほど育児アイデア集
[ad] 子育てブレスト: その手があったか!67のなるほど育児アイデア集
佐藤 ねじ, 佐藤 蕗 (単行本)