CaioT
CaioT

Reputation: 2211

Cloud Function always using default service account (Terraform)

I am creating a cloud function resource with Terraform and wanted to overwrite the default service account '@appspot.gserviceaccount.com' to use a custom service account with least privileges.

I've done the following but once my Terraform resources are created and I check the cloud function permissions tab, it's still defaulting to the original one '@appspot.gserviceaccount.com'

resource "google_service_account" "service_account" {
  account_id   = "mysa"
  display_name = "Service Account"
}

data "google_iam_policy" "cfunction_iam" {
  binding {
    role = google_project_iam_custom_role.cfunction_role.id
    members = [
      "serviceAccount:${google_service_account.service_account.email}",
    ]
  }
  binding {
    role = "roles/cloudfunctions.developer"
    members = [
      "serviceAccount:${google_service_account.service_account.email}",
    ]
  }
}

resource "google_cloudfunctions_function_iam_policy" "policy" {
  project = google_cloudfunctions_function.function.project
  region = google_cloudfunctions_function.function.region
  cloud_function = google_cloudfunctions_function.function.name
  policy_data = data.google_iam_policy.cfunction_iam.policy_data
}

resource "google_project_iam_custom_role" "cfunction_role" {
    role_id = "customCFunctionRole"
    title = "Custom Cloud Function Role"
    description = "More granular permissions other than default @appspot SA"
    permissions = [
      "storage.objects.create", 
      "storage.multipartUploads.create",
      "storage.objects.get",
      "bigquery.tables.create",
      "bigquery.tables.list",
      "bigquery.tables.updateData",
      "logging.logEntries.create",
    ]
}

@Update, I've set the service account parameter within the Cloud Function resource as well:

service_account_email = "${google_service_account.service_account.email}"

What am I missing here?

Thanks!

Upvotes: 1

Views: 2100

Answers (1)

CaioT
CaioT

Reputation: 2211

Adding my own answer here. After deleting the previous state and let Terraform re-create all the resources, it picked up the correct service account as defined in the description.

Upvotes: 1

Related Questions