CareerByteCode
ByteBlogby CareerByteCode

Secret Manager: Store Passwords and API Keys Safely

What you build: an app that reads rotated secrets at runtime, in your own Google Cloud account. Every step, command and screenshot explained for beginners.

Secret Manager: Store Passwords and API Keys Safely

✍️ Translate this blog into Hindi, Tamil or Telugu

In this lab you keep a password out of your code: you store it in Google Cloud Secret Manager, add new versions (rotation), give exactly one app permission to read it, and run a small Cloud Run app that receives it as an environment variable. You also see what happens when the app has no permission, and how to switch an old version off. You finish by deleting everything.

Who it is for: beginners who have ever put a password in a config file or a git repository and want the right way. Time: about 1 hour. Cost: free tier (Secret Manager gives 6 active secret versions and 10,000 access operations a month free; Cloud Run and Cloud Build stay inside their free tiers in this lab).

Every command below was run for real by the CareerByteCode Team on a fresh Google Cloud project, and every output and screenshot is the real result we got. We ran the commands from a terminal with the Google Cloud CLI; Cloud Shell in your browser has the same tools, so you can copy and paste each command there. The password in this lab (Lab-Pass-2026-v1) is a made-up value that only exists inside the lab. Never paste a real password into a blog, a chat or a terminal recording.

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterโ‚น499Build the projects →

Part A: secrets in plain English

A secret is any value that would hurt you if a stranger saw it: a database password, an API key, a private token. Putting it in code is dangerous because code is copied, shared and pushed to git, and git keeps everything forever.

How an app gets a secret
The secret stays in Secret Manager; IAM says who may read it; Cloud Run hands it to the app when it starts

The words you need:

  • Secret: a named box in Secret Manager, here db-password. Real-life example: a hotel room safe.
  • Version: one value of the secret. Adding a new value adds a new version; old versions stay until you disable or destroy them. latest always means the newest enabled version. Real-life example: changing the safe's code without changing the safe.
  • Service account: a robot account an app runs as. Our app runs as secret-reader.
  • Secret Accessor role (roles/secretmanager.secretAccessor): permission to read the value of a secret. Real-life example: the key card that opens the safe. We give it on ONE secret, not the whole project. This is called least privilege.
  • Rotation: replacing a secret with a new value on a schedule or after a leak.

Before you start

  1. A Google Cloud account (the free trial works) and a project with billing linked.
  2. Open Cloud Shell (the >_ icon at the top of the Google Cloud console).
  3. Save your project id (put your own id between the quotes):
export PROJECT_ID="your-project-id"
  1. Run every step from your home folder (cd ~). Steps that work on the app start with cd secret-demo themselves.

Part B: the lab

Step 1: turn on the APIs

Why: Secret Manager stores the secret; Cloud Run, Cloud Build and Artifact Registry are needed to build and run the small app.

gcloud config set project $PROJECT_ID
gcloud services enable secretmanager.googleapis.com run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com
gcloud services list --enabled --filter="name:secretmanager" --format="value(name)"
Updated property [core/project].
Operation "operations/acat.p2-PROJECT_NUMBER-4f1ef735-3901-4657-a246-16bed2e30be4" finished successfully.
projects/PROJECT_NUMBER/services/secretmanager.googleapis.com

Step 2: create a secret

Why: --data-file=- reads the value from the pipe, so the value never appears as a command argument (arguments can show up in process lists). --replication-policy=automatic lets Google choose where to keep copies.

printf "Lab-Pass-2026-v1" | gcloud secrets create db-password \
  --replication-policy=automatic --data-file=-
gcloud secrets list --format="table(name,createTime.date(%Y-%m-%d %H:%M))"
Created version [1] of the secret [db-password].
NAME         CREATED
db-password  2026-11-17 22:25

Step 3: read the secret back

Why: to check what you stored. In real life only people and apps that need the value should be allowed to do this.

gcloud secrets versions access latest --secret=db-password; echo
Lab-Pass-2026-v1
Create and read
Steps 1 to 3: the API is on, db-password exists, and version 1 reads back

Step 4: rotate it, add version 2

printf "Lab-Pass-2026-v2" | gcloud secrets versions add db-password --data-file=-
gcloud secrets versions list db-password --format="table(name,state,createTime.date(%H:%M:%S))"
Created version [2] of the secret [db-password].
NAME  STATE    CREATED
2     enabled  22:25:19
1     enabled  22:25:08

Step 5: old and new versions side by side

Why: to see that rotation does not overwrite anything. Version 1 is still there, and latest points to version 2.

echo "version 1: $(gcloud secrets versions access 1 --secret=db-password)"
echo "latest   : $(gcloud secrets versions access latest --secret=db-password)"
version 1: Lab-Pass-2026-v1
latest   : Lab-Pass-2026-v2
Versions
Steps 4 and 5: two enabled versions; latest is version 2

