Secret Manager is easier to use with Cloud Run since I last wrote about "serverless mysteries". At the time of that writing, the best way to use a Secret in Cloud Run was to add code to your service to integrate with the Secret Manager API. Now Cloud Run does that for you!
In this post we'll migrate the "Loyalty Checker" service from using the Secret Manager client library to use Cloud Run's direct Secret Manager integration. (As of this writing, the integration is still in preview.)
If you're still set up from last time, just open Cloud Shell and continue where we left off.
Otherwise, please walk through the last post then continue here to enjoy the feeling of deleting code.
Direct integration with Secret Manager makes the code simpler:
- Remove code to initialize the client library
- Remove code to retrieve the secret on the first request
- Rename the
SECRET_VALUE, the service will have direct access to the secret from the environment variable.
After these changes the service has shrunk by 46 lines of code, and no longer has any dependencies on Secret Manager:
We'll combine the Secret integration with the new all-in-one deploy command:
gcloud beta run deploy loyalty \ --source . \ --remove-env-vars SECRET_NAME \ --update-secrets SECRET_VALUE=you-know-who:1
--sourceflag tells gcloud to check for a Dockerfile in the current directory and use Cloud Build under the hood to build a container image without a separate command. (Read more about deploying from source code if you're curious about the details.)
--remove-env-varsflag removes the no-longer-needed reference to a secret for our code to load.
--update-secretsflag integrates a new secret with the service without disrupting any existing secrets. (Use
--set-secretsto simultaneously remove any the other secrets.)
One of the nice things about Cloud Run's secrets flag is how you can use just the "resource ID" part of the overall resource name. Secrets are normally referenced as "
projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION" but all you need to reference a secret in the same project is
There's no need to change IAM settings. Last time we set up a dedicated service account and gave it access to the secret. The same configuration works for client libraries or for this direct integration.
If you want to be able to "live refresh" the secret in your service, check out the documentation to learn how to mount your secrets as a volume. The environment variable method in this post is configured when an instance is started and is never updated.
All code © Google w/ Apache 2 license