CareerByteCode
ByteBlogby CareerByteCode

DevOps Interview Questions Answered with Real Pipelines

What you build: proof for 14 classic DevOps interview answers on Google Cloud: Docker layers, CI that stops a bug, secrets, digests, blue/green, canary, rollback, a failed deploy, least privilege.

DevOps Interview Questions Answered with Real Pipelines

✍️ Translate this blog into Hindi, Tamil or Telugu

Most DevOps interview answers are memorised: "Docker images have layers", "use canary releases", "follow least privilege". Interviewers can tell. The strongest answer is "here is what happened when I tried it". In this lab you prove 14 classic DevOps interview answers with real commands on Google Cloud: Docker layers and caching, image size, CMD vs ENTRYPOINT, configuration, a CI pipeline that a failing test stops, secrets in CI, tags vs digests, blue/green, canary, rollback, a failed deploy, debugging a crashing container, least privilege and idempotent scripts. Every answer comes with the real output you can describe in an interview.

Who it is for: anyone preparing for DevOps, cloud or SRE interviews who wants proof, not slogans. Time: about 1.5 hours. Cost: inside free tiers for this lab (Cloud Build's free build minutes, Cloud Run, Artifact Registry and Secret Manager at lab size). We delete everything at the end.

Every command below was run for real by the CareerByteCode Team on a fresh Google Cloud project, and every output is the real result we got. Ids, digests and timings will differ on your machine.

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterβ‚Ή499Build the projects →

Part A: the plan

Interview map
Build an image, prove CI, ship safely with blue/green and canary, recover, and lock things down
#Interview questionHow we prove it
Q1What is an image layer? Why does Dockerfile order matter?Rebuild after a code change: which layers come from cache
Q2Why use slim base images?The same app on two bases, sizes compared
Q3CMD vs ENTRYPOINT?Inspect the image, pass arguments
Q4How does one image run in dev and prod?Same image, two environment variables
Q5What happens when a test fails in CI?A real bug stops the pipeline
Q6How do you keep secrets out of CI logs?A secret used in a build, never printed
Q7Why not deploy :latest?A tag moved to another image; digests do not move
Q8What is blue/green?Two revisions, the new one with a test URL and no traffic
Q9What is a canary release?10 percent of real traffic, counted
Q10How fast can you roll back?One command, timed
Q11What happens when a deploy fails?A missing image: the deploy stops, users unaffected
Q12A container crashes at start: how do you debug it?Run the same image locally with the same settings
Q13What is least privilege?A read-only account tries to change traffic
Q14What is an idempotent script?The same script twice, same result

The app is a tiny Flask service (main.py) that returns its version and a colour read from the COLOR environment variable, with two unit tests, a Dockerfile, and a cloudbuild.yaml pipeline (test, build, use a secret).

# CI pipeline: test, then build and push. If the test step fails, nothing after it runs.
steps:
- id: test
  name: python:3.12-slim
  entrypoint: bash
  args: ["-c", "pip install -q -r requirements.txt pytest 2>/dev/null && python -m pytest -q"]
- id: build
  name: gcr.io/cloud-builders/docker
  args: ["build", "-t", "us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:$_TAG", "."]
- id: secret-check
  name: bash
  entrypoint: bash
  secretEnv: ["DB_PASSWORD"]
  args: ["-c", "echo \"the build can use a secret of $${#DB_PASSWORD} characters without printing it\""]
images: ["us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:$_TAG"]
availableSecrets:
  secretManager:
  - versionName: projects/$PROJECT_ID/secrets/db-password/versions/latest
    env: DB_PASSWORD
substitutions:
  _TAG: "manual"
options:
  logging: CLOUD_LOGGING_ONLY

Make a folder ~/app with these files (the exact files from our lab), plus the cloudbuild.yaml above saved as ~/app/cloudbuild.yaml:

~/app/main.py:

# main.py: a tiny service for the interview labs. Settings come from environment variables (12-factor).
import os, sys
from flask import Flask, jsonify

VERSION = "1.0.0"
if os.environ.get("START_FAIL") == "1":          # used to show what a container that cannot start looks like
    print("startup check failed: DATABASE_URL is missing", flush=True)
    sys.exit(1)
app = Flask(__name__)


@app.get("/")
def home():
    return jsonify(version=VERSION, color=os.environ.get("COLOR", "blue"))


@app.get("/health")
def health():
    return "ok\n"


def add(a, b):
    return a + b

~/app/tests/test_main.py:

from main import app, add


def test_home():
    assert app.test_client().get("/").status_code == 200


def test_add():
    assert add(2, 3) == 5

~/app/requirements.txt:

flask==3.1.*
gunicorn==23.*

~/app/Dockerfile:

# The normal image: slim base, dependencies first (cached), code last (changes often)
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
ENV PYTHONUNBUFFERED=1
ENTRYPOINT ["gunicorn", "--bind", ":8080", "--workers", "1", "--threads", "4"]
CMD ["main:app"]

~/app/Dockerfile.full:

# The same app on the FULL Python image (for the image size question)
FROM python:3.12
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py .
ENTRYPOINT ["gunicorn", "--bind", ":8080", "--workers", "1", "--threads", "4"]
CMD ["main:app"]

Before you start

  1. A Google Cloud account (the free trial works) and a project.
  2. Open Cloud Shell (the >_ icon at the top right of the console). It has Docker, gcloud and Python. Turn on the APIs:
export PROJECT_ID="your-project-id"
gcloud config set project $PROJECT_ID
gcloud services enable cloudbuild.googleapis.com run.googleapis.com artifactregistry.googleapis.com secretmanager.googleapis.com

Part B: the lab

Setup: Docker, an image repository, a secret and a pipeline account

Why: the pipeline runs as its own service account with four roles only: push images, write logs, read secrets, read the build source. The secret db-password is made for this lab only. New roles take a little time to work everywhere, so a tiny probe build retries until the account can run builds and write logs.

# Setup: Docker on the Cloud Shell VM, an image repository, a secret, and a pipeline account with only what it needs
sudo apt-get update -qq && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq docker.io > /dev/null 2>&1 && sudo docker --version
gcloud artifacts repositories create interview --repository-format=docker --location=us-east1 2>&1 | tail -1
printf "lab-only-password-123" | gcloud secrets create db-password --data-file=- --replication-policy=automatic --format="value(name.basename())"
gcloud iam service-accounts create iv-ci-1122 --display-name="Interview lab pipeline" 2>&1 | tail -1
until gcloud iam service-accounts describe iv-ci-1122@$PROJECT_ID.iam.gserviceaccount.com > /dev/null 2>&1; do sleep 5; done
for r in roles/artifactregistry.writer roles/logging.logWriter roles/secretmanager.secretAccessor roles/storage.objectViewer; do
  until gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:iv-ci-1122@$PROJECT_ID.iam.gserviceaccount.com" --role=$r --condition=None --format="value(etag)" > /dev/null 2>&1; do sleep 5; done; echo "iv-ci-1122: $r"
done
gcloud auth configure-docker us-east1-docker.pkg.dev --quiet 2>&1 | tail -1; sudo gcloud auth configure-docker us-east1-docker.pkg.dev --quiet > /dev/null 2>&1
# New roles can take a few minutes to work. A tiny probe build retries until the account can run builds AND write logs
printf 'steps:\n- name: bash\n  args: ["-c", "echo the pipeline account works"]\noptions:\n  logging: CLOUD_LOGGING_ONLY\n' > probe.yaml
for i in $(seq 1 20); do PID_=$(gcloud builds submit --no-source --config=probe.yaml --region=us-east1 --service-account=projects/$PROJECT_ID/serviceAccounts/iv-ci-1122@$PROJECT_ID.iam.gserviceaccount.com --async --format="value(id)" 2>/dev/null); sleep 30; gcloud builds log $PID_ --region=us-east1 2>/dev/null | grep -q "pipeline account works" && break; sleep 20; done; echo "probe build: $(gcloud builds describe $PID_ --region=us-east1 --format='value(status)') and its log is readable, after $i tries"
Docker version 20.10.24+dfsg1, build 297e128
Created repository [interview].
Created version [1] of the secret [db-password].
db-password
Service account email: iv-ci-1122@your-project-id.iam.gserviceaccount.com
iv-ci-1122: roles/artifactregistry.writer
iv-ci-1122: roles/logging.logWriter
iv-ci-1122: roles/secretmanager.secretAccessor
iv-ci-1122: roles/storage.objectViewer
gcloud credential helpers already registered correctly.
probe build: SUCCESS and its log is readable, after 2 tries

Q1: layers and the build cache

Why: each Dockerfile instruction makes a layer. Docker reuses a cached layer when nothing before it changed. We build once, change one line of code, and build again.

# Q1: What is an image layer, and why does the order of Dockerfile lines matter? Build, change one line of code, build again
cd ~/app && sudo docker build -q -t app:v1 . > /dev/null && echo "first build done"
sed -i 's/VERSION = "1.0.0"/VERSION = "1.0.1"/' main.py
sudo docker build -t app:v1b . 2>&1 | grep -E "^Step|Using cache"
sudo docker history app:v1b --format "{{.Size}}\t{{.CreatedBy}}" | head -6 | cut -c1-90
sed -i 's/VERSION = "1.0.1"/VERSION = "1.0.0"/' main.py   # back to 1.0.0 for the next questions
first build done
Step 1/8 : FROM python:3.12-slim
Step 2/8 : WORKDIR /app
 ---> Using cache
Step 3/8 : COPY requirements.txt .
 ---> Using cache
Step 4/8 : RUN pip install --no-cache-dir -r requirements.txt
 ---> Using cache
Step 5/8 : COPY main.py .
Step 6/8 : ENV PYTHONUNBUFFERED=1
Step 7/8 : ENTRYPOINT ["gunicorn", "--bind", ":8080", "--workers", "1", "--threads", "4"]
Step 8/8 : CMD ["main:app"]
0B	/bin/sh -c #(nop)  CMD ["main:app"]
0B	/bin/sh -c #(nop)  ENTRYPOINT ["gunicorn" "-…
0B	/bin/sh -c #(nop)  ENV PYTHONUNBUFFERED=1
581B	/bin/sh -c #(nop) COPY file:621be3c676415412…
14.5MB	/bin/sh -c pip install --no-cache-dir -r req…
28B	/bin/sh -c #(nop) COPY file:50a4b3bd579d6bfc…

Answer: steps 2 to 4 (including the 14.5 MB pip install) say Using cache; only COPY main.py and the steps after it are rebuilt. That is why Dockerfiles copy requirements.txt and install dependencies before copying the code: code changes often, dependencies rarely. docker history shows each layer and its size.

Q2: slim images

# Q2: Why use a slim base image? The same app on python:3.12 and on python:3.12-slim
cd ~/app && sudo docker build -q -f Dockerfile.full -t app:full . > /dev/null
sudo docker images app --format "table {{.Tag}}\t{{.Size}}" | grep -E "TAG|full|^v1 "
TAG       SIZE
full      1.12GB
v1        134MB

Answer: the same app is 1.12 GB on python:3.12 and 134 MB on python:3.12-slim. Smaller images pull and start faster, cost less to store and contain fewer packages that could have security holes.

Layers and size
Only the code layer is rebuilt after a code change; the full base image is 1.12 GB, slim is 134 MB

Q3: CMD vs ENTRYPOINT

# Q3: CMD vs ENTRYPOINT. ENTRYPOINT is the program; CMD is its default arguments, and arguments you pass replace CMD
cd ~/app && sudo docker inspect app:v1 --format 'ENTRYPOINT={{json .Config.Entrypoint}}  CMD={{json .Config.Cmd}}'
sudo docker run --rm app:v1 --version
sudo docker run -d --rm --name q3 -p 8081:8080 app:v1 > /dev/null && sleep 3 && curl -s localhost:8081/ && sudo docker stop q3 > /dev/null
ENTRYPOINT=["gunicorn","--bind",":8080","--workers","1","--threads","4"]  CMD=["main:app"]
gunicorn (version 23.0.0)
{"color":"blue","version":"1.0.0"}

Answer: ENTRYPOINT is the program (gunicorn ...), CMD is its default arguments (main:app). docker run app:v1 --version replaced CMD and printed gunicorn's version; the plain docker run used the default and served the app.

Q4: one image, many environments

# Q4: How does one image run in dev and prod? Settings come from the environment, not from the image (12-factor)
sudo docker run -d --rm --name dev -p 8082:8080 -e COLOR=green app:v1 > /dev/null
sudo docker run -d --rm --name prod -p 8083:8080 -e COLOR=blue app:v1 > /dev/null
sleep 3; echo "dev:  $(curl -s localhost:8082/)"; echo "prod: $(curl -s localhost:8083/)"
sudo docker stop dev prod > /dev/null
dev:  {"color":"green","version":"1.0.0"}
prod: {"color":"blue","version":"1.0.0"}

Answer: the same image answered green and blue because the setting comes from an environment variable, not from the image (the "config" rule of the twelve-factor app). You promote one tested image from dev to prod and only change settings.

Break it: a failing test in CI (Q5)

We put a real bug in the code (add() subtracts) and run the pipeline.

# Q5: What happens when a test fails in CI? Break the code, run the pipeline: it stops at the test, no image is built
cd ~/app && sed -i 's/return a + b/return a - b/' main.py
ID=$(gcloud builds submit --config=cloudbuild.yaml --region=us-east1 --substitutions=_TAG=broken \
  --service-account=projects/$PROJECT_ID/serviceAccounts/iv-ci-1122@$PROJECT_ID.iam.gserviceaccount.com . --async --format="value(id)" 2>/dev/null)
for i in $(seq 1 90); do gcloud builds describe $ID --region=us-east1 --format="value(status)" | grep -qE "SUCCESS|FAILURE|TIMEOUT|CANCELLED" && break; sleep 10; done; sleep 20
echo "build ${ID:0:8}: $(gcloud builds describe $ID --region=us-east1 --format='value(status)')"
gcloud builds log $ID --region=us-east1 2>/dev/null | grep -E "passed|failed|assert|Starting Step|STATUS|SUCCESS|FAILURE" | sed -E 's/^Step #[0-9]+ - "[a-z-]+": //' | head -8
echo "images tagged broken: $(gcloud artifacts docker tags list us-east1-docker.pkg.dev/$PROJECT_ID/interview/app --format='value(tag)' 2>/dev/null | grep -c broken)"
build 08d2fe94: FAILURE
Starting Step #0 - "test"
=================================== FAILURES ===================================
>       assert add(2, 3) == 5
E       assert -1 == 5
FAILED tests/test_main.py::test_add - assert -1 == 5
1 failed, 1 passed in 0.17s
ERROR: build step 0 "python:3.12-slim" failed: step exited with non-zero status: 1
images tagged broken: 0

Answer: the test step failed (assert -1 == 5), so the build stopped: no image was built and nothing tagged broken exists in the registry. CI is a gate: broken code never becomes an artifact.

Fix it, and use a secret without showing it (Q6)

# Q6: Fix it and run again: test, build, push, and the secret is used without ever being printed
cd ~/app && sed -i 's/return a - b/return a + b/' main.py
ID=$(gcloud builds submit --config=cloudbuild.yaml --region=us-east1 --substitutions=_TAG=v1 \
  --service-account=projects/$PROJECT_ID/serviceAccounts/iv-ci-1122@$PROJECT_ID.iam.gserviceaccount.com . --async --format="value(id)" 2>/dev/null)
for i in $(seq 1 90); do gcloud builds describe $ID --region=us-east1 --format="value(status)" | grep -qE "SUCCESS|FAILURE|TIMEOUT|CANCELLED" && break; sleep 10; done; sleep 20
echo "build ${ID:0:8}: $(gcloud builds describe $ID --region=us-east1 --format='value(status)')"
gcloud builds log $ID --region=us-east1 2>/dev/null | grep -E "passed|secret of|Successfully built|digest:|STATUS|SUCCESS|FAILURE" | sed -E 's/^Step #[0-9]+ - "[a-z-]+": //' | head -8
build ba3e9832: SUCCESS
2 passed in 0.15s
Successfully built 4c5e3bafa4b4
the build can use a secret of 21 characters without printing it
v1: digest: sha256:3da284964c7e1d53246b6f8d63ccb536f1f2f9dbbae21954e0df1fb5cd7ee798 size: 1991

Answer: with the bug fixed, the tests pass and the image is pushed. The secret-check step reads db-password from Secret Manager through availableSecrets and only prints its length. The value never appears in the code, the pipeline file or the logs, and only the pipeline account may read it.

CI
A failing test stops the build; after the fix the build passes, pushes v1 and uses the secret without printing it

Q7: tags vs digests

# Q7: Why not deploy :latest? A tag can be moved to other content; a digest (sha256) never changes
cd ~/app && sudo docker tag app:v1 us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:latest && sudo docker push -q us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:latest > /dev/null
echo "latest -> $(gcloud artifacts docker images describe us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:latest --format='value(image_summary.digest)' | cut -c1-19)"
sed -i 's/"blue")/"latest-was-moved")/' main.py && sudo docker build -q -t app:other . > /dev/null && sudo docker tag app:other us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:latest && sudo docker push -q us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:latest > /dev/null
echo "latest -> $(gcloud artifacts docker images describe us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:latest --format='value(image_summary.digest)' | cut -c1-19)  (same tag, different image)"
echo "v1     -> $(gcloud artifacts docker images describe us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:v1 --format='value(image_summary.digest)' | cut -c1-19)"
latest -> sha256:654a6880a964
latest -> sha256:f3734358d748  (same tag, different image)
v1     -> sha256:3da284964c7e

Answer: we pushed :latest, then pushed a different image with the same tag: latest now points somewhere else. A digest (sha256:...) is the fingerprint of the image content and never changes. Deploy by a version tag you never reuse, or by digest, so "what is running" is always certain.

Q8: blue/green

Why: blue takes all traffic. green is deployed with no traffic and its own tag URL (green---...), so you can test it in production before any user sees it.

# Q8: Blue/green: deploy v1 (blue), then v2 (green) with NO traffic and its own test URL
gcloud run deploy iv-app --image=us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:v1 --region=us-east1 --allow-unauthenticated --max-instances=2 --revision-suffix=blue --quiet 2>&1 | grep -E "Service URL|serving"
gcloud run deploy iv-app --image=us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:v1 --region=us-east1 --set-env-vars=COLOR=green --revision-suffix=green --no-traffic --tag=green --quiet 2>&1 | grep -E "URL|traffic" | head -2
URL=$(gcloud run services describe iv-app --region=us-east1 --format="value(status.url)")
echo "users see: $(curl -s $URL/)"; echo "green test URL: $(curl -s $(echo $URL | sed 's#https://#https://green---#')/)"
Service [iv-app] revision [iv-app-blue] has been deployed and is serving 100 percent of traffic.
Service URL: https://iv-app-PROJECT_NUMBER.us-east1.run.app
Routing traffic.....done
Service [iv-app] revision [iv-app-green] has been deployed and is serving 0 percent of traffic.
users see: {"color":"blue","version":"1.0.0"}
green test URL: {"color":"green","version":"1.0.0"}

Q9: canary

Why: send a small share of real users to the new version and watch it. We split 90/10 and count 100 requests.

# Q9: Canary: send 10 percent of real traffic to green, and count 100 requests
gcloud run services update-traffic iv-app --region=us-east1 --to-revisions=iv-app-green=10,iv-app-blue=90 --quiet 2>&1 | grep -E "[0-9]+%" | head -2
URL=$(gcloud run services describe iv-app --region=us-east1 --format="value(status.url)")
for i in $(seq 1 100); do curl -s $URL/ | grep -o '"color":"[a-z]*"'; done | sort | uniq -c
  90% iv-app-blue
  10% iv-app-green
     89 "color":"blue"
     11 "color":"green"

Answer: about 1 in 10 requests got green, the rest blue: a canary. If errors rise, you roll back; if not, you increase the share.

🎓⭐ Recommended by CareerByteCode · Live trainingCloud & DevOps Live Cohort Internshipβ‚Ή2,360See the training →

Q10: rollback

# Q10: Rollback: green is bad, send 100 percent back to blue, and time it
URL=$(gcloud run services describe iv-app --region=us-east1 --format="value(status.url)")
S=$(date +%s); gcloud run services update-traffic iv-app --region=us-east1 --to-revisions=iv-app-blue=100 --quiet > /dev/null 2>&1; echo "rollback took $(( $(date +%s) - S )) seconds"
for i in $(seq 1 50); do curl -s $URL/ | grep -o '"color":"[a-z]*"'; done | sort | uniq -c
rollback took 3 seconds
     50 "color":"blue"
Blue/green, canary, rollback
Green tested on its own URL, a 90/10 canary counted, then all traffic back to blue in a few seconds

Answer: one command sent 100 percent back to blue in a few seconds, and all 50 checks got blue. Cloud Run keeps old revisions, so a rollback is a traffic change, not a rebuild.

Break it: a deploy that fails (Q11)

Someone deploys a tag that was never pushed (v9).

# Q11: What happens when a deploy fails? Deploy an image tag that does not exist: the deploy stops and users keep the old version
gcloud run deploy iv-app --image=us-east1-docker.pkg.dev/$PROJECT_ID/interview/app:v9 --region=us-east1 --revision-suffix=bad --quiet 2>&1 | grep -E "ERROR" | cut -c1-200 | head -1
URL=$(gcloud run services describe iv-app --region=us-east1 --format="value(status.url)")
echo "users still see: $(curl -s $URL/)"
gcloud run revisions list --service=iv-app --region=us-east1 --format="table(metadata.name, status.conditions[0].status:label=READY)"
ERROR: (gcloud.run.deploy) Image 'us-east1-docker.pkg.dev/your-project-id/interview/app:v9' not found.
users still see: {"color":"blue","version":"1.0.0"}
NAME          READY
iv-app-bad    False
iv-app-green  True
iv-app-blue   True

Answer: the deploy stops with an error and no new revision takes traffic: users still see blue. A failed deploy should never be an outage.

Q12: debug a container that crashes at start

Why: "it works on my machine" is answered by running the exact same image with the exact same settings. Our app refuses to start when START_FAIL=1 (it stands for a missing database setting). timeout 15 stops the test after 15 seconds, and the output goes to crash.log.

# Q12: A container crashes at start. How do you debug it? Run the same image locally with the same settings for 15 seconds
timeout 15 sudo docker run --rm --name crashtest -e START_FAIL=1 app:v1 > crash.log 2>&1; sudo docker rm -f crashtest > /dev/null 2>&1
grep -c "startup check failed" crash.log | sed 's/$/ times: "startup check failed: DATABASE_URL is missing"/'
grep -m 3 -E "startup check|exited with code|Booting worker" crash.log | sed -E 's/^\[[^]]*\] //'
69 times: "startup check failed: DATABASE_URL is missing"
[7] [INFO] Booting worker with pid: 7
startup check failed: DATABASE_URL is missing
[1] [ERROR] Worker (pid:7) exited with code 1

Answer: in 15 seconds the app printed startup check failed: DATABASE_URL is missing 69 times. The real lesson: gunicorn (the web server) keeps restarting the crashed worker (Worker exited with code 1, Booting worker), so the container never stops by itself and its port stays open. That is exactly why a platform that only checks "is the port open?" can think this app is healthy. The fixes: read the logs (here locally, on Cloud Run in Cloud Logging), add an HTTP health check that calls the app itself, and make a missing setting stop the whole process, not just a worker.

Q13: least privilege

Why: an account with only roles/run.viewer may look but not change. We act as it (--impersonate-service-account) to list services, then to change traffic.

# Q13: Least privilege: an account that may only VIEW Cloud Run tries to deploy
gcloud iam service-accounts create iv-viewonly --display-name="Can only view Cloud Run" 2>&1 | tail -1
until gcloud iam service-accounts describe iv-viewonly@$PROJECT_ID.iam.gserviceaccount.com > /dev/null 2>&1; do sleep 5; done
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:iv-viewonly@$PROJECT_ID.iam.gserviceaccount.com" --role=roles/run.viewer --condition=None --format="value(etag)" > /dev/null && echo "iv-viewonly: roles/run.viewer"
ME=$(gcloud config get-value account); case "$ME" in *.gserviceaccount.com) ME="serviceAccount:$ME";; *) ME="user:$ME";; esac
gcloud iam service-accounts add-iam-policy-binding iv-viewonly@$PROJECT_ID.iam.gserviceaccount.com --member="$ME" --role=roles/iam.serviceAccountTokenCreator --format="value(etag)" > /dev/null && echo "I may act as iv-viewonly for this test"
for i in $(seq 1 20); do gcloud auth print-access-token --impersonate-service-account=iv-viewonly@$PROJECT_ID.iam.gserviceaccount.com > /dev/null 2>&1 && break; sleep 15; done; echo "acting as iv-viewonly works (after $i tries)"
gcloud run services list --region=us-east1 --impersonate-service-account=iv-viewonly@$PROJECT_ID.iam.gserviceaccount.com --format="value(metadata.name)" 2>&1 | grep -v WARNING
gcloud run services update-traffic iv-app --region=us-east1 --to-latest --impersonate-service-account=iv-viewonly@$PROJECT_ID.iam.gserviceaccount.com --quiet 2>&1 | grep -E "PERMISSION_DENIED|denied" | cut -c1-230 | head -1
Service account email: iv-viewonly@your-project-id.iam.gserviceaccount.com
Updated IAM policy for project [your-project-id].
iv-viewonly: roles/run.viewer
Updated IAM policy for serviceAccount [iv-viewonly@your-project-id.iam.gserviceaccount.com].
I may act as iv-viewonly for this test
acting as iv-viewonly works (after 6 tries)
iv-app
ERROR: (gcloud.run.services.update-traffic) PERMISSION_DENIED: Permission 'run.services.update' denied on resource 'namespaces/your-project-id/services/iv-app' (or resource may not exist).
Failures and least privilege
A missing image fails the deploy with no user impact, the crash is reproduced locally, and a read-only account is refused