Step 6: create a service account for the app

Why: the app should not run with your own powers. It gets its own robot account, which at first has no access to anything.

gcloud iam service-accounts create secret-reader --display-name="Secret Manager lab app"
gcloud iam service-accounts list --filter="email:secret-reader*" --format="value(email)"
Created service account [secret-reader].
Service account email: secret-reader@your-project-id.iam.gserviceaccount.com
secret-reader@your-project-id.iam.gserviceaccount.com

Step 7: write a tiny app that uses the secret

Why: the app reads DB_PASSWORD from its environment. It prints only the length and the last 2 characters, so we can prove which version it got without showing the value. Do the same in your apps: never log a secret.

mkdir -p secret-demo && cd secret-demo
cat > main.py <<EOF
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        secret = os.environ.get("DB_PASSWORD", "")
        # never print a real secret: show only its length and the last 2 characters
        text = "DB_PASSWORD loaded: " + str(len(secret)) + " characters, ends with ..." + secret[-2:] + "\n"
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(text.encode())

HTTPServer(("", int(os.environ.get("PORT", "8080"))), Handler).serve_forever()
EOF
cat > Procfile <<EOF
web: python main.py
EOF
ls -1
Procfile
main.py
The account and the app
Steps 6 and 7: the secret-reader account and the app files (project id blurred)

Break it: deploy before giving access

We deploy now, on purpose, before the account may read the secret. --set-secrets=DB_PASSWORD=db-password:latest asks Cloud Run to put the latest version into the variable DB_PASSWORD. --source=. builds the container from the folder for you (Cloud Build does it in the background).

cd secret-demo
gcloud run deploy secret-demo --source=. --region=us-east1 --allow-unauthenticated \
  --service-account=secret-reader@$PROJECT_ID.iam.gserviceaccount.com \
  --set-secrets=DB_PASSWORD=db-password:latest 2>&1 | tail -3
Creating Revision..........failed
Deployment failed
ERROR: (gcloud.run.deploy) spec.template.spec.containers[0].env[0].value_from.secret_key_ref.name: Permission denied on secret: projects/PROJECT_NUMBER/secrets/db-password/versions/latest for Revision service account secret-reader@your-project-id.iam.gserviceaccount.com. The service account used must be granted the 'Secret Manager Secret Accessor' role (roles/secretmanager.secretAccessor) at the secret, project or higher level.
Deploy denied
Cloud Run refuses: Permission denied on secret for the revision service account

The error is clear: the revision's service account needs the Secret Accessor role "at the secret, project or higher level". Cloud Run checked the permission before it started the app, so a broken app never went live.

Fix it: give access to this one secret, then deploy again

We grant the role on the secret only, not on the project. The app can now read db-password and nothing else.

gcloud secrets add-iam-policy-binding db-password \
  --member="serviceAccount:secret-reader@$PROJECT_ID.iam.gserviceaccount.com" \
  --role="roles/secretmanager.secretAccessor" --format="table(bindings.role,bindings.members)"
📝⭐ Recommended by CareerByteCode · Certification examGoogle Analytics Certification (GA4) PracticeTake the examTake the exam →
Updated IAM policy for secret [db-password].
ROLE                                    MEMBERS
['roles/secretmanager.secretAccessor']  [['serviceAccount:secret-reader@your-project-id.iam.gserviceaccount.com']]
cd secret-demo
gcloud run deploy secret-demo --source=. --region=us-east1 --allow-unauthenticated \
  --service-account=secret-reader@$PROJECT_ID.iam.gserviceaccount.com \
  --set-secrets=DB_PASSWORD=db-password:latest 2>&1 | tail -3
curl -s $(gcloud run services describe secret-demo --region=us-east1 --format="value(status.url)")
Done.
Service [secret-demo] revision [secret-demo-00002-2vf] has been deployed and is serving 100 percent of traffic.
Service URL: https://secret-demo-PROJECT_NUMBER.us-east1.run.app
DB_PASSWORD loaded: 16 characters, ends with ...v2
Grant and deploy
Fix: the role is on the secret, the deploy works and the app says 16 characters, ends with v2

The app answers 16 characters, ends with ...v2: it got version 2, the latest.

POC: rotate to version 3 and prove the app picks it up

A running revision keeps the value it got at start. A new revision reads latest again. We add version 3, check the app, then roll out a new revision with a label change (no new code):

printf "Lab-Pass-2026-v3" | gcloud secrets versions add db-password --data-file=-
URL=$(gcloud run services describe secret-demo --region=us-east1 --format="value(status.url)")
echo "before: $(curl -s $URL)"
gcloud run services update secret-demo --region=us-east1 --update-labels=rotated=v3 2>&1 | tail -1
echo "after : $(curl -s $URL)"
Created version [3] of the secret [db-password].
before: DB_PASSWORD loaded: 16 characters, ends with ...v2
Service URL: https://secret-demo-PROJECT_NUMBER.us-east1.run.app
after : DB_PASSWORD loaded: 16 characters, ends with ...v3
Rotation proof
Before the new revision the app still has v2; after it, v3

