Deploying a Google Translate App on Cloud Run Using Cloud Build

Effortless Deployment of a Multilingual Translation App on Google Cloud Run with Cloud Build

Deploying a Google Translate App on Cloud Run Using Cloud Build

Introduction:

As cloud engineers, automation is fundamental to our workflow. In this blog post, we will guide you through the process of automating the deployment of a Google Translate Flask application on Google Cloud Run using Cloud Build. We will cover the step-by-step implementation of provisioning the necessary resources, setting up the CI/CD pipeline, and achieving a seamless and efficient deployment process.

Prerequisites:

Before we dive into the technical details, ensure that you have the following prerequisites in place:

  1. Google Cloud Platform (GCP) Account: You'll need an GCP account with appropriate permissions to create resources like Google Cloud Build and Cloud Run services.

  2. GitHub Account: Have a GitHub account with a repository set up to manage your Google Translate Flask application and Cloud Build configurations.

Repo Structure:

To maintain an organized project structure, we'll follow this directory structure within our GitHub repository: GitHub-Repository

You can clone the sample repository for reference GitHub-Repository

Code Overview:

Dockerfile:

This file defines the Docker image for your Google Translate Flask application. It sets the Python version, creates a directory for your app, installs Python dependencies from requirements.txt, copies your source code into the container, exposes a port, and runs your Flask app using Gunicorn.

FROM python:2-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
ENTRYPOINT ["python", "main.py"]

cloudbuild.yaml:

This Cloud Build configuration file defines the steps for building and deploying your Docker image to Google Cloud Run. It uses Docker to build the image and push it to Google Container Registry (GCR). Then, it deploys the image to Cloud Run with specific settings like service name, image location, region, and allowing unauthenticated access.

steps:
# This step will build and push new container image to "google container registry(GCR)"
- name: 'gcr.io/cloud-builders/docker'
  args: ['build', '-t', 'gcr.io/$PROJECT_ID/google-translate-app', '.']
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'gcr.io/$PROJECT_ID/google-translate-app']

# This step will deploy the new container image to cloud run
- name: 'gcr.io/cloud-builders/gcloud'
  args: ['run','deploy', 'google-translate-app-service', '--image=gcr.io/$PROJECT_ID/google-translate-app', '--region=us-central1', '--allow-unauthenticated']

main.py:

This is the main Python script for your Google Translate Flask application. It defines a Flask app with a single route that translates text. It interacts with the Google Cloud Translate API.

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from flask import Flask, render_template, request
import google.auth
from google.cloud import translate

app = Flask(__name__)
_, PROJECT_ID = google.auth.default()
TRANSLATE = translate.TranslationServiceClient()
PARENT = 'projects/{}'.format(PROJECT_ID)
SOURCE, TARGET = ('en', 'English'), ('hi', 'Hindi') #change your source & Target language as per your choice

@app.route('/', methods=['GET', 'POST'])
def translate(gcf_request=None):
    """
    main handler - show form and possibly previous translation
    """

    # Flask Request object passed in for Cloud Functions
    # (use gcf_request for GCF but flask.request otherwise)
    local_request = gcf_request if gcf_request else request

    # reset all variables (GET/POST)
    text = translated = None

    # form submission and if there is data to process (POST)
    if local_request.method == 'POST':
        text = local_request.form['text'].strip()
        if text:
            data = {
                'contents': [text],
                'parent': PARENT,
                'target_language_code': TARGET[0],
            }
            # handle older call for backwards-compatibility
            try:
                rsp = TRANSLATE.translate_text(request=data)
            except TypeError:
                rsp = TRANSLATE.translate_text(**data)
            translated = rsp.translations[0].translated_text

    # create context & render template
    context = {
        'orig':  {'text': text, 'lc': SOURCE},
        'trans': {'text': translated, 'lc': TARGET},
    }
    return render_template('index.html', **context)


if __name__ == '__main__':
    import os
    app.run(debug=True, threaded=True, host='0.0.0.0',
            port=int(os.environ.get('PORT', 8080)))

requirements.txt:

This file lists the Python packages and their versions required for your application, including Flask and the Google Cloud Translate library.

#gunicorn>=19.10.0
grpcio<1.40.0; python_version < '3.0'
flask
google-cloud-translate

Implementation Steps:

Now, let's outline the steps to automate the deployment of your Google Translate Flask application using Cloud Build and Google Cloud Run:

  1. Set Up a Google Cloud Project:

    • Create or use an existing Google Cloud Platform (GCP) project where you'll deploy your Google Translate Flask application.

  2. Enable Necessary APIs:

    • In your GCP project, enable the Cloud Build, Container Registry, and Cloud Run APIs if they are not already enabled.

  3. Create a GitHub Repository:

    • Create a new GitHub repository or use an existing one to host your Google Translate Flask application code.

  4. Create a Service Account Key:

    • Generate a service account key in JSON format in GCP with appropriate permissions for Cloud Build and Cloud Run.

  5. Add Secrets to GitHub Repository:

    • In your GitHub repository, go to "Settings" > "Secrets" and add the following secrets:

      • GCLOUD_PROJECT_ID: Your GCP project ID.

      • GOOGLE_CREDENTIALS: The content of the service account key JSON file you generated.

  6. Create a Cloud Build Trigger:

    • In GCP, set up a Cloud Build trigger linked to your GitHub repository. Configure it to use the cloudbuild.yaml file for builds.

  7. Push Code to GitHub:

    • Push your Google Translate Flask application code (including Dockerfile, cloudbuild.yaml, gunicorn.conf.py, main.py, and requirements.txt) to your GitHub repository.

  8. Automated Deployment:

    • Whenever you push changes to your GitHub repository's main branch, the Cloud Build trigger will automatically build a Docker image, push it to GCR, and deploy it to Cloud Run.

  9. Access Your Application:

    • After the deployment is successful, you can access your Google Translate Flask application on Google Cloud Run using the provided URL.

By following these implementation steps, your Google Translate Flask application will be deployed and updated automatically whenever you push changes to your GitHub repository's main branch. This provides a streamlined CI/CD pipeline for your application on Google Cloud Run.

Conclusion:

In this journey through automating Google Translate Flask application deployment using Google Cloud Run and Cloud Build, we've streamlined the process, ensuring your app runs seamlessly, scales effortlessly, and remains effortlessly manageable. With this setup, you're poised to take full advantage of the cloud's power, enabling efficient, consistent, and automated deployments. Happy automating!

References: