How to Use Secret Manager with Cloud Run on GCP
To use
Secret Manager with Cloud Run, grant your Cloud Run service the Secret Manager Accessor role, then configure your service to access secrets as environment variables or via the Secret Manager API. This lets your Cloud Run app securely retrieve secrets without hardcoding them.Syntax
Here is the basic syntax to access secrets in Cloud Run:
- Grant permissions: Assign the
roles/secretmanager.secretAccessorrole to the Cloud Run service account. - Reference secrets: Use environment variables or call the Secret Manager API in your code.
- Deploy Cloud Run: Include secret references in your deployment command or YAML.
bash
gcloud run deploy SERVICE_NAME \ --image IMAGE_URL \ --update-secrets SECRET_ENV_VAR=SECRET_NAME:latest
Example
This example shows how to deploy a Cloud Run service that uses a secret as an environment variable.
The secret named my-secret is exposed as the environment variable API_KEY inside the container.
bash
gcloud secrets create my-secret --data-file=./api_key.txt gcloud run deploy my-service \ --image gcr.io/my-project/my-image \ --update-secrets API_KEY=my-secret:latest \ --region us-central1 \ --platform managed
Output
Deploying service [my-service]...
Done.
Service URL: https://my-service-xyz.a.run.app
Common Pitfalls
Common mistakes when using Secret Manager with Cloud Run include:
- Not granting
secretAccessorrole to the Cloud Run service account, causing permission errors. - Using incorrect secret names or versions in deployment commands.
- Hardcoding secrets inside the container instead of using Secret Manager.
- Forgetting to redeploy Cloud Run after updating secret references.
bash
### Wrong: No permissions granted
# This causes permission denied errors
### Right: Grant permission
PROJECT_ID=$(gcloud config get-value project)
SERVICE_ACCOUNT=$(gcloud run services describe my-service --region us-central1 --format='value(spec.template.spec.serviceAccountName)')
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:$SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com \
--role=roles/secretmanager.secretAccessorQuick Reference
Summary tips for using Secret Manager with Cloud Run:
- Always assign
roles/secretmanager.secretAccessorto your Cloud Run service account. - Use
--update-secretsflag ingcloud run deployto map secrets to environment variables. - Access secrets securely in your app via environment variables or Secret Manager API.
- Update and redeploy your service when secrets change.
Key Takeaways
Grant the Secret Manager Accessor role to your Cloud Run service account to allow secret access.
Use the --update-secrets flag during deployment to expose secrets as environment variables.
Never hardcode secrets; always retrieve them securely from Secret Manager.
Redeploy Cloud Run services after updating secret references to apply changes.
Test permissions and secret names carefully to avoid access errors.