Configure secrets  |  Cloud Run Documentation  |  Google Cloud (2024)

Your service might need to have dependencies requiring API keys, passwords, certificates, or other sensitive information. For Cloud Run, Google recommendsthat you store this type of sensitive information in a secret created inSecret Manager.

You can make a secret available to your containers in either of two ways:

  • Mount each secret as a volume, which makes the secret available to thecontainer as files. Reading a volume always fetches the secret value fromSecret Manager, so it can be used with the latest version. Thismethod also works well with secret rotation.
  • Pass a secret using environment variables.Environment variables are resolved at instance startup time, so if you usethis method, Google recommends that you pin the secret to a particular versionrather than using latest.

For more information, refer to the Secret Managerbest practices document.

How secrets are checked at deployment and runtime

During service deployment, all secrets used, whether asenvironment variable or mounted as a volume, are checked to ensure theservice account used to run the containerhas access to them. If any check fails, the service deployment fails.

During runtime, when instances start up:

  • If the secret is an environment variable, the value of the secret is retrievedprior to starting the instance, so if secret retrieval fails, the instance does not start.
  • If the secret is mounted as a volume, no check is performed during instance startup. However, during runtime, if a secret is inaccessible, attempts to read the mounted volume will fail.

Volume ownership differs by execution environment and deployment type

When you mount a volume, the identity owning the files and directories differsdepending on the workload's execution environment and on whether the deploymentconsists of one or multiple containers.

In the first generation execution environment where you are deploying a singlecontainer, the volume is owned by the identity used for the container. In allother cases, the volume is owned by root. This includes:

  • First generation execution environment where you are deploying multiplecontainers
  • The second generation environment

Before you begin

You can use an existing Secret Manager secret orcreate a new secret.

Required roles

To get the permissions that you need to configure secrets, ask your administrator to grant you the following IAM roles:

  • Cloud Run Admin (roles/run.admin) on the Cloud Run service
  • Service Account User (roles/iam.serviceAccountUser) on the service identity

To allow Cloud Run to access the secret, theservice identity must have the following role:

  • Secret Manager Secret Accessor (roles/secretmanager.secretAccessor)

For instructions on how to add the service identity principal to theSecret Manager Secret Accessor role, seeManage access to secrets.

For a list of IAM roles and permissions that are associated withCloud Run, seeCloud Run IAM rolesand Cloud Run IAM permissions.If your Cloud Run service interfaces withGoogle Cloud APIs, such as Cloud Client Libraries, see theservice identity configuration guide.For more information about granting roles, seedeployment permissionsand manage access.

Make a secret accessible to Cloud Run

Any configuration change leads to thecreation of a new revision. Subsequent revisions will also automatically getthis configuration setting unless you make explicit updates to change it.

You can make a secret accessible to your serviceusing the Google Cloud console, the Google Cloud CLI, or a YAML file when youdeploy a new service or update an existingservice and deploy a revision:

Console

  1. In the Google Cloud console, go to Cloud Run:

    Go to Cloud Run

  2. Click Deploy container and select Service to configure anew service. If you are configuring an existing service, click theservice, then click Edit and deploy new revision.

  3. If you are configuring a new service, fill out the initial servicesettings page, then click Container(s), volumes, networking, security to expand theservice configuration page.

  4. Click the Container tab.

    Configure secrets | Cloud Run Documentation | Google Cloud (1)

    • Under Secrets:
      • Click Reference a Secret.
      • Select the secret you want to use from the Secret pulldown list.
      • In the Reference methodpulldown menu, select the way you want to use your secret, mounted as avolume or exposed as environment variables.
      • If you are mounting the secret as a volume:
        1. Under Mount path, specify the mount path you are using for secrets.
        2. By default, the latest version is selected. You can select a specific version if you want. Under Specified paths for secret versions, specify the path to the version and the version number.
        3. Click Done.
      • If you are exposing the secret as an environment variable:
        1. Supply the Name of the variable and select the secret version, or latest to always use the current secret version.
        2. Click Done.
  5. Click Create or Deploy.

gcloud