Answer: the read-only account could list the service but was refused when it tried to change traffic. Give each person and each pipeline only what its job needs, so a mistake or a stolen key can do little harm.

Q14: idempotent scripts

# Q14: What is an idempotent script? Run "create the repository if it is missing" twice: same result, no error
for run in 1 2; do
  if gcloud artifacts repositories describe interview --location=us-east1 > /dev/null 2>&1; then echo "run $run: repository already exists, nothing to do"; else gcloud artifacts repositories create interview --repository-format=docker --location=us-east1 2>&1 | tail -1; fi
done
run 1: repository already exists, nothing to do
run 2: repository already exists, nothing to do

Answer: "create if missing" ran twice with the same result and no error. Idempotent scripts are safe to re-run after a failure halfway, which is what Terraform and Ansible are built around.

POC: prove it works

  • Q1 to Q4: cached layers, 1.12 GB vs 134 MB, ENTRYPOINT vs CMD, one image with two configs.
  • Q5 and Q6: a failing test stopped CI with no image built; the fixed build used a secret without printing it.
  • Q7: a moved latest tag versus fixed digests.
  • Q8 to Q10: green tested with no traffic, a counted 90/10 canary, a rollback in seconds.
  • Q11 to Q14: a failed deploy with no user impact, a crash reproduced locally, a read-only account refused, an idempotent script.

