Search Tutorials


Top GCP Cloud Build & CI/CD Interview Questions (2026) | JavaInUse

Top 20 GCP Cloud Build & CI/CD Interview Questions


  1. What is Cloud Build?
  2. What is Artifact Registry?
  3. What is Cloud Deploy?
  4. How do you create a build config?
  5. What are build triggers?
  6. How do you build Docker images?
  7. What are Cloud Build substitutions?
  8. How do you manage secrets in builds?
  9. What are build pools?
  10. How do you run tests in Cloud Build?
  11. What are Artifact Registry repositories?
  12. How do you implement blue-green deployments?
  13. What are Cloud Deploy pipelines?
  14. How do you implement GitOps?
  15. What are approval gates?
  16. How do you monitor builds?
  17. What are Cloud Build workers?
  18. How do you optimize build times?
  19. What is vulnerability scanning?
  20. What are CI/CD best practices?

Google Cloud Interview Questions

1. What is Cloud Build?

Cloud Build is a serverless CI/CD platform that executes builds on GCP infrastructure.

Cloud Build Features:
+-- Serverless build execution
+-- Docker image building
+-- Any language/tool support
+-- Automatic scaling
+-- Built-in triggers
+-- Integration with GCP services
+-- Private worker pools

Cloud Build Architecture:
+-------------------------------------------------------------+
|                    Cloud Build                               |
+-------------------------------------------------------------+
|  +-----------------------------------------------------+   |
|  |                     Triggers                         |   |
|  |  +-- Push to branch                                 |   |
|  |  +-- Pull request                                   |   |
|  |  +-- Tag push                                       |   |
|  |  +-- Manual/API                                     |   |
|  +-----------------------------------------------------+   |
|                          |                                  |
|  +-----------------------------------------------------+   |
|  |                Build Execution                       |   |
|  |  +---------+ +---------+ +---------+ +---------+  |   |
|  |  | Step 1  |>| Step 2  |>| Step 3  |>| Step 4  |  |   |
|  |  |(Build)  | |(Test)   | |(Package)| |(Deploy) |  |   |
|  |  +---------+ +---------+ +---------+ +---------+  |   |
|  +-----------------------------------------------------+   |
|                          |                                  |
|  +-----------------------------------------------------+   |
|  |                   Outputs                            |   |
|  |  +-- Container images                               |   |
|  |  +-- Build artifacts                                |   |
|  |  +-- Logs                                           |   |
|  +-----------------------------------------------------+   |
+-------------------------------------------------------------+

# Enable Cloud Build
gcloud services enable cloudbuild.googleapis.com

# Submit build manually
gcloud builds submit --config=cloudbuild.yaml .

# List builds
gcloud builds list --limit=10

# View build logs
gcloud builds log BUILD_ID

2. What is Artifact Registry?

Artifact Registry is a fully managed service for storing and managing build artifacts and dependencies.

Artifact Registry Features:
+-- Docker images
+-- Language packages (npm, Maven, Python, Go)
+-- Helm charts
+-- OS packages (apt, yum)
+-- Regional and multi-regional
+-- IAM integration
+-- Vulnerability scanning
+-- Cleanup policies

# Create repository
gcloud artifacts repositories create my-repo \
    --repository-format=docker \
    --location=us-central1 \
    --description="Docker images"

# Configure Docker authentication
gcloud auth configure-docker us-central1-docker.pkg.dev

# Push image
docker tag my-image us-central1-docker.pkg.dev/my-project/my-repo/my-image:v1
docker push us-central1-docker.pkg.dev/my-project/my-repo/my-image:v1

# List images
gcloud artifacts docker images list us-central1-docker.pkg.dev/my-project/my-repo

# Create Python repository
gcloud artifacts repositories create python-repo \
    --repository-format=python \
    --location=us-central1

# Configure pip
gcloud artifacts print-settings python \
    --project=my-project \
    --repository=python-repo \
    --location=us-central1

# npm repository
gcloud artifacts repositories create npm-repo \
    --repository-format=npm \
    --location=us-central1

# Configure npm
gcloud artifacts print-settings npm \
    --project=my-project \
    --repository=npm-repo \
    --location=us-central1

3. What is Cloud Deploy?