Proof: before ends with v2, after ends with v3. The password changed without touching the code or the container image.

Switch an old version off

After a rotation, disable the old version so nobody can use it, even by accident. A disabled version can be enabled again; a destroyed version is gone for good.

gcloud secrets versions disable 1 --secret=db-password
gcloud secrets versions list db-password --format="table(name,state)"
gcloud secrets versions access 1 --secret=db-password
Disabled version [1] of the secret [db-password].
NAME  STATE
3     enabled 
2     enabled 
1     disabled
ERROR: (gcloud.secrets.versions.access) FAILED_PRECONDITION: Secret Version [projects/PROJECT_NUMBER/secrets/db-password/versions/1] is in DISABLED state.
Disable version 1
Version 1 is disabled and reading it fails with DISABLED state

Clean up (delete everything)

Why: each active version counts toward the free 6; the service, the account, the images that --source created and the source bucket should all go.

gcloud run services delete secret-demo --region=us-east1 --quiet 2>&1 | tail -1
gcloud secrets delete db-password --quiet 2>&1 | tail -1
gcloud iam service-accounts delete secret-reader@$PROJECT_ID.iam.gserviceaccount.com --quiet 2>&1 | tail -1
gcloud artifacts repositories delete cloud-run-source-deploy --location=us-east1 --quiet 2>&1 | tail -1
for B in $(gcloud storage buckets list --format="value(name)"); do gcloud storage rm --recursive gs://$B --quiet > /dev/null 2>&1; done
echo "services: $(gcloud run services list --format="value(name)" | wc -l), secrets: $(gcloud secrets list --format="value(name)" | wc -l), buckets: $(gcloud storage buckets list --format="value(name)" | wc -l), repositories: $(gcloud artifacts repositories list --location=us-east1 --format="value(name)" 2>/dev/null | wc -l)"
Deleted service [secret-demo].
Deleted secret [db-password].
deleted service account [secret-reader@your-project-id.iam.gserviceaccount.com]
Deleted repository [cloud-run-source-deploy].
services: 0, secrets: 0, buckets: 0, repositories: 0
Clean up
0 services, 0 secrets, 0 buckets, 0 repositories

FAQ

Is an environment variable safe? It is much safer than code or git, because the value is never stored in your image or repository. For extra safety you can mount the secret as a file instead (--set-secrets=/secrets/db=db-password:latest), so it does not appear in the environment.

Why did the running app not change when I added version 3? Environment variables are filled once, when an instance starts. A new revision (or a new instance) reads latest again.

**Should I use latest or a version number?** latest makes rotation easy. A fixed number (db-password:2) gives you full control: nothing changes until you deploy.

What is the difference between disable and destroy? Disable can be undone; destroy deletes the value forever. Disable first, wait, then destroy.

Who can see the secret value? Anyone with the Secret Accessor role on the secret or the project, plus project Owners. Check with gcloud secrets get-iam-policy db-password.

Can I keep API keys from other companies here? Yes, any text or file up to 64 KiB per version.

Troubleshooting

You seeWhyFix
Permission denied on secret ... for Revision service accountThe app account has no Secret Accessor roleRun the Fix step: grant the role on the secret
Service account ... does not exist right after creating itNew accounts take a few seconds to appear everywhereWait 10 to 30 seconds and run the command again
is in DISABLED stateYou read a disabled versionUse another version, or gcloud secrets versions enable 1 --secret=db-password
The app still shows the old valueRunning instances keep the value they started withRoll out a new revision (Step POC)
An error that the secret already existsYou ran Step 2 twiceUse gcloud secrets versions add to add a value
API [secretmanager.googleapis.com] not enabledThe API is offRun Step 1

What next

Prepared by the CareerByteCode Team from our tested lab, with AI help for the write-up.

Read next →Google Cloud IAM for Beginners: Roles, Members and Least Privilege⏱ 10 min

⭐ Keep learning with CareerByteCode

Hand-picked to go deeper on this topic
News, guides and updates from the CareerByteCode team
🏅 Contributor writer

The CareerByteCode team writes about what is new on careerbytecode.in: courses, labs, exams, events and the community, which is free to join for influencers and content creators in tech.

Get CareerByteCode Team's next blog by email

One email a week when they publish. Add the weekly Best of ByteBlog too. No spam, unsubscribe with one click.

We email you once to confirm. By subscribing you agree to the privacy policy.

💬 Comments (0)

Top · Newest

Sign in to comment

More from CareerByteCode Team

🧪⭐ Recommended by CareerByteCode · ByteLabs project bundleCloud and DevOps Realtime Starterโ‚น499Build the projects →