How to automatically deploy your changes from version control to Cloud Run

1. Overview

This Codelab will demonstrate how to configure Cloud Run to automatically deploy new versions of your application when a change is made to the source code repository of your application. This will allow you to avoid the additional steps of manually building and deploying your application every time you want to deploy a new version.

What you will learn

In this lab, you will learn how to do the following:

  • Write a Python application with Cloud Shell Editor
  • Store your application code using version control
  • Automatically deploy your application to Cloud Run

Prerequisites

  • This lab assumes familiarity with the Cloud Console and Cloud Shell environments.

2. Before you begin

Cloud Project setup

  1. Sign-in to the Google Cloud Console and create a new project or reuse an existing one. If you don't already have a Google account, you must create one.b35bf95b8bf3d5d8.pnga99b7ace416376c4.pngbd84a6d3004737c5.png
    • The Project name is the display name for this project. It is a character string not used by Google APIs. You can update it at any time.
    • The Project ID is unique across all Google Cloud projects and is immutable (cannot be changed after it has been set). The Cloud Console auto-generates a unique string; usually you don't care what it is. In most codelabs, you'll need to reference the Project ID (it is typically identified as PROJECT_ID). If you don't like the generated ID, you may generate another random one. Alternatively, you can try your own and see if it's available. It cannot be changed after this step and will remain for the duration of the project.
    • For your information, there is a third value, a Project Number which some APIs use. Learn more about all three of these values in the documentation.
  2. Next, you'll need to enable billing in the Cloud Console to use Cloud resources/APIs. Running through this codelab shouldn't cost much, if anything at all. To shut down resources so you don't incur billing beyond this tutorial, you can delete the resources you created or delete the whole project. New users of Google Cloud are eligible for the $300 USD Free Trial program.

Environment Setup

Activate Cloud Shell by clicking on the icon to the right of the search bar.

ecdc43ada29e91b.png

From Cloud Shell, enable the APIs:

gcloud services enable sourcerepo.googleapis.com \
  run.googleapis.com cloudbuild.googleapis.com

If prompted to authorize, click "Authorize" to continue.

6356559df3eccdda.png

This command may take a few minutes to complete, but it should eventually produce a successful message similar to this one:

Operation "operations/acf.p2-327036483151-73d90d00-47ee-447a-b600-a6badf0eceae" finished successfully.

3. Write the application

To write an application in Python:

  1. Create a new directory named helloworld and change directory into it:
    mkdir helloworld
    cd helloworld
    
  2. Create a file named main.py and paste the following code into it:
    import os
    
    from flask import Flask
    
    app = Flask(__name__)
    
    app_version = "0.0.0"
    
    @app.route("/")
    def hello_world():
        return f"Hello! This is version {app_version} of my application."
    
    
    if __name__ == "__main__":
        app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
    
    This code responds to requests with our "Hello! This is version 0.0.0 of my application." greeting.
  3. Create a file named requirements.txt and paste the following code into it:
    Flask==3.0.0
    gunicorn==20.1.0
    
    This adds packages needed by the sample.

Your initial code for your application is finished and ready to be stored in version control.

4. Create a repository

In a Cloud Shell terminal window, initialize your project as a git repository with main as the default branch name.

git init
git branch -M main

Make your first commit

git add .
git commit -m "first commit for python application"

Use the gcloud source repos create command to create a Google Cloud repository named hello-world:

gcloud source repos create hello-world

Provide your authentication credentials

git config credential.https://source.developers.google.com.helper gcloud.sh

Add the Google Cloud Source Repositories repository as a remote

git remote add origin \
    https://source.developers.google.com/p/${GOOGLE_CLOUD_PROJECT}/r/hello-world

Push your commit to the repository.

git push -u origin main

Visit Cloud Source Repository to view your code. Run this command and visit the resulting URL:

echo -e "\n\nTo see your code, visit this URL:\nhttps://source.cloud.google.com/${GOOGLE_CLOUD_PROJECT}/hello-world/+/main:main.py"

5. Set up automatic deployments

https://console.cloud.google.com/run

  1. Click Create a Service
  2. Click Continuously deploy new revisions from a source repository
  3. Click the SET UP CLOUD BUILD button.
    1. Select Cloud Source Repositories as the Repository Provider
    2. Select hello-world as the Repository
    3. Leave Branch as ^main$
    4. Click Go, Node.js, Python, Java, .NET Core, Ruby or PHP via Google Cloud's buildpacks
    5. Leave Build context directory as /
    6. Click Save
  4. Scroll down to Authentication
  5. Click Allow unauthenticated invocations
  6. Click CREATE

After a few minutes, a custom URL (like https://hello-world-XXXXXXXXXX-uc.a.run.app) will be generated.

Click the link after the application is built.

6. Make a change and redeploy

Return to Cloud Shell Editor

Change 0.0.0 in main.py to 0.0.1.

app_version = "0.0.1"

Push the changes to Cloud Source Repositories

git add .
git commit -m "update version to 0.0.1"
git push

After a few minutes, the latest version will be deployed to the url from the previous step (like https://hello-world-XXXXXXXXXX-uc.a.run.app).

You can see the history of all revisions here:

https://console.cloud.google.com/run/detail/us-central1/hello-world/revisions

7. Clean up

While Cloud Run does not charge when the service is not in use, you might still be charged for storing the container image in Artifact Registry. You can delete your Cloud project to avoid incurring charges. Deleting your Cloud project stops billing for all the resources used within that project.

To delete your Google Cloud project,

  1. Retrieve your current project ID:
    PROJECT_ID=$(gcloud config get-value core/project)
    
  2. Make sure this is the project you wish to delete:
    echo $PROJECT_ID
    
  3. Delete the project:
    gcloud projects delete $PROJECT_ID