Cloud Deploy is a managed continuous delivery service for deploying to GKE and Cloud Run.

Cloud Deploy Architecture:
+-------------------------------------------------------------+
|                    Cloud Deploy                              |
+-------------------------------------------------------------+
|  +-----------------------------------------------------+   |
|  |              Delivery Pipeline                       |   |
|  |                                                      |   |
|  |  +-----+    +---------+    +---------+             |   |
|  |  | Dev |--->| Staging |--->|  Prod   |             |   |
|  |  +-----+    +---------+    +---------+             |   |
|  |              (approval)     (approval)              |   |
|  +-----------------------------------------------------+   |
|                                                              |
|  +-----------------------------------------------------+   |
|  |                   Targets                            |   |
|  |  +-- GKE Clusters                                   |   |
|  |  +-- Cloud Run Services                             |   |
|  |  +-- Anthos                                         |   |
|  +-----------------------------------------------------+   |
+-------------------------------------------------------------+

# delivery-pipeline.yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
  name: my-pipeline
description: Main delivery pipeline
serialPipeline:
  stages:
    - targetId: dev
      profiles: [dev]
    - targetId: staging
      profiles: [staging]
    - targetId: prod
      profiles: [prod]
      strategy:
        canary:
          runtimeConfig:
            kubernetes:
              serviceNetworking:
                service: my-service
          canaryDeployment:
            percentages: [25, 50, 75]
            verify: true

# targets.yaml
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: dev
description: Dev cluster
gke:
  cluster: projects/my-project/locations/us-central1/clusters/dev-cluster
---
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: prod
description: Production cluster
gke:
  cluster: projects/my-project/locations/us-central1/clusters/prod-cluster
requireApproval: true

# Create pipeline
gcloud deploy apply --file=delivery-pipeline.yaml --region=us-central1
gcloud deploy apply --file=targets.yaml --region=us-central1

# Create release
gcloud deploy releases create release-001 \
    --delivery-pipeline=my-pipeline \
    --region=us-central1 \
    --images=my-app=us-central1-docker.pkg.dev/my-project/repo/app:v1

4. How do you create a build config?

cloudbuild.yaml Structure:

# cloudbuild.yaml
steps:
  # Step 1: Build application
  - name: 'gcr.io/cloud-builders/npm'
    args: ['install']
  
  # Step 2: Run tests
  - name: 'gcr.io/cloud-builders/npm'
    args: ['test']
  
  # Step 3: Build Docker image
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'build'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/my-repo/my-app:$SHORT_SHA'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/my-repo/my-app:latest'
      - '.'
  
  # Step 4: Push image
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'push'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/my-repo/my-app:$SHORT_SHA'

# Images to push automatically
images:
  - 'us-central1-docker.pkg.dev/$PROJECT_ID/my-repo/my-app:$SHORT_SHA'
  - 'us-central1-docker.pkg.dev/$PROJECT_ID/my-repo/my-app:latest'

# Build artifacts to store
artifacts:
  objects:
    location: 'gs://$PROJECT_ID-artifacts/'
    paths: ['build/**']

# Build options
options:
  machineType: 'E2_HIGHCPU_8'
  diskSizeGb: 100
  logging: CLOUD_LOGGING_ONLY

# Timeout
timeout: '1200s'

# Service account
serviceAccount: 'projects/my-project/serviceAccounts/build-sa@my-project.iam.gserviceaccount.com'

# Environment variables
env:
  - 'NODE_ENV=production'
  - 'API_URL=https://api.example.com'

# Step-specific options
steps:
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'my-image', '.']
    timeout: '600s'
    dir: 'app/'
    env:
      - 'DOCKER_BUILDKIT=1'

5. What are build triggers?

Build Triggers:

# Create push trigger
gcloud builds triggers create github \
    --name=push-trigger \
    --repo-name=my-repo \
    --repo-owner=my-org \
    --branch-pattern='^main$' \
    --build-config=cloudbuild.yaml

# Create PR trigger
gcloud builds triggers create github \
    --name=pr-trigger \
    --repo-name=my-repo \
    --repo-owner=my-org \
    --pull-request-pattern='^main$' \
    --build-config=cloudbuild-pr.yaml \
    --comment-control=COMMENTS_ENABLED