Quiz task: check what you learned

  1. You change only requirements.txt. Which layers rebuild? (Answer: from COPY requirements.txt down: the dependency install and everything after it.)
  2. Where should a database password for CI live? (Answer: in a secret manager, given to the pipeline at run time; never in the repo or the pipeline file.)
  3. Blue/green or canary for a risky change? (Answer: canary first, to limit how many users see a problem; blue/green when you want a quick full switch with a tested standby.)
  4. Why deploy by digest? (Answer: a tag can be moved; a digest always means the same image.)
  5. Name two signs your script is not idempotent. (Answer: it fails with "already exists" on a re-run, or it creates a duplicate.)

Clean up (delete everything)

# Clean up: service, images, secret, accounts and roles, build buckets, local images
gcloud run services delete iv-app --region=us-east1 --quiet 2>&1 | tail -1
gcloud artifacts repositories delete interview --location=us-east1 --quiet 2>&1 | tail -1
gcloud secrets delete db-password --quiet 2>&1 | tail -1
for r in roles/artifactregistry.writer roles/logging.logWriter roles/secretmanager.secretAccessor roles/storage.objectViewer; do for t in 1 2 3 4 5; do gcloud projects remove-iam-policy-binding $PROJECT_ID --member="serviceAccount:iv-ci-1122@$PROJECT_ID.iam.gserviceaccount.com" --role=$r --condition=None --format="value(etag)" > /dev/null 2>&1 && break; sleep 5; done; done
gcloud projects remove-iam-policy-binding $PROJECT_ID --member="serviceAccount:iv-viewonly@$PROJECT_ID.iam.gserviceaccount.com" --role=roles/run.viewer --condition=None --format="value(etag)" > /dev/null 2>&1; echo "roles removed"
for sa in iv-ci-1122 iv-viewonly; do gcloud iam service-accounts delete $sa@$PROJECT_ID.iam.gserviceaccount.com --quiet 2>&1 | tail -1; done
for b in $(gcloud storage buckets list --format="value(name)" | grep -E "cloudbuild"); do gcloud storage rm -r gs://$b --quiet > /dev/null 2>&1 && echo "deleted the build bucket"; done
cd ~ && rm -rf app probe.yaml crash.log
sudo docker system prune -af > /dev/null 2>&1; echo "local images: $(sudo docker images -q | wc -l)"
echo "services: $(gcloud run services list --format='value(name)' | grep -c iv-app)  secrets: $(gcloud secrets list --format='value(name)' | grep -c db-password)"
Deleted service [iv-app].
Deleted repository [interview].
Deleted secret [db-password].
roles removed
deleted service account [iv-ci-1122@your-project-id.iam.gserviceaccount.com]
deleted service account [iv-viewonly@your-project-id.iam.gserviceaccount.com]
deleted the build bucket
local images: 0
services: 0  secrets: 0
Clean up
Service, images, secret, accounts, build bucket and local images deleted

