Search code examples
terraformgoogle-cloud-functionsgoogle-cloud-pubsub

Run cloud function on pubsub message arrival using Terraform


Requirement

Need to create Terraform IAC to run cloud function on pubsub event_trigger. I don't need to create the pubsub resources in my iac because it was created by other team.

My try 1

  event_trigger {
      event_type    = "google.pubsub.topic.publish"
      resource   = "project/${var.project_id}/topics/${var.environment}_my_topic"
  }

error on try1

│ Error: googleapi: Error 400: The request has errors
│ Details:
│ [
│   {
│     "@type": "type.googleapis.com/google.rpc.BadRequest",
│     "fieldViolations": [
│       {
│         "description": "Pub/Sub topic name projects/myprojectID/topics/project/myprojectID/topics/my_topic does not match the expected pattern",
│         "field": "pubsub_topic"
│       }
│     ]
│   }
│ ]
│ , badRequest

My try 2

  event_trigger {
      event_type    = "google.pubsub.topic.publish"
      resource = {
        service = "pubsub.googleapis.com"
        name = "project/${var.project_id}/topics/${var.environment}_my_topic"
        type = "type.googleapis.com/google.pubsub.v1.PubsubMessage"
        }
  }

error on try2

│     │ var.environment is a string, known only after apply
│     │ var.project_id is a string, known only after apply
│ 
│ Inappropriate value for attribute "resource": string required.

Please help


Solution

  • I have corrected the resource path.

    It should be starting with projects/...

    My try1 has been changed like this and it worked.

      event_trigger {
          event_type    = "google.pubsub.topic.publish"
          resource   = "projects/${var.project_id}/topics/${var.environment}_my_topic"
      }