Search code examples
google-cloud-platformterraformgoogle-cloud-pubsubterraform-provider-gcp

How can I attach a policy to a resource (in this case a PubSub topic)?


resource "google_pubsub_topic" "topic" {
  name   = "argo-events"
}

resource "google_service_account" "argo_events_pubsub_publish" {
  account_id   = "pubsub-publish"
}

resource "google_project_iam_member" "argo_events_pubsub_publish" {
  role   = "roles/pubsub.editor"
  member = "serviceAccount:${google_service_account.argo_events_pubsub_publish.email}"
}

This will create a service account with editor permissions on all PubSub infrastructure of the project.

How can I attach the policy (resulting from Service Account + roles/pubsub.editor) to the initially created topic?

(Such that the Service Account has permissions from roles/pubsub.editor but only on the initially created topic named "argo-events".)


The question was written under the assumption that terraform implements the policy attachment analogous to GCPs generic concept.


Solution

  • There are a couple of ways to attach a policy to a topic or a subscription. Interestingly the approach is not generic but specific to what resource you want to bind to (in this case a pubsub topic) and there are at least three ways how to do it:

    In this case a solution could look like this:

    data "google_iam_policy" "topic" {
      binding {
        role = "roles/pubsub.publisher"
        members = [
          "serviceAccount:${google_service_account.argo_events_pubsub_publish.email}",
        ]
      }
    }
    
    resource "google_pubsub_topic_iam_policy" "policy" {
      topic = google_pubsub_topic.topic.name
      policy_data = data.google_iam_policy.topic.policy_data
    }