To make a secret accessible to your service, enter one of the followingcommands.

  • To mount the secret as a volume when deploying a service:

    gcloud run deploy SERVICE --image IMAGE_URL \--update-secrets=PATH=SECRET_NAME:VERSION

    Replace:

    • SERVICE with the name of your service.
    • IMAGE_URL with a reference to the container image, forexample, us-docker.pkg.dev/cloudrun/container/hello:latest. If you use Artifact Registry,the repository REPO_NAME mustalready be created. The URL has the shape LOCATION-docker.pkg.dev/PROJECT_ID/REPO_NAME/PATH:TAG
    • PATHwith the mount path of the volume andfilename of the secret. It must start with a leading slash, for example:/etc/secrets/dbconfig/password, where /etc/secrets/dbconfig/ is themount path of the volume, and password is the filename of the secret.
    • SECRET_NAME with the secret name in the same project, e.g. mysecret.
    • VERSION with the secret version. Use latestfor latest version, or a number, for example, 2.
  • To expose the secret as an environment variable when deploying aservice:

    gcloud run deploy SERVICE \--image IMAGE_URL \--update-secrets=ENV_VAR_NAME=SECRET_NAME:VERSION

    Replace:

    • SERVICE with the name of your service.
    • IMAGE_URL with a reference to the container image, forexample, us-docker.pkg.dev/cloudrun/container/hello:latest. If you use Artifact Registry,the repository REPO_NAME mustalready be created. The URL has the shape LOCATION-docker.pkg.dev/PROJECT_ID/REPO_NAME/PATH:TAG
    • ENV_VAR_NAME with the name of the environment variable you want to use with the secret.
    • SECRET_NAME with the secret name in the same project, e.g. mysecret.
    • VERSION with the secret version. Use latestfor latest version, or a number, for example, 2.
  • You can update multiple secrets at the same time. To do this, separate theconfiguration options for each secret with a comma. The following commandupdates one secret mounted as a volume and another secret exposed as anenvironment variable.

    To update existing secrets, enter the following command:

    gcloud run deploy SERVICE --image IMAGE_URL \--update-secrets=PATH=SECRET_NAME:VERSION,ENV_VAR_NAME=SECRET_NAME:VERSION
  • To clear existing secrets and make a new secret accessible tothe service, use the --set-secrets flag:

    gcloud run services update SERVICE \--set-secrets="ENV_VAR_NAME=SECRET_NAME:VERSION"

YAML

  1. If you are creating a new service, skip this step.If you are updating an existing service, download its YAML configuration:

    gcloud run services describe SERVICE --format export > service.yaml
  2. For secrets exposed as environment variables, under env, update theENV_VAR, VERSION,and/or SECRET_NAME as desired. If you have multiple secretsmounted as environment variables, you will have multiples of theseattributes.

    apiVersion: serving.knative.dev/v1kind: Servicemetadata: name: SERVICEspec: template: metadata: name: REVISION spec: containers: - image: IMAGE_URL env: - name: ENV_VAR valueFrom: secretKeyRef: key: VERSION name: SECRET_NAME
  3. For secrets mounted as file paths, update theMOUNT_PATH, VOLUME_NAME, VERSION,FILENAME, and/or SECRET_NAME as desired. If youhave multiple secrets mounted as file paths, you will have multiples of theseattributes.

    apiVersion: serving.knative.dev/v1kind: Servicemetadata: name: SERVICEspec: template: metadata: name: REVISION spec: containers: - image: IMAGE_URL volumeMounts: - mountPath: MOUNT_PATH name: VOLUME_NAME volumes: - name: VOLUME_NAME secret: items: - key: VERSION path: FILENAME secretName: SECRET_NAME

    Note that VOLUME_NAME can be set to any name.

    Replace

    • SERVICE with the name of your Cloud Run service
    • IMAGE_URL with a reference to the container image, forexample, us-docker.pkg.dev/cloudrun/container/hello:latest. If you use Artifact Registry,the repository REPO_NAME mustalready be created. The URL has the shape LOCATION-docker.pkg.dev/PROJECT_ID/REPO_NAME/PATH:TAG
    • REVISION with a new revision name or delete it (if present). If you supply a new revision name, it must meet the following criteria:
      • Starts with SERVICE-
      • Contains only lowercase letters, numbers and -
      • Does not end with a -
      • Does not exceed 63 characters
  4. Replace the service with its new configuration using the followingcommand:

    gcloud run services replace service.yaml