FAQ

How do I use this in an interview? Pick two or three you ran, and tell them as a short story: the situation, what you did, the real result (for example "the canary sent 10 of 100 requests to green; one command rolled back in a few seconds").

Is Cloud Run enough to talk about Kubernetes questions? The ideas are the same (revisions, traffic splitting, rollbacks, probes). Kubernetes adds Deployments, Services and rollouts; our Kubernetes Roadmap links the labs that cover those.

What about infrastructure as code? Q14's idea is the core of Terraform: describe the wanted state, apply it any number of times. A Terraform lab is a good next step.

What do interviewers ask after "canary"? How you decide to continue or roll back: error rate, latency (SLOs), and automatic rollback when they get worse.

Why use your own service account for CI? So the pipeline has only the roles it needs, separate from people and from the default account.

Do I need to memorise commands? No. Know why each step exists and what the output means; that is what this lab shows.

Troubleshooting

You seeWhyFix
Permission ... uploadArtifacts denied in a buildThe pipeline account's roles are not active yet, or missingWait (probe loop); grant roles/artifactregistry.writer
invalid value for 'build.substitutions'A shell $var in cloudbuild.yamlWrite $$var
Cloud Run answers 403 ForbiddenThe service does not allow unauthenticated callsDeploy with --allow-unauthenticated (needs Cloud Run admin) or call with a token
Failed to impersonateNo Token Creator role yet, or it is still spreadingGrant roles/iam.serviceAccountTokenCreator; retry after a minute
docker: permission deniedYour user is not in the docker groupUse sudo docker or add yourself to the group
A build fails with an empty logThe pipeline account cannot write logs yetWait for the roles; read with gcloud builds log <id>

What next

Prepared by the CareerByteCode Team from our tested lab, with AI help for the write-up.

Read next →DevOps Project for Your Resume: Full CI/CD on Google Cloud⏱ 19 min

⭐ Keep learning with CareerByteCode

Hand-picked to go deeper on this topic
News, guides and updates from the CareerByteCode team
🏅 Expert writer

The CareerByteCode team writes about what is new on careerbytecode.in: courses, labs, exams, events and the community, which is free to join for influencers and content creators in tech.

Get CareerByteCode Team's next blog by email

One email a week when they publish. Add the weekly Best of ByteBlog too. No spam, unsubscribe with one click.

We email you once to confirm. By subscribing you agree to the privacy policy.

💬 Comments (0)

Top · Newest

Sign in to comment

Related blogs

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterβ‚Ή499Build the projects →