# Create tag trigger
gcloud builds triggers create github \
    --name=release-trigger \
    --repo-name=my-repo \
    --repo-owner=my-org \
    --tag-pattern='^v[0-9]+\.[0-9]+\.[0-9]+$' \
    --build-config=cloudbuild-release.yaml

# Trigger configuration via YAML
# trigger.yaml
name: my-trigger
description: Main build trigger
github:
  owner: my-org
  name: my-repo
  push:
    branch: ^main$
includedFiles:
  - 'src/**'
ignoredFiles:
  - 'docs/**'
  - '*.md'
filename: cloudbuild.yaml
substitutions:
  _DEPLOY_ENV: production
  _REGION: us-central1

# Create from file
gcloud builds triggers create --file=trigger.yaml

# Manual trigger
gcloud builds triggers run my-trigger \
    --branch=main \
    --substitutions=_DEPLOY_ENV=staging

# Webhook trigger
gcloud builds triggers create webhook \
    --name=webhook-trigger \
    --secret=projects/my-project/secrets/webhook-secret/versions/latest \
    --build-config=cloudbuild.yaml





6. How do you build Docker images?

Docker Build Patterns:

# Basic build
steps:
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'build'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$COMMIT_SHA'
      - '.'

# Multi-stage build with cache
steps:
  # Pull cache image
  - name: 'gcr.io/cloud-builders/docker'
    entrypoint: 'bash'
    args:
      - '-c'
      - 'docker pull us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:latest || exit 0'
  
  # Build with cache
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'build'
      - '--cache-from'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:latest'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$COMMIT_SHA'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:latest'
      - '.'

# Kaniko build (no Docker daemon)
steps:
  - name: 'gcr.io/kaniko-project/executor:latest'
    args:
      - '--destination=us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$COMMIT_SHA'
      - '--cache=true'
      - '--cache-ttl=72h'

# Buildpacks (no Dockerfile needed)
steps:
  - name: 'gcr.io/k8s-skaffold/pack'
    args:
      - 'build'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$COMMIT_SHA'
      - '--builder'
      - 'gcr.io/buildpacks/builder:v1'

# Multi-platform build
steps:
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'buildx'
      - 'build'
      - '--platform'
      - 'linux/amd64,linux/arm64'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$COMMIT_SHA'
      - '--push'
      - '.'

7. What are Cloud Build substitutions?

Built-in Substitutions:
+-- $PROJECT_ID - Project ID
+-- $BUILD_ID - Build ID
+-- $COMMIT_SHA - Full commit SHA
+-- $SHORT_SHA - First 7 chars of SHA
+-- $REVISION_ID - Commit SHA or tag
+-- $BRANCH_NAME - Branch name
+-- $TAG_NAME - Tag name
+-- $REPO_NAME - Repository name
+-- $TRIGGER_NAME - Trigger name

# Using substitutions
steps:
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'build'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$BRANCH_NAME'
      - '--build-arg'
      - 'VERSION=$SHORT_SHA'
      - '.'

# Custom substitutions
substitutions:
  _DEPLOY_ENV: production
  _REGION: us-central1
  _CLUSTER_NAME: prod-cluster

steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    args:
      - 'run'
      - 'deploy'
      - 'my-service'
      - '--image=us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA'
      - '--region=$_REGION'
      - '--set-env-vars=ENV=$_DEPLOY_ENV'

# Override at runtime
gcloud builds submit \
    --config=cloudbuild.yaml \
    --substitutions=_DEPLOY_ENV=staging,_REGION=us-east1

# Dynamic substitutions
steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        echo "Building for environment: $_DEPLOY_ENV"
        if [ "$_DEPLOY_ENV" = "production" ]; then
          echo "Using production settings"
        fi

8. How do you manage secrets in builds?

Secrets Management:

# 1. Secret Manager integration
steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        gcloud secrets versions access latest --secret=my-api-key > /workspace/api_key.txt

# 2. Available as environment variable
availableSecrets:
  secretManager:
    - versionName: projects/$PROJECT_ID/secrets/api-key/versions/latest
      env: 'API_KEY'
    - versionName: projects/$PROJECT_ID/secrets/db-password/versions/latest
      env: 'DB_PASSWORD'

steps:
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'my-image', '.']
    secretEnv: ['API_KEY', 'DB_PASSWORD']

# 3. Mount as file
availableSecrets:
  secretManager:
    - versionName: projects/$PROJECT_ID/secrets/service-account/versions/latest
      env: 'SERVICE_ACCOUNT_KEY'

steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        echo "$$SERVICE_ACCOUNT_KEY" > /workspace/key.json
        gcloud auth activate-service-account --key-file=/workspace/key.json
    secretEnv: ['SERVICE_ACCOUNT_KEY']

# 4. Docker build secrets
steps:
  - name: 'gcr.io/cloud-builders/docker'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        echo "$$NPM_TOKEN" > /workspace/.npmrc
        docker build --secret id=npmrc,src=/workspace/.npmrc -t my-image .
    secretEnv: ['NPM_TOKEN']

# Grant access to secret
gcloud secrets add-iam-policy-binding api-key \
    --member="serviceAccount:123456789@cloudbuild.gserviceaccount.com" \
    --role="roles/secretmanager.secretAccessor"

9. What are build pools?

Private Pools:
+-- Dedicated compute resources
+-- VPC connectivity
+-- Custom machine types
+-- Compliance requirements
+-- Network isolation

# Create private pool
gcloud builds worker-pools create my-pool \
    --region=us-central1 \
    --peered-network=projects/my-project/global/networks/my-vpc \
    --peered-network-ip-range=192.168.0.0/24

# Configure worker pool
# pool.yaml
name: projects/my-project/locations/us-central1/workerPools/my-pool
privatePoolV1Config:
  workerConfig:
    machineType: e2-standard-8
    diskSizeGb: 100
  networkConfig:
    peeredNetwork: projects/my-project/global/networks/my-vpc
    peeredNetworkIpRange: /29
    egressOption: NO_PUBLIC_EGRESS

gcloud builds worker-pools update my-pool \
    --region=us-central1 \
    --config-from-file=pool.yaml

# Use in build config
options:
  pool:
    name: 'projects/my-project/locations/us-central1/workerPools/my-pool'

steps:
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'my-image', '.']

# Access internal resources
steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        # Can access internal VPC resources
        curl http://internal-api.internal.local/health

# Delete pool
gcloud builds worker-pools delete my-pool --region=us-central1

10. How do you run tests in Cloud Build?

Testing Patterns:

# Unit tests
steps:
  - name: 'node:18'
    entrypoint: 'npm'
    args: ['ci']
  
  - name: 'node:18'
    entrypoint: 'npm'
    args: ['test']
    env:
      - 'CI=true'

# Python tests
steps:
  - name: 'python:3.11'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        pip install -r requirements.txt
        pip install pytest pytest-cov
        pytest --cov=src --cov-report=xml tests/

# Integration tests
steps:
  # Start dependencies
  - name: 'docker/compose:1.29.2'
    args: ['up', '-d', 'postgres', 'redis']
  
  # Wait for services
  - name: 'gcr.io/cloud-builders/docker'
    entrypoint: 'bash'
    args:
      - '-c'
      - 'sleep 10'
  
  # Run tests
  - name: 'node:18'
    entrypoint: 'npm'
    args: ['run', 'test:integration']
    env:
      - 'DATABASE_URL=postgres://user:pass@localhost:5432/test'
  
  # Cleanup
  - name: 'docker/compose:1.29.2'
    args: ['down']

# E2E tests with browser
steps:
  - name: 'cypress/included:12.0.0'
    entrypoint: 'cypress'
    args:
      - 'run'
      - '--browser'
      - 'chrome'
    env:
      - 'CYPRESS_BASE_URL=http://localhost:3000'

# Test result reporting
steps:
  - name: 'node:18'
    entrypoint: 'npm'
    args: ['test', '--', '--reporters=jest-junit']
    env:
      - 'JEST_JUNIT_OUTPUT_DIR=/workspace/test-results'

artifacts:
  objects:
    location: 'gs://$PROJECT_ID-test-results/'
    paths: ['test-results/**']

11. What are Artifact Registry repositories?

Repository Types:

# Docker repository
gcloud artifacts repositories create docker-repo \
    --repository-format=docker \
    --location=us-central1 \
    --description="Docker images" \
    --kms-key=projects/my-project/locations/us-central1/keyRings/my-ring/cryptoKeys/my-key

# Python repository
gcloud artifacts repositories create python-repo \
    --repository-format=python \
    --location=us-central1

# pip.conf
[global]
extra-index-url = https://us-central1-python.pkg.dev/my-project/python-repo/simple/

# npm repository
gcloud artifacts repositories create npm-repo \
    --repository-format=npm \
    --location=us-central1

# .npmrc
@my-scope:registry=https://us-central1-npm.pkg.dev/my-project/npm-repo/
//us-central1-npm.pkg.dev/my-project/npm-repo/:always-auth=true

# Maven repository
gcloud artifacts repositories create maven-repo \
    --repository-format=maven \
    --location=us-central1

# pom.xml

  
    artifact-registry
    https://us-central1-maven.pkg.dev/my-project/maven-repo
  


# Virtual repository (proxy + remote)
gcloud artifacts repositories create virtual-repo \
    --repository-format=docker \
    --location=us-central1 \
    --mode=virtual-repository \
    --upstream-policy-file=upstream.yaml

# upstream.yaml
upstreamPolicies:
  - id: local
    repository: projects/my-project/locations/us-central1/repositories/local-repo
    priority: 100
  - id: dockerhub
    repository: projects/my-project/locations/us-central1/repositories/dockerhub-remote
    priority: 50

12. How do you implement blue-green deployments?

Blue-Green Deployment Patterns:

