'Cannot change storage transfer service account permissions from terraform

I am trying to launch a google storage transfer service using url list from a cloudfunction.

For that I need the storage transfer service account to have the following permissions (following the google documentation here). For that, my IAC is the following:

main.tf

provider "google" {
  project = var.project
  region  = var.region
  zone    = var.zone
}

locals {
  storage_transfer_service_account = "project-${var.project}@storage-transfer-service.iam.gserviceaccount.com"
}

resource "google_project_service" "storage_transfer_api" {
  project            = var.project
  service            = "storagetransfer.googleapis.com"
  disable_on_destroy = true
}

# For the storage transfer service account
resource "google_project_iam_member" "legacy_bucket_writer" {
  project = var.project
  role    = "roles/storage.legacyBucketWriter"
  member  = "serviceAccount:${local.storage_transfer_service_account}"
}

resource "google_project_iam_member" "object_viewer" {
  project = var.project
  role    = "roles/storage.objectViewer"
  member  = "serviceAccount:${local.storage_transfer_service_account}"
}

But when I run my terraform plan I get the following error:

tf.plan : var.project is a string, known only after apply
tf.plan : Can't access attributes on a primitive-typed value (string).

I understand the project variable is not set yet during plan, but how can I grant the necessary permission to the service account ?



Solution 1:[1]

Couple of comments about terraform code only:

  1. There is a special terraform data resource - google_storage_transfer_project_service_account - it might be useful to utilize it. It might look something like (var.project means the project ID):

    data "google_storage_transfer_project_service_account" "st_service_account" {
      project = var.project
    }
    
  2. Terraform tries to run a lot API commands asynchronously. At the same time some resources may be dependent on others. Sometimes it is possible to infer those dependencies and sometimes there is not enough information in terraform source files. In the alter case a depends_on meta-argument can be used. There is a piece of code (in your terraform) used to enable a Storage Transfer API. It takes time. From the best of my understanding, the storage transfer service account is created during that API enabling. And until the service account is created, it is not possible to get its details and assign additional IAM roles for it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 al-dann