Managing Secrets in Cloud Deployments

Ma Mahalakshmi V Updated 19 Sep 2026
7 min read ·Lesson 194 of 224

Scope of This Lesson

Unit 23 covered secret management in general: what a secret manager is, why plaintext .env files are inadequate for anything beyond local development, and rotation strategies. This lesson does not repeat that material. Instead, it focuses specifically on how secrets are delivered to an application once it is running inside a cloud deployment — a container orchestrator, a serverless platform, or a managed compute service — where "just put it in a .env file" (Lesson 2's local-development pattern) is not how production secrets actually reach the process.

Two Delivery Mechanisms: Environment Variables and Mounted Files

Cloud platforms generally deliver secrets to a running container in one of two ways, and a well-written application should be able to accept either without code changes.

The first is environment variable injection: the platform's secret store (AWS Secrets Manager, Google Secret Manager, Azure Key Vault, or a platform-native equivalent) is configured to populate specific environment variables in the container's process environment before your application starts. From your code's point of view, this looks identical to the os.environ.get("OPENAI_API_KEY") pattern already used throughout this unit — the platform, not a .env file, is what put the value there.

The second is mounted secret files: the platform writes the secret's value to a file inside the container's filesystem, typically under a path like /run/secrets/openai_api_key or /var/secrets/openai_api_key, and your application reads the file's contents at startup. This approach is common in Docker Swarm and Kubernetes, and it has one advantage environment variables do not: some platforms can update the mounted file's contents in place when a secret rotates, without restarting the container, whereas environment variables are fixed at process start and require a restart to pick up a new value.

import os
from pathlib import Path


class SecretNotFoundError(RuntimeError):
    pass


def get_secret(name: str, file_env_var: str | None = None) -> str:
    """
    Resolve a secret by checking, in order:
    1. A direct environment variable named `name`.
    2. A file path given by `file_env_var`, if that env var is set
       (the common "_FILE" convention for mounted secrets).
    Raises SecretNotFoundError if neither source provides a value.
    """
    direct = os.environ.get(name)
    if direct:
        return direct

    if file_env_var:
        path_str = os.environ.get(file_env_var)
        if path_str:
            path = Path(path_str)
            if path.is_file():
                return path.read_text(encoding="utf-8").strip()

    raise SecretNotFoundError(
        f"Secret {name!r} not found via env var or file path in {file_env_var!r}"
    )


api_key = get_secret("OPENAI_API_KEY", file_env_var="OPENAI_API_KEY_FILE")

get_secret checks the plain environment variable first, then falls back to a file path named by a second environment variable following the _FILE suffix convention (OPENAI_API_KEY_FILE=/run/secrets/openai_api_key) that several secret-injection tools use. Writing it this way means the exact same application code runs correctly whether it is deployed on a platform that injects environment variables directly, one that mounts secret files, or a developer's laptop with a plain OPENAI_API_KEY set locally per Lesson 2 — the application does not need to know or care which mechanism supplied the value, only that get_secret resolved one.

.strip() on the file-read path matters in practice: files written by secret-mounting tools frequently include a trailing newline, and an API key with a trailing \n silently baked into an HTTP Authorization header produces confusing authentication failures that have nothing to do with the key itself being wrong.

Never Bake Secrets Into the Image

Lesson 3 already established that a Dockerfile should never contain ENV OPENAI_API_KEY=.... It is worth restating why this matters even more once you are in a cloud deployment context: images are typically stored in a container registry, often shared across a team or even across an organization's CI/CD pipeline. Anyone who can pull the image — including automated vulnerability scanners, CI runners, and anyone with registry read access — can extract any value that was baked in at build time, even from a layer that a later instruction appears to overwrite, because Docker image layers are cumulative and each one remains inspectable.

The correct pattern, consistent with everything in this unit so far, is that the image is secret-free and portable across environments, and the secret is supplied only at deployment time — via the platform's environment-variable injection or mounted-file mechanism described above — separately for each environment.

Rotation and Its Effect on Running Containers

A secret manager (Unit 23) makes rotating a compromised or expiring credential straightforward from the secret-store side. What is easy to overlook is the effect on containers that are already running with the old value.

If your secret is delivered as an environment variable, it was read once, at process start, and lives in that process's memory for as long as the process runs — updating the value in the secret store does not retroactively change what a running container sees. The container must be restarted (or replaced, in a rolling deployment) to pick up the new value. If your secret is delivered as a mounted file and your platform supports live updates to that file, some applications can be built to detect the change and reload — but this requires deliberate code to watch the file, which most applications do not implement, and defaulting to "restart on rotation" is simpler and safer than half-built hot-reload logic.

import logging

logger = logging.getLogger("myapp.secrets")


def load_api_key_or_exit() -> str:
    try:
        return get_secret("OPENAI_API_KEY", file_env_var="OPENAI_API_KEY_FILE")
    except SecretNotFoundError:
        logger.critical("OPENAI_API_KEY could not be resolved at startup; exiting")
        raise SystemExit(1)

Practically, this means your deployment process should treat "the secret was rotated" as an event that triggers a rolling restart of the affected service, not as something the running process is expected to notice on its own. Most managed platforms that integrate with a secret manager offer a way to trigger exactly this — a redeployment tied to the secret's version — precisely because environment variables are immutable for the lifetime of a process.

Least-Privilege Access to Secrets

A subtlety specific to cloud deployments is that the deployment platform itself needs permission to read the secret from the secret store in order to inject it into your container — this is a separate permission boundary from your application's own OpenAI API key permissions. The identity your deployment pipeline runs as (a service account, an IAM role, a managed identity, depending on the cloud provider) should be granted read access only to the specific secrets that specific service needs, not blanket access to every secret in the project or account.

This matters because a misconfigured deployment pipeline with overly broad secret access becomes a much larger blast radius if it is ever compromised — instead of exposing one service's API key, it exposes every secret the overly broad role could read. This is the same least-privilege principle Unit 23 applied to application-level access; here it applies one layer up, to the infrastructure that hands your application its secrets in the first place.

Note: The exact mechanism for granting a deployment identity access to a specific secret — IAM policies on AWS, service account bindings on Google Cloud, managed identity role assignments on Azure — is provider-specific and changes as each platform evolves its access-control model. Consult your provider's current documentation for the specific syntax; the least-privilege principle itself does not change across providers.

Common Mistakes

Logging the resolved secret value, even temporarily, during debugging. A line like logger.debug(f"using key: {api_key}") left in code can leak a live credential into a log-aggregation system that many more people have access to than the secret store itself. Never log secret values; log only whether one was successfully resolved (a boolean, a truncated fingerprint, or a source label).

Assuming a rotated secret takes effect immediately in running containers. As explained above, environment-variable-based secrets are fixed at process start; rotation without a corresponding restart leaves running instances using the old, potentially revoked value until they happen to restart on their own.

Granting the deployment pipeline's identity broad access to all secrets "to keep things simple." This turns a single compromised pipeline into an organization-wide secret exposure instead of a contained, single-service one.

Best Practices

Write secret-resolution code that accepts either environment-variable or mounted-file delivery, so the same application code deploys unchanged across platforms with different secret-injection mechanisms.

Treat secret rotation as a deployment event, not a runtime event — trigger a rolling restart of affected services when a secret changes rather than expecting a running process to detect it.

Apply least-privilege access at the infrastructure layer, scoping each deployment identity's secret-read permissions to only the specific secrets that specific service actually needs.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Managing Secrets in Cloud Deployments and get answers drawn from it.

Signed-in readers only.