# Cloud Run blue-green
steps:
  # Build and push
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA', '.']
  
  - name: 'gcr.io/cloud-builders/docker'
    args: ['push', 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA']
  
  # Deploy new revision (no traffic)
  - name: 'gcr.io/cloud-builders/gcloud'
    args:
      - 'run'
      - 'deploy'
      - 'my-service'
      - '--image=us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA'
      - '--region=us-central1'
      - '--no-traffic'
      - '--tag=green'
  
  # Run smoke tests
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        GREEN_URL=$(gcloud run services describe my-service --region=us-central1 --format='value(status.traffic[0].url)' | grep green)
        curl -f $GREEN_URL/health || exit 1
  
  # Switch traffic
  - name: 'gcr.io/cloud-builders/gcloud'
    args:
      - 'run'
      - 'services'
      - 'update-traffic'
      - 'my-service'
      - '--region=us-central1'
      - '--to-tags=green=100'

# GKE blue-green with Cloud Deploy
# delivery-pipeline.yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
  name: my-pipeline
serialPipeline:
  stages:
    - targetId: production
      strategy:
        standard:
          verify: true
          predeploy:
            actions: ["verify-healthy"]
          postdeploy:
            actions: ["integration-tests"]

# skaffold.yaml
apiVersion: skaffold/v4beta1
kind: Config
deploy:
  kubectl:
    manifests:
      - k8s/*.yaml
verify:
  - name: integration-tests
    container:
      name: test-runner
      image: gcr.io/my-project/test-runner
      command: ["./run-tests.sh"]

13. What are Cloud Deploy pipelines?

Cloud Deploy Pipeline Components:

# delivery-pipeline.yaml
apiVersion: deploy.cloud.google.com/v1
kind: DeliveryPipeline
metadata:
  name: app-pipeline
  annotations:
    description: Application delivery pipeline
serialPipeline:
  stages:
    - targetId: dev
      profiles: [dev]
    - targetId: staging
      profiles: [staging]
      strategy:
        canary:
          runtimeConfig:
            kubernetes:
              gatewayServiceMesh:
                httpRoute: my-route
                service: my-service
                deployment: my-deployment
          canaryDeployment:
            percentages: [10, 50]
            verify: true
    - targetId: prod
      profiles: [prod]
      strategy:
        canary:
          canaryDeployment:
            percentages: [5, 25, 50, 75]
            verify: true

# targets.yaml
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: dev
gke:
  cluster: projects/my-project/locations/us-central1/clusters/dev-cluster
---
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: staging
gke:
  cluster: projects/my-project/locations/us-central1/clusters/staging-cluster
executionConfigs:
  - usages: [RENDER, DEPLOY]
    serviceAccount: deploy-sa@my-project.iam.gserviceaccount.com
---
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: prod
requireApproval: true
gke:
  cluster: projects/my-project/locations/us-central1/clusters/prod-cluster
deployParameters:
  replicas: "5"

# skaffold.yaml
apiVersion: skaffold/v4beta1
kind: Config
profiles:
  - name: dev
    deploy:
      kubectl:
        manifests: ["k8s/base/*", "k8s/dev/*"]
  - name: prod
    deploy:
      kubectl:
        manifests: ["k8s/base/*", "k8s/prod/*"]

# Create release
gcloud deploy releases create release-$(date +%Y%m%d-%H%M%S) \
    --delivery-pipeline=app-pipeline \
    --region=us-central1 \
    --images=app=us-central1-docker.pkg.dev/my-project/repo/app:v1.0.0

14. How do you implement GitOps?

GitOps with Config Sync:

# ConfigManagement setup
apiVersion: configmanagement.gke.io/v1
kind: ConfigManagement
metadata:
  name: config-management
spec:
  git:
    syncRepo: https://github.com/my-org/k8s-config
    syncBranch: main
    secretType: ssh
    policyDir: "clusters/prod"
  policyController:
    enabled: true

# Install Config Sync
gcloud container fleet config-management apply \
    --membership=my-cluster \
    --config=config-management.yaml

# Repository structure
k8s-config/
+-- clusters/
|   +-- dev/
|   |   +-- namespace.yaml
|   |   +-- deployments/
|   +-- staging/
|   +-- prod/
+-- namespaces/
+-- policies/

# Cloud Build for GitOps
# On code change, update manifest repo
steps:
  # Build and push image
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA', '.']
  
  - name: 'gcr.io/cloud-builders/docker'
    args: ['push', 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA']
  
  # Update manifest repository
  - name: 'gcr.io/cloud-builders/git'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        git clone https://github.com/my-org/k8s-config
        cd k8s-config
        
        # Update image tag
        sed -i "s|image:.*app:.*|image: us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA|g" \
          clusters/dev/deployments/app.yaml
        
        git config user.email "cloudbuild@example.com"
        git config user.name "Cloud Build"
        git add -A
        git commit -m "Update app to $SHORT_SHA"
        git push origin main
    secretEnv: ['GITHUB_TOKEN']

availableSecrets:
  secretManager:
    - versionName: projects/$PROJECT_ID/secrets/github-token/versions/latest
      env: 'GITHUB_TOKEN'

15. What are approval gates?

Approval Gates:

# Target with approval
apiVersion: deploy.cloud.google.com/v1
kind: Target
metadata:
  name: production
requireApproval: true
gke:
  cluster: projects/my-project/locations/us-central1/clusters/prod

# Approve release
gcloud deploy rollouts approve ROLLOUT_NAME \
    --delivery-pipeline=my-pipeline \
    --release=release-001 \
    --region=us-central1

# List pending approvals
gcloud deploy rollouts list \
    --delivery-pipeline=my-pipeline \
    --release=release-001 \
    --region=us-central1 \
    --filter="approvalState=NEEDS_APPROVAL"

# Automated approval with Cloud Functions
import functions_framework
from google.cloud import deploy_v1

@functions_framework.cloud_event
def auto_approve(cloud_event):
    client = deploy_v1.CloudDeployClient()
    
    # Parse event
    rollout = cloud_event.data['rollout']
    
    # Check conditions
    if should_auto_approve(rollout):
        client.approve_rollout(
            name=rollout['name'],
            approved=True
        )

def should_auto_approve(rollout):
    # Check test results, time window, etc.
    return True

# Manual approval notification
steps:
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        # Send Slack notification
        curl -X POST -H 'Content-type: application/json' \
          --data '{"text":"Release awaiting approval: $RELEASE_NAME"}' \
          $SLACK_WEBHOOK_URL
    secretEnv: ['SLACK_WEBHOOK_URL']

# IAM for approvers
gcloud projects add-iam-policy-binding my-project \
    --member="group:release-approvers@company.com" \
    --role="roles/clouddeploy.approver"

16. How do you monitor builds?

Build Monitoring:

# View build logs
gcloud builds log BUILD_ID

# Stream logs
gcloud builds log BUILD_ID --stream

# Cloud Logging query
resource.type="build"
resource.labels.build_id="BUILD_ID"

# Build notifications with Pub/Sub
gcloud pubsub topics create cloud-builds

gcloud builds triggers update my-trigger \
    --include-build-logs=INCLUDE_BUILD_LOGS_WITH_STATUS

# Cloud Function for notifications
import functions_framework
from google.cloud import pubsub_v1
import json

@functions_framework.cloud_event
def build_notification(cloud_event):
    build = json.loads(cloud_event.data['message']['data'])
    
    status = build['status']
    build_id = build['id']
    
    if status == 'FAILURE':
        send_alert(f"Build {build_id} failed!")
    elif status == 'SUCCESS':
        send_notification(f"Build {build_id} succeeded")

# Cloud Monitoring dashboard
# Build success rate
fetch cloud_build
| metric cloudbuild.googleapis.com/build/count
| filter status = "SUCCESS"
| group_by [build_trigger_id]
| ratio

# Build duration
fetch cloud_build
| metric cloudbuild.googleapis.com/build/time
| group_by [build_trigger_id], mean(value)

# Alert on build failures
gcloud alpha monitoring policies create \
    --display-name="Build Failure Alert" \
    --condition-display-name="Build failures" \
    --condition-filter='resource.type="build" AND metric.type="cloudbuild.googleapis.com/build/count" AND metric.labels.status="FAILURE"' \
    --condition-threshold-value=1 \
    --notification-channels=CHANNEL_ID

17. What are Cloud Build workers?

Worker Configuration:

# Machine types
options:
  machineType: 'E2_HIGHCPU_8'
  # Available: E2_MEDIUM, E2_HIGHCPU_8, E2_HIGHCPU_32, N1_HIGHCPU_8, N1_HIGHCPU_32

# Disk size
options:
  diskSizeGb: 200

# Logging options
options:
  logging: CLOUD_LOGGING_ONLY
  # Options: CLOUD_LOGGING_ONLY, GCS_ONLY, NONE, LEGACY

# Dynamic configuration based on branch
substitutions:
  _MACHINE_TYPE: 'E2_MEDIUM'

options:
  machineType: ''

# Different config per step (not supported, use workaround)
steps:
  # Light step
  - name: 'gcr.io/cloud-builders/gcloud'
    args: ['version']
  
  # Heavy step (run in separate build)
  - name: 'gcr.io/cloud-builders/gcloud'
    args:
      - 'builds'
      - 'submit'
      - '--config=heavy-build.yaml'
      - '--async'

# Private pool configuration
gcloud builds worker-pools create high-memory-pool \
    --region=us-central1 \
    --peered-network=projects/my-project/global/networks/my-vpc

# Update pool
gcloud builds worker-pools update high-memory-pool \
    --region=us-central1 \
    --worker-machine-type=e2-highmem-8 \
    --worker-disk-size=500GB

# Use in build
options:
  pool:
    name: 'projects/my-project/locations/us-central1/workerPools/high-memory-pool'

18. How do you optimize build times?

Build Optimization:

# 1. Docker layer caching
steps:
  - name: 'gcr.io/cloud-builders/docker'
    entrypoint: 'bash'
    args:
      - '-c'
      - 'docker pull us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:latest || exit 0'
  
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'build'
      - '--cache-from'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:latest'
      - '-t'
      - 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA'
      - '.'

# 2. Kaniko caching
steps:
  - name: 'gcr.io/kaniko-project/executor:latest'
    args:
      - '--destination=us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA'
      - '--cache=true'
      - '--cache-ttl=168h'

# 3. Parallel steps
steps:
  - name: 'node:18'
    id: 'install'
    args: ['npm', 'ci']
  
  # These run in parallel
  - name: 'node:18'
    id: 'lint'
    waitFor: ['install']
    args: ['npm', 'run', 'lint']
  
  - name: 'node:18'
    id: 'test'
    waitFor: ['install']
    args: ['npm', 'test']
  
  # This waits for both
  - name: 'node:18'
    id: 'build'
    waitFor: ['lint', 'test']
    args: ['npm', 'run', 'build']

# 4. Incremental builds
steps:
  - name: 'gcr.io/cloud-builders/gsutil'
    args: ['cp', 'gs://build-cache/node_modules.tar.gz', '.']
  
  - name: 'node:18'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        tar -xzf node_modules.tar.gz || true
        npm ci
        tar -czf node_modules.tar.gz node_modules/
  
  - name: 'gcr.io/cloud-builders/gsutil'
    args: ['cp', 'node_modules.tar.gz', 'gs://build-cache/']

# 5. Use faster machine
options:
  machineType: 'E2_HIGHCPU_32'





19. What is vulnerability scanning?

Container Scanning:

# Enable scanning
gcloud services enable containerscanning.googleapis.com

# Auto-scanning on push
gcloud artifacts repositories update my-repo \
    --location=us-central1 \
    --enable-vulnerability-scanning

# Manual scan
gcloud artifacts docker images scan \
    us-central1-docker.pkg.dev/my-project/repo/app:v1

# List vulnerabilities
gcloud artifacts docker images list-vulnerabilities \
    us-central1-docker.pkg.dev/my-project/repo/app@sha256:xxx

# Build with scan gate
steps:
  - name: 'gcr.io/cloud-builders/docker'
    args: ['build', '-t', 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA', '.']
  
  - name: 'gcr.io/cloud-builders/docker'
    args: ['push', 'us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA']
  
  # Wait for scan
  - name: 'gcr.io/cloud-builders/gcloud'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        # Wait for scan to complete
        sleep 60
        
        # Check for critical vulnerabilities
        CRITICAL=$(gcloud artifacts docker images describe \
          us-central1-docker.pkg.dev/$PROJECT_ID/repo/app:$SHORT_SHA \
          --show-image-basis \
          --format='value(discovery.discovered.analysis_status.critical)')
        
        if [ "$CRITICAL" -gt 0 ]; then
          echo "Critical vulnerabilities found!"
          exit 1
        fi

# Binary Authorization
# Require attestation before deploy
gcloud container binauthz policy export > policy.yaml

# policy.yaml
admissionWhitelistPatterns:
  - namePattern: us-central1-docker.pkg.dev/my-project/repo/*
defaultAdmissionRule:
  evaluationMode: REQUIRE_ATTESTATION
  enforcementMode: ENFORCED_BLOCK_AND_AUDIT_LOG
  requireAttestationsBy:
    - projects/my-project/attestors/security-attestor

gcloud container binauthz policy import policy.yaml

20. What are CI/CD best practices?

CI/CD Best Practices:

1. Build Security
# Use specific image tags
- name: 'gcr.io/cloud-builders/docker@sha256:xxx'

# Scan for vulnerabilities
# Use Binary Authorization
# Store secrets in Secret Manager

2. Pipeline Structure
# cloudbuild.yaml
steps:
  # Validate
  - name: 'validator'
    id: 'validate'
  
  # Build
  - name: 'builder'
    id: 'build'
    waitFor: ['validate']
  
  # Test (parallel)
  - name: 'tester'
    id: 'unit-test'
    waitFor: ['build']
  
  - name: 'tester'
    id: 'integration-test'
    waitFor: ['build']
  
  # Package
  - name: 'packager'
    id: 'package'
    waitFor: ['unit-test', 'integration-test']
  
  # Deploy
  - name: 'deployer'
    id: 'deploy'
    waitFor: ['package']

3. Environment Promotion
dev --> staging --> production
+-- Automated to dev
+-- Manual approval for staging
+-- Manual approval for production

4. Rollback Strategy
# Cloud Run
gcloud run services update-traffic my-service \
    --to-revisions=PREVIOUS_REVISION=100

# GKE
kubectl rollout undo deployment/my-app

5. Monitoring and Alerts
# Build duration trends
# Success/failure rates
# Deployment frequency
# Mean time to recovery

6. Infrastructure as Code
# Version control all configs
# Review changes via PR
# Automate deployments

7. Artifact Management
# Tag images semantically
# Implement cleanup policies
# Use immutable tags for production

gcloud artifacts repositories set-cleanup-policies my-repo \
    --location=us-central1 \
    --policy=cleanup-policy.json

Google Cloud Interview Questions


Popular Posts