Skip to content

IAM

IAM, or Identity and Access Management is GCP's management tool for access control

In this exercise you will learn how to import dynamically data from GCP using Terraform and create resource with policy attachment to allow access to the previously created Cloud Run service. Let's get started!

Exercises

  1. Create a data source google_iam_policy using the data block type with the name noauth
  2. Create an IAM binding allowing access our Cloud Run service, by setting parameters to google_iam_policy
    • Provide the binding parameter to google_iam_policy.
    • Set role to be roles/run.invoker.
    • Set members to be a list with the sole member being "allUsers"
  3. Utilize the output from the data source, and your service to create a google_cloud_run_service_iam_policy resource
    • location = google_cloud_run_service.default.location
    • project = google_cloud_run_service.default.project
    • service = google_cloud_run_service.default.name
    • policy_data= data.google_iam_policy.noauth.policy_data

Extra

  1. Add a variable called cloud_run_public which is a boolean
    • Use it to control whether the service is exposed to "allUsers" or not
    • Hint: Use a ternary operator on the members list and default to "[]", "serviceAccount:" or "user:"
    • If you change from "allUsers" to any other option, it might take a while to be applied on GCP. Wait a bit, and try again in incognito mode for example! :)

Check your changes

Usually, even though terraform apply does show you the plan, you iterate on things by running terraform plan before applying anything:

terraform plan

Apply your changes

Now you are ready to apply everything!

terraform apply

Again, will show you the resources that Terraform will create, delete or change.

Notice that the previously created Cloud Run service should not change, as the its state matches the desired one. Also, the data source does not actually manage a resource so you should see only the google_cloud_run_service_iam_policy to be added.

Check that every resource looks OK, and write yes to apply the changes.

This time, the URL in the output should be accessible!


Answer

cloud_run.tf

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.default.location
  project  = google_cloud_run_service.default.project
  service  = google_cloud_run_service.default.name

  policy_data = data.google_iam_policy.noauth.policy_data
}

Next

Next, we create a separate service with Compute Engine.