📘

Terraformで認証なしのCloud Runリソースを作成する

2023/08/03に公開

目的

この記事では、Terraformで認証なしのCloud Runリソースを作成します。

手順

terraform initの実行

terraform init
Terraform has made some changes to the provider dependency selections recorded
in the .terraform.lock.hcl file. Review those changes and commit them to your
version control system if they represent changes you intended to make.

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

main.tfの作成

google_cloud_run_serviceにて、リソースを作成します。

ここでは、以下でArtifact RegistryへデプロイしたイメージをCloud Runで起動するイメージとして指定します。

https://zenn.dev/tossy21/articles/a04412b21164ae#作成したコンテナをartifact-registryへpushします

terraform {
  required_version = ">= 1.2.7"
}

provider "google" {
  project = "${PROJECT_ID}"
  region  = "us-central1"
  zone    = "us-central1-c"
}


resource "google_cloud_run_service" "cloud_run_instance" {
  name     = "cloud-run-instance"
  location = "us-central1"

  template {
    spec {
      containers {
        image = "asia-northeast1-docker.pkg.dev/${PROJECT_ID}/cloudrun-handson/sumservice:v1"
      }
    }
  }

}

data "google_iam_policy" "noauth" {
  binding {
    role = "roles/run.invoker"
    members = [
      "allUsers",
    ]
  }
}

resource "google_cloud_run_service_iam_policy" "noauth" {
  location = google_cloud_run_service.cloud_run_instance.location
  project  = google_cloud_run_service.cloud_run_instance.project
  service  = google_cloud_run_service.cloud_run_instance.name

  policy_data = data.google_iam_policy.noauth.policy_data
}

https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_service#example-usage---cloud-run-service-noauth

デプロイ

terraform planで作成されるリソースについて確認します。

terraform plan
data.google_iam_policy.noauth: Reading...
data.google_iam_policy.noauth: Read complete after 0s [id=xxxxxxxxxx]

Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # google_cloud_run_service.cloud_run_instance will be created
  + resource "google_cloud_run_service" "cloud_run_instance" {
      + autogenerate_revision_name = false
      + id                         = (known after apply)
      + location                   = "us-central1"
      + name                       = "cloud-run-instance"
      + project                    = (known after apply)
      + status                     = (known after apply)

      + metadata {
          + annotations      = (known after apply)
          + generation       = (known after apply)
          + labels           = (known after apply)
          + namespace        = (known after apply)
          + resource_version = (known after apply)
          + self_link        = (known after apply)
          + uid              = (known after apply)
        }

      + template {
          + metadata {
              + annotations      = (known after apply)
              + generation       = (known after apply)
              + labels           = (known after apply)
              + name             = (known after apply)
              + namespace        = (known after apply)
              + resource_version = (known after apply)
              + self_link        = (known after apply)
              + uid              = (known after apply)
            }

          + spec {
              + container_concurrency = (known after apply)
              + service_account_name  = (known after apply)
              + serving_state         = (known after apply)
              + timeout_seconds       = (known after apply)

              + containers {
                  + image = "asia-northeast1-docker.pkg.dev/${PROJECT_ID}/cloudrun-handson/sumservice:v1"
                  + name  = (known after apply)

                  + ports {
                      + container_port = (known after apply)
                      + name           = (known after apply)
                      + protocol       = (known after apply)
                    }

                  + resources {
                      + limits   = (known after apply)
                      + requests = (known after apply)
                    }

                  + startup_probe {
                      + failure_threshold     = (known after apply)
                      + initial_delay_seconds = (known after apply)
                      + period_seconds        = (known after apply)
                      + timeout_seconds       = (known after apply)

                      + grpc {
                          + port    = (known after apply)
                          + service = (known after apply)
                        }

                      + http_get {
                          + path = (known after apply)
                          + port = (known after apply)

                          + http_headers {
                              + name  = (known after apply)
                              + value = (known after apply)
                            }
                        }

                      + tcp_socket {
                          + port = (known after apply)
                        }
                    }
                }
            }
        }

      + traffic {
          + latest_revision = (known after apply)
          + percent         = (known after apply)
          + revision_name   = (known after apply)
          + tag             = (known after apply)
          + url             = (known after apply)
        }
    }

  # google_cloud_run_service_iam_policy.noauth will be created
  + resource "google_cloud_run_service_iam_policy" "noauth" {
      + etag        = (known after apply)
      + id          = (known after apply)
      + location    = "us-central1"
      + policy_data = jsonencode(
            {
              + bindings = [
                  + {
                      + members = [
                          + "allUsers",
                        ]
                      + role    = "roles/run.invoker"
                    },
                ]
            }
        )
      + project     = (known after apply)
      + service     = "cloud-run-instance"
    }

Plan: 2 to add, 0 to change, 0 to destroy.

確認したら、terraform applyでデプロイします。

terraform apply

yesを入力し、エンターを押下します。

...

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: 
google_cloud_run_service.cloud_run_instance: Creating...
google_cloud_run_service.cloud_run_instance: Still creating... [10s elapsed]
google_cloud_run_service.cloud_run_instance: Creation complete after 13s [id=locations/us-central1/namespaces/${PROJECT_ID}/services/cloud-run-instance]
google_cloud_run_service_iam_policy.noauth: Creating...
google_cloud_run_service_iam_policy.noauth: Creation complete after 1s [id=v1/projects/${PROJECT_ID}/locations/us-central1/services/cloud-run-instance]

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

Cloud Runリソースが作成されたことを確認します。

gcloud run services list

   SERVICE             REGION       URL                                                 LAST DEPLOYED BY         LAST DEPLOYED AT
✔  cloud-run-instance  us-central1  https://cloud-run-instance-xxxxxxxxx-uc.a.run.app  xxxxxxxxxxxxxxxxx  2023-08-03T00:42:43.164510Z

サービスが起動していることを確認します。

 curl -s -H "Content-Type: application/json" -d '{"numbers": [10, 20, 30, 300, 100]}' https://cloud-run-instance-xxxxxxxxx-uc.a.run.app/sum | jq
{
  "sum": 460
}

確認後は、リソースを削除します。

terraform destroy

まとめ

この記事では、Terraformで認証なしのCloud Runリソースを作成しました。

GitHubで編集を提案

Discussion