Terraform

  1. Create a secret and a secret version.

    terraform { required_providers { google = { source = "hashicorp/google" version = "~> 5.13.0" } }}resource "google_secret_manager_secret" "default" { secret_id = "my-secret" replication { auto {} }}resource "google_secret_manager_secret_version" "default" { secret = google_secret_manager_secret.default.name secret_data = "this is secret data"}
  2. Create a service account and grant it access to the secret:

    resource "google_service_account" "default" { account_id = "cloud-run-service-account" display_name = "Service account for Cloud Run"}resource "google_secret_manager_secret_iam_member" "default" { secret_id = google_secret_manager_secret.default.id role = "roles/secretmanager.secretAccessor" # Grant the new deployed service account access to this secret. member = "serviceAccount:${google_service_account.default.email}" depends_on = [google_secret_manager_secret.default]}
  3. Secret Manager secrets can be accessed from Cloud Run as mounted file paths or as environment variables.

    1. For secrets mounted as file paths, reference the Secret Manager resource in the volumes parameter. The name corresponds with an entry in the volume_mounts parameter:

      resource "google_cloud_run_v2_service" "mounted_secret" { name = "cloudrun-srv-mounted-secret" location = "us-central1" ingress = "INGRESS_TRAFFIC_ALL" template { volumes { name = "my-service-volume" secret { secret = google_secret_manager_secret.default.secret_id items { version = "latest" path = "my-secret" mode = 0 # use default 0444 } } } containers { image = "us-docker.pkg.dev/cloudrun/container/hello" volume_mounts { name = "my-service-volume" mount_path = "/secrets" } } service_account = google_service_account.default.email } depends_on = [google_secret_manager_secret_version.default]}
    2. For secrets exposed as environment variables, reference the Secret Manager resource in the env parameter:

      resource "google_cloud_run_v2_service" "env_variable_secret" { name = "cloudrun-srv-env-var-secret" location = "us-central1" ingress = "INGRESS_TRAFFIC_ALL" template { containers { image = "us-docker.pkg.dev/cloudrun/container/hello" env { name = "MY_SECRET" value_source { secret_key_ref { secret = google_secret_manager_secret.default.secret_id version = "latest" } } } } service_account = google_service_account.default.email } depends_on = [google_secret_manager_secret_version.default]}

Referencing secrets from other projects

You can reference a secret from another project, if your project's serviceaccount has been allowed to access the secret.

Console

  1. In the Google Cloud console, go to Cloud Run:

    Go to Cloud Run

  2. Click Deploy container and select Service to configure anew service. If you are configuring an existing service, click theservice, then click Edit and deploy new revision.

  3. If you are configuring a new service, fill out the initial servicesettings page, then click Container(s), volumes, networking, security to expand theservice configuration page.

  4. Click the Container tab.

    Configure secrets | Cloud Run Documentation | Google Cloud (2)

    • Under Secrets:
      • Click Reference a Secret.
      • Select Don't see your secret? Enter secret resource ID from the Secret pulldown list todisplay the following form:

        Configure secrets | Cloud Run Documentation | Google Cloud (3)

      • In the Add a secret by resource ID form, enter the secret fromthe other project, in the format projects/PROJECT_NUMBER/secrets/SECRET_NAME.You can alternatively copy and paste the resource ID from the other project ifyou have access to it, by selecting the secret, clicking theActions ellipsis at the right of the secret, and selectingCopy resource ID from the pulldown menu.
      • Click Add secret.
      • In the Reference method pulldown menu, select the way you want touse your secret, mounted as a volume or exposed as environment variables.
      • If you are mounting the secret as a volume:
        1. Under Mount path, specify the mount path you are using for secrets.
        2. By default, the latest version is selected. You can select a specific version if you want. Under Specified paths for secret versions, specify the path to the version and the version number.
        3. Click Done.
      • If you are exposing the secret as an environment variable:
        1. Supply the Name of the variable and select the secret version, or latest to always use the current secret version.
        2. Click Done.
  5. Click Create or Deploy.

gcloud

  • To mount a secret as a volume when deploying a service:

    gcloud run deploy SERVICE --image IMAGE_URL \--update-secrets=PATH=projects/PROJECT_NUMBER/secrets/SECRET_NAME:VERSION

    Replace:

    • SERVICE with the name of your service.
    • IMAGE_URL with a reference to the container image, forexample, us-docker.pkg.dev/cloudrun/container/hello:latest. If you use Artifact Registry,the repository REPO_NAME mustalready be created. The URL has the shape LOCATION-docker.pkg.dev/PROJECT_ID/REPO_NAME/PATH:TAG
    • PATHwith the mount path of the volume andfilename of the secret. It must start with a leading slash, for example:/etc/secrets/dbconfig/password, where /etc/secrets/dbconfig/ is themount path of the volume, and password is the filename of the secret.
    • PROJECT_NUMBER with the project number for theproject the secret was created in.
    • SECRET_NAME with the secret name, e.g. mysecret.
    • VERSION with the secret version. Use latestfor latest version, or a number, for example, 2.

YAML

  1. If you are creating a new service, skip this step.If you are updating an existing service, download its YAML configuration:

    gcloud run services describe SERVICE --format export > service.yaml

Due to constraints around API compatibility, the secret locations must be storedin an annotation.

  1. For secrets exposed as environment variables:

    apiVersion: serving.knative.dev/v1kind: Servicemetadata: name: SERVICEspec: template: metadata: annotations: run.googleapis.com/secrets: SECRET_LOOKUP_NAME:projects/PROJECT_NUMBER/secrets/SECRET_NAME spec: containers: - image: IMAGE_URL env: - name: ENV_VAR valueFrom: secretKeyRef: key: VERSION name: SECRET_LOOKUP_NAME

    Replace:

    • SERVICE with the name of your service.
    • IMAGE_URL with a reference to the container image, forexample, us-docker.pkg.dev/cloudrun/container/hello:latest. If you use Artifact Registry,the repository REPO_NAME mustalready be created. The URL has the shape LOCATION-docker.pkg.dev/PROJECT_ID/REPO_NAME/PATH:TAG
    • ENV_VAR
    • PROJECT_NUMBER with the project number for theproject the secret was created in.
    • SECRET_NAME with the secret name, e.g. mysecret.
    • VERSION with the secret version. Use latestfor latest version, or a number, for example, 2.
    • SECRET_LOOKUP_NAME with any name that has avalid secret name syntax (e.g. my-secret), it can be the same asSECRET_NAME
  2. For secrets mounted as file paths:

    apiVersion: serving.knative.dev/v1kind: Servicemetadata: name: SERVICEspec: template: metadata: annotations: run.googleapis.com/secrets: SECRET_LOOKUP_NAME:projects/PROJECT_NUMBER/secrets/SECRET_NAME spec: containers: - image: IMAGE_URL volumeMounts: - mountPath: MOUNT_PATH name: VOLUME_NAME volumes: - name: VOLUME_NAME secret: items: - key: VERSION path: FILENAME secretName: SECRET_LOOKUP_NAME

    Replace:

    • SERVICE with the name of your service.
    • IMAGE_URL with a reference to the container image, forexample, us-docker.pkg.dev/cloudrun/container/hello:latest. If you use Artifact Registry,the repository REPO_NAME mustalready be created. The URL has the shape LOCATION-docker.pkg.dev/PROJECT_ID/REPO_NAME/PATH:TAG
    • PATHwith the mount path of the volume andfilename of the secret. It must start with a leading slash, for example:/etc/secrets/dbconfig/password, where /etc/secrets/dbconfig/ is themount path of the volume, and password is the filename of the secret.
    • PROJECT_NUMBER with the project number for theproject the secret was created in.
    • SECRET_NAME with the secret name, e.g. mysecret.
    • VERSION with the secret version. Use latestfor latest version, or a number, for example, 2.
    • SECRET_LOOKUP_NAME with any name that has avalid secret name syntax (e.g. my-secret), it can be the same asSECRET_NAME
    • VOLUME_NAME with any name (e.g. my-volume), it can be the same asSECRET_NAME

View secrets settings

To view the current secrets settings for yourCloud Run service:

Console

  1. In the Google Cloud console, go to Cloud Run:

    Go to Cloud Run

  2. Click the service you are interested in to open the Service detailspage.

  3. Click the Revisions tab.

  4. In the details panel at the right, the secrets settingis listed under the Container tab.

gcloud

  1. Use the following command:

    gcloud run services describe SERVICE
  2. Locate the secrets setting in the returnedconfiguration.

Use secrets in your code

For examples on accessing secrets in your code as environment variables, referto the tutorial on end user authentication, particularly the sectionHandling sensitive configuration with Secret Manager.

Disallowed paths and limitations

Cloud Run does not allow you to mount secrets at /dev,/proc and /sys, or on their subdirectories.

If you are mounting secrets on /tmp and you are usingfirst generation execution environment,refer to the known issue onmounting secrets on /tmp.

Cloud Run does not allow you to mount multiple secrets at the same pathbecause two volume mounts cannot be mounted at the same location.

Overriding a directory

If the secret is mounted as a volume in Cloud Run, and the lastdirectory in the volume mount path already exists, then any files or folders inthe existing directory become inaccessible.

For example, if a secret called my-secret is mounted to path/etc/app_data, all the contents inside the app_data directory will beoverwritten, and the only visible file is /etc/app_data/my-secret.

To avoid overwriting files in an existing directory, create a new directory formounting the secret, for example, /etc/app_data/secrets, so that the mountpath for the secret is /etc/app_data/secrets/my-secret.

Configure secrets  |  Cloud Run Documentation  |  Google Cloud (2024)
Top Articles
Everything to Know About Bitcoin Pizza Day
Who owns Waste Management? WM Stock Ownership - TipRanks.com
Knoxville Tennessee White Pages
Cold Air Intake - High-flow, Roto-mold Tube - TOYOTA TACOMA V6-4.0
Wizard Build Season 28
Readyset Ochsner.org
Apex Rank Leaderboard
Elden Ring Dex/Int Build
Atrium Shift Select
Skip The Games Norfolk Virginia
Oppenheimer & Co. Inc. Buys Shares of 798,472 AST SpaceMobile, Inc. (NASDAQ:ASTS)
Elizabethtown Mesothelioma Legal Question
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Sony E 18-200mm F3.5-6.3 OSS LE Review
Gino Jennings Live Stream Today
Munich residents spend the most online for food
Tamilrockers Movies 2023 Download
Katherine Croan Ewald
Diamond Piers Menards
The Ultimate Style Guide To Casual Dress Code For Women
Site : Storagealamogordo.com Easy Call
Is Windbound Multiplayer
Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
Integer Division Matlab
Sandals Travel Agent Login
Horn Rank
Ltg Speech Copy Paste
Cognitive Science Cornell
Random Bibleizer
Craigslist Fort Smith Ar Personals
The Clapping Song Lyrics by Belle Stars
Poe T4 Aisling
R/Sandiego
Kempsville Recreation Center Pool Schedule
Rogold Extension
Beaver Saddle Ark
Log in or sign up to view
A Man Called Otto Showtimes Near Amc Muncie 12
Powerspec G512
Saybyebugs At Walmart
2007 Jaguar XK Low Miles for sale - Palm Desert, CA - craigslist
Miami Vice turns 40: A look back at the iconic series
Love Words Starting with P (With Definition)
Tlc Africa Deaths 2021
Youravon Com Mi Cuenta
Nope 123Movies Full
Kushfly Promo Code
Diario Las Americas Rentas Hialeah
Game Akin To Bingo Nyt
Marion City Wide Garage Sale 2023
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 5505

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.