Skip to content

Instantly share code, notes, and snippets.

@miticojo
Last active January 11, 2023 11:19
Show Gist options
  • Save miticojo/148bee975636d9c6d0116fd0e3a2412d to your computer and use it in GitHub Desktop.
Save miticojo/148bee975636d9c6d0116fd0e3a2412d to your computer and use it in GitHub Desktop.
GCP: setup Pub Sub Cloud Build Trigger across Project

Step by step procedure

If you need to setup a cross project trigger from Cloud Source Repository (aka CSR) to Cloud Build (aka CB), one way could be this one:

Setup env variables used

# this is the project containing the Cloud Source Repository
export PROJECT_CSR=my-csr-project
export CSR_REPO_NAME=my-repo
# this is the project running Cloud Build Job
export PROJECT_CB=my-cb-project

Create a Cloud Pub Sub Topic inside the same repository where is hosted your CSR repo

gcloud pubsub topics create projects/$PROJECT_CSR/topics/$CSR_REPO_NAME

Update your CSR repo to send update to that topic

gcloud source repos update $CSR_REPO_NAME --add-topic=$CSR_REPO_NAME

Collect Cloud Build Agent service account

Note: the CB service need to be already enabled on the project otherwise the service account will not be present

CB_SA=$(gcloud projects get-iam-policy $PROJECT_CB --flatten="bindings[].members"   --filter='bindings.members:*@gcp-sa-cloudbuild.iam.gserviceaccount.com' --filter='bindings.role:roles/cloudbuild.serviceAgent' --format='value(bindings.members)')

now you should have the variable '$CB_SA' with the name of the CB service account agent present.

Grant roles/pubsub.subscriber to CB Service Account on CSR Project

this is needed to allow CB to subscribe the topic where CSR will push notifications

gcloud projects add-iam-policy-binding $PROJECT_CSR \
  --member serviceAccount:$CB_SA \
  --role=roles/pubsub.subscriber

Grant roles/source.reader to CB Service Account on CSR Project

this is needed to allow CB to pull code from the target repository

gcloud projects add-iam-policy-binding $PROJECT_CSR \
  --member serviceAccount:$CB_SA \
  --role=roles/source.reader

Create the Cloud Build Trigger based on Pub Sub topic

In this example I'm using inline config file (cloudbuild-test.yaml) but you should adapt it based on your target.

gcloud builds triggers create pubsub \
  --name=$CSR_REPO_NAME \
  --topic=projects/$PROJECT_CSR/topics/$CSR_REPO_NAME \
  --region=global \
  --inline-config=./cloudbuild-test.yaml \
  --repo=https://source.developers.google.com/p/$PROJECT_CSR/r/$CSR_REPO_NAME \
  --repo-type=CLOUD_SOURCE_REPOSITORIES \
  --branch=master

Ready to go!

Now you should be able to trigger a CB job on a code change pushed on the CSR repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment