0
0
GcpHow-ToBeginner · 3 min read

How to Set Environment Variables in Cloud Run

To set environment variables in Cloud Run, use the Google Cloud Console or the gcloud run deploy command with the --set-env-vars flag. These variables configure your service without changing code, making deployments flexible and secure.
📐

Syntax

Use the gcloud run deploy command with the --set-env-vars flag to define environment variables. The syntax is:

  • gcloud run deploy SERVICE_NAME --image IMAGE_URL --set-env-vars KEY1=VALUE1,KEY2=VALUE2

Here, SERVICE_NAME is your Cloud Run service name, IMAGE_URL is your container image, and KEY=VALUE pairs set environment variables.

bash
gcloud run deploy SERVICE_NAME --image IMAGE_URL --set-env-vars KEY1=VALUE1,KEY2=VALUE2
💻

Example

This example deploys a Cloud Run service named hello-service with two environment variables: GREETING and TARGET. The service uses the container image gcr.io/cloudrun/hello.

bash
gcloud run deploy hello-service \
  --image gcr.io/cloudrun/hello \
  --set-env-vars GREETING=Hello,TARGET=World \
  --region us-central1 \
  --platform managed
Output
Deploying container to Cloud Run service [hello-service] in project [YOUR_PROJECT_ID] region [us-central1] Service [hello-service] revision [hello-service-00001-abc] has been deployed and is serving 100 percent of traffic. Service URL: https://hello-service-xyz.a.run.app
⚠️

Common Pitfalls

Common mistakes when setting environment variables in Cloud Run include:

  • Using spaces after commas in --set-env-vars which causes errors.
  • Not redeploying the service after changing environment variables.
  • Exposing sensitive data directly in environment variables without encryption or secret management.

Always double-check syntax and consider using Secret Manager for sensitive values.

bash
Wrong:
gcloud run deploy my-service --image IMAGE_URL --set-env-vars KEY1=VALUE1, KEY2=VALUE2

Right:
gcloud run deploy my-service --image IMAGE_URL --set-env-vars KEY1=VALUE1,KEY2=VALUE2
📊

Quick Reference

CommandDescription
gcloud run deploy SERVICE --image IMAGE --set-env-vars KEY=VALUEDeploy service with environment variables
gcloud run services describe SERVICEView current environment variables
gcloud run deploy SERVICE --clear-env-varsRemove all environment variables
Use Cloud Console Environment Variables tabSet env vars via UI

Key Takeaways

Use the --set-env-vars flag with gcloud run deploy to set environment variables.
Avoid spaces after commas in environment variable lists to prevent errors.
Redeploy your Cloud Run service to apply environment variable changes.
Use Secret Manager for sensitive environment variables instead of plain text.
You can also set environment variables via the Cloud Run Console UI.