In this tutorial we are going to use google cloud build to build an image and then deploy to cloud run.
lets create a project and add the following files in there
cloudbuild.yaml
In cloud build, every name used is a docker image step and argument are the command that we would like to run on that steps. In this case, we are using docker image to do a docker build, then we are pushing it to artefact registry using docker image too and finally we deploy our image using cloud-sdk image.
steps:
# 1. Build the container image
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', 'us-west2-docker.pkg.dev/project-xxxx/quickstart-docker-repo/hello-world-image:${_TAG}', '.']
# 2. Push it to Artifact Registry
- name: 'gcr.io/cloud-builders/docker'
args: ['push', 'us-west2-docker.pkg.dev/project-xxxxx/quickstart-docker-repo/hello-world-image:${_TAG}']
# 3. Deploy to Cloud Run
- name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
entrypoint: gcloud
args:
- 'run'
- 'deploy'
- 'hello-world'
- '--image=us-west2-docker.pkg.dev/project-xxxxxxx/quickstart-docker-repo/hello-world-image:${_TAG}'
- '--region=${_REGION}'
- '--allow-unauthenticated'
images:
- 'us-west2-docker.pkg.dev/project-xxxxxx/quickstart-docker-repo/hello-world-image:${_TAG}'
substitutions:
_REGION: us-west1
_TAG: v33
options:
logging: CLOUD_LOGGING_ONLY
Dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD exec gunicorn --bind :$PORT --workers 1 app:app
app.py
import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
requirements.txt
To get it deploy, run the following command - please note we assume that you have the artefact repository created in your project
gcloud builds submit --config=cloudbuild.yaml .
And let's say you would like to use secret in your pipeline, we can use the following example here: -
- name: 'ubuntu'
entrypoint: bash
args: ['-c', 'echo dbpassword: $$DB_PASSWORD']
secretEnv: ['DB_PASSWORD']
availableSecrets:
secretManager:
- versionName: projects/$PROJECT_ID/secrets/first-api-key/versions/latest
env: 'DB_PASSWORD'
But make sure you have granted the right role to your service account -
cloud secrets add-iam-policy-binding first-api-key --member="serviceAccount:project-id-compute@developer.gserviceaccount.com" --role="roles/secretmanager.secretAccessor"
Comments