12
votes

Let's say I have project A, B and C in Google Cloud with several cloud functions in each one.

I want to setup a Pub/Sub in project C so the functions in A and B can subscribe to.

Is this possible? Do I need to setup some kind of service account with custom permissions?

Thanks

2
As far as I know the PubSub topic must be in the same project as the Cloud Functions that it triggers. But you could publish to that topic from other projects.Frank van Puffelen
To send push notifications to functions in other projects I think its possible as it is a simple HTTP request from the Pub/Sub server. But to publish from other functions is something that I'm not sure aboutmartosoler
I cannot answer for Google Cloud Functions specifically, but I have a PubSub in one project that I access (both to publish and subscribe) from apps on Google Cloud Kubernetes Engine in a different project. GOOGLE_APPLICATION_CREDENTIALS simply has to point to the certificate of a service account with access to the PubSub in the correct project.ZackK
@FrankvanPuffelen could you post your comment as an answer? Thank you.komarkovich
I'm actually not sure I am correct. @ZackK seems to indicate that it is possible to call PubSub across projects, which is a better answer for what OP is asking.Frank van Puffelen

2 Answers

9
votes

In the subscribing project on the IAM page, add a new member with the Pub/Sub Publisher role, the new member name is the serviceaccount-email of from the publishing project. Then create a cloud function in the publishing project and assign the same service-account in the bottom of the page(under more) to the function.

Here's a node example for a cloud function:

const PubSub = require('@google-cloud/pubsub');
const pubsub = new PubSub();
const topic = pubsub.topic('projects/subscribing-project-name/topics/topic-to- 
publish-to');
const publisher = topic.publisher();

exports.helloWorld = (req, res) => {
const customAttributes = {
message: 'Hello'
};
publisher.publish(Buffer.from("Hello from another project"), customAttributes, 
(err) => {
if (err) {
  res.status(500).send(JSON.stringify({ success: false, error: err.message }));
  return;
}
res.status(200).send(JSON.stringify({ success: true, message: "Message sent to 
pubsub topic" }));
});
};
2
votes

As you mentioned in the comment, you can subscribe to the topic from another Cloud Functions if you set a push subscription.

To publish to a Pub/Sub topic from another project you should grant the right permissions for it's service account in the destination project.