You can use Cloud Build to automate builds and deployments to Cloud Run.
You can accomplish this using a Cloud Build trigger to automatically build and deploy your code whenever new commits are pushed to a given branch of a git repository. This includes Cloud Source Repositories, GitHub, or any other repository supported by Cloud Build.
The build trigger does the following:
- Builds the Docker Image
- Pushes the image to the Container Registry
- Deploys a new revision to the Cloud Run service
Setting up continuous deployment with Cloud Build
To automate deployment with Cloud Build:
In your repository root, add a file named
cloudbuild.yamlthat has these entries:
steps: # build the container image - name: 'gcr.io/cloud-builders/docker' args: ['build', '-t', 'gcr.io/$PROJECT_ID/[SERVICE-NAME]', '.'] # push the container image to Container Registry - name: 'gcr.io/cloud-builders/docker' args: ['push', 'gcr.io/$PROJECT_ID/[SERVICE-NAME]'] # Deploy container image to Cloud Run - name: 'gcr.io/cloud-builders/gcloud' args: ['beta', 'run', 'deploy', '[SERVICE-NAME]', '--image', 'gcr.io/$PROJECT_ID/[SERVICE-NAME]', '--region', '[REGION]','--platform', '[PLATFORM]', '--quiet'] images: - gcr.io/$PROJECT_ID/[SERVICE-NAME]
- [PLATFORM] with
managedif deploying to fully managed Cloud Run, or with
gkeif deploying to Cloud Run on GKE.
- [SERVICE-NAME] with the name of the Cloud Run service.
- [REGION] with the region of the Cloud Run service
you are deploying to. If you are using Cloud Run on GKE, use
--cluster-locationinstead of the
- [PLATFORM] with
Grant the Cloud Run Admin and Service Account User roles to the Cloud Build service account:
Open the Cloud Build settings page in the GCP Console:
In the Service account permissions panel, set the status of the Cloud Run Admin role to Enable:
Select GRANT ACCESS TO ALL SERVICE ACCOUNTS to grant the Service Account User role on all service accounts in the project on your page.
Click Triggers in the left navigation panel to open the Triggers page:
Click Create Trigger.
select your repository from the displayed repository list, and click Continue.
For more information on specifying which branches to autobuild, see Creating a build trigger.
cloudbuild.yamlin Build Configuration.
You are finished! From now on, whenever you push to your repository, a build and a deployment to your Cloud Run service is automatically triggered.
Continuous deployment with minimal IAM permissions
When a container is deployed to a Cloud Run service, it runs with the identity of the Runtime Service Account of this Cloud Run service. Because Cloud Build can deploy new containers automatically, Cloud Build needs to be able to act as the Runtime Service Account of your Cloud Run service.
Instead of allowing Cloud Build to act as any service account, you can allow it to only "act as" your Cloud Run Runtime Service account. Follow the instructions to deploy artifacts to Cloud Build to set up least-privilege deployment.