# Keeping secrets and API keys safe in ML pipelines



Learn how to secure ML pipelines using environment variables, API best practices, and runtime secret injection for GPU jobs and serverless inference.



Security · 2026-08-13 · 4 min read



Managing credentials in machine learning pipelines presents a unique challenge. Unlike traditional web applications, ML workflows often span multiple environments: local notebooks for experimentation, distributed clusters for training, and serverless endpoints for inference.

Hardcoding an API key for a vector database or a weights-and-biases logger might seem like a quick fix during a late-night debugging session, but it is a security debt that eventually comes due. Whether it’s an accidental Git commit or an exposed logging output, leaked secrets can lead to compromised data and runaway cloud costs.

In this guide, we will walk through practical strategies to keep your ML secrets safe, from local development to production deployment.

## 1. Never Hardcode: Use Environment Variables
The first rule of secret management is that secrets should never live in your source code. Instead, use environment variables. This decouples your configuration from your execution logic.

In Python, the standard way to handle this is via the `os` module or the `python-dotenv` library for local development.

```python
import os
from dotenv import load_dotenv

# Load variables from a .env file (local only)
load_dotenv()

# Access your keys
huggingface_token = os.getenv("HF_TOKEN")
database_url = os.getenv("DB_CONNECTION_STRING")

if not huggingface_token:
    raise ValueError("HF_TOKEN not found in environment variables.")
```

**Pro Tip:** Add `.env` to your `.gitignore` immediately. For extra safety, create a `.env.example` file with the keys listed but the values blank, so teammates know which variables they need to provide.

## 2. Secrets in the API Workflow
When working with infrastructure via an API, you often need to authenticate your local machine to the remote provider. For instance, when using the Podstack API, you should avoid passing keys as raw arguments in your shell history.

Instead, export the key to your shell session:

```text
Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key.
```

By using `export`, the key stays in memory for that terminal session and isn't written into script files that might be shared or version-controlled.

## 3. Injecting Secrets into GPU Jobs
When you move from local code to a remote GPU job, your environment variables need to travel with your code—but securely. You shouldn't bake them into a Docker image, as images are often stored in registries where others might have access.

The best practice is to inject secrets at runtime. When launching a job or a serverless inference endpoint, use the platform's native secret management system. This ensures that the secret is only decrypted and mounted into the container's environment when the GPU starts processing your task.

## 4. Scoping and Least Privilege
One of the most common mistakes in ML engineering is using a "Master Admin" key for every task. If your inference endpoint only needs to read from an S3 bucket, don't give it a key that has delete permissions.

*   **Read-only keys:** Use these for fetching datasets or model weights.
*   **Write-only keys:** Use these for logging metrics or uploading checkpoints.
*   **Environment-specific keys:** Use different API keys for `development`, `staging`, and `production`.

## 5. Handling Secrets in Serverless Inference
Serverless inference is particularly sensitive because endpoints are often public-facing. If your Python function calls an external API (like an LLM provider or a payment gateway), you must ensure the function itself doesn't log the secret to `stdout` or `stderr`.

ML frameworks often log the entire environment during a crash. To prevent this, wrap your secret-accessing logic in try-except blocks that sanitize the error message before it hits the logs.

## Secure ML Workflows on Podstack
Podstack is designed to make GPU orchestration seamless, and that includes security. Because Podstack bills by the second and scales your Python functions automatically, you need a way to ensure every spawned instance has the right credentials without manual intervention.

When using the Podstack API to deploy on-demand jobs or serverless endpoints, you can manage your secrets through the Podstack dashboard or via the API's secret vault.

For example, when deploying a GPU function:
1. Store your sensitive keys in the Podstack Secret Manager.
2. Reference them in your `podstack.yaml` or via the API flag `--env-secret HF_TOKEN=my_stored_secret`.
3. Podstack securely injects these into your Python GPU function at runtime.

This approach ensures that even if you are running hundreds of parallel inference jobs across a fleet of H100s, your `PODSTACK_API_KEY` and third-party tokens remain encrypted at rest and protected during execution.

By following these patterns—moving secrets to the environment, using runtime injection, and following the principle of least privilege—you can focus on optimizing your models without worrying about who might be watching your logs.
