How to Store API Keys on Server: .env, Permissions, systemd

· 0x.cloud Team

How to Store API Keys on Server: .env, Permissions, systemd

To store API keys on server safely, put them in a .env file with 600 permissions that never enters git, and for systemd services use EnvironmentFile= or, better, LoadCredential=. Keys never go in source code, in a committed docker-compose.yml, or in your shell history. Give each server its own key with minimal permissions and a spending limit, so a leak means revoking one key and the limit caps the damage.

Below are ready-to-use setups for Ubuntu 24.04 and Debian 12, using OpenAI, Anthropic and 0x.cloud API keys as examples.

On this page: rules · .env · EnvironmentFile · LoadCredential · agents · leak check · mistakes

Five rules to store API keys on server

  1. Not in code, not in git. Add .env to .gitignore before the first commit.
  2. Mode 600. Only the owner can read the file.
  3. One key per server. If it leaks, you revoke one key, not all of them.
  4. A spending limit at the provider. In the Anthropic Console that's a workspace spend limit; in OpenAI, a project budget. Check whether the limit blocks requests or only sends an alert.
  5. Not in shell history. Type keys with read -s or an editor, not export KEY=... on the command line.

Option 1: a .env file with 600 permissions

Create the file already locked down, so it's never world-readable even for a second:

cd ~/mybot
install -m 600 /dev/null .env        # empty file, mode 600
nano .env
# .env: one variable per line, no spaces around =
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
TELEGRAM_BOT_TOKEN=123456:ABC...
echo ".env" >> .gitignore
ls -l .env      # -rw------- 1 bot bot ... .env

Loading it in your app:

  • Python: pip install python-dotenv, then from dotenv import load_dotenv; load_dotenv() and read os.environ["OPENAI_API_KEY"].
  • Node.js 20.6+: no library needed: node --env-file=.env app.js (Node.js docs).
  • Docker Compose: env_file: .env on the service. Don't copy .env into the image.

Option 2: systemd EnvironmentFile

If your bot or agent runs as a service (see create a systemd service), keep the keys outside the code directory:

sudo mkdir -p /etc/mybot
sudo install -m 600 -o root -g root /dev/null /etc/mybot/env
sudo nano /etc/mybot/env           # same KEY=value lines

In the unit:

[Service]
User=bot
EnvironmentFile=/etc/mybot/env
ExecStart=/home/bot/mybot/venv/bin/python /home/bot/mybot/bot.py
sudo systemctl daemon-reload
sudo systemctl restart mybot

systemd reads the file as root before starting the process, so the bot user needs no access to it, and the app can't accidentally print or overwrite it.

Option 3: LoadCredential keeps keys out of the environment

The systemd.exec docs say it plainly: environment variables aren't suitable for secrets, because they're exposed over D-Bus and inherited by child processes. For valuable keys use LoadCredential= (systemd 247+, available on Ubuntu 24.04 and Debian 12):

sudo install -m 600 -o root -g root /dev/null /etc/mybot/openai.key
sudo nano /etc/mybot/openai.key    # just the key, one line
[Service]
User=bot
LoadCredential=openai:/etc/mybot/openai.key
ExecStart=/home/bot/mybot/venv/bin/python /home/bot/mybot/bot.py

Read it from the app:

import os, pathlib
key = (pathlib.Path(os.environ["CREDENTIALS_DIRECTORY"]) / "openai").read_text().strip()

Only the service's user and root can see the credentials directory, and systemd keeps it in non-swappable memory where possible.

Keys for Claude Code and Codex on a server

Terminal agents run as your user, so keep their keys in your home directory:

install -m 600 /dev/null ~/.config/agent.env
nano ~/.config/agent.env           # ANTHROPIC_API_KEY=..., OX_API_KEY=...
echo 'set -a; . ~/.config/agent.env; set +a' >> ~/.bashrc

set -a exports every variable in the file to new shells. For Codex it's simpler to log in once, piping the key through stdin so it never hits history: printenv OPENAI_API_KEY | codex login --with-api-key (per the Codex docs). Full walkthroughs: Claude Code on a server and Codex CLI on Ubuntu.

Model keys belong to you. On 0x.cloud the For AI agents image already has Node, Python, Git, tmux and Docker; install Claude Code or Codex if they're missing, and add your own keys. An s2-4 (2 vCPU, 4 GB RAM, $15.99/mo) fits a coding agent; see VPS for AI agents. Try it hourly first, about $0.109520 an hour, and get the unused balance back when you delete it.

A 0x.cloud API key for your agent

The 0x.cloud API follows the same rules, with protection built in. Keys start with 0x_live_ and are shown once, so put yours in agent.env as OX_API_KEY right away. Each key has permissions, a monthly spend cap, an expiry date and an IP allow list.

Heads up: a new key defaults to servers.*, which means it can delete servers (servers.delete) and run commands on them as root (servers.exec). For an agent that only checks prices and creates servers, keep servers.read and servers.create and remove the rest. Only the owner can change permissions and limits, in the dashboard; the key can't raise its own.

The spend cap only blocks new paid actions: past the cap, the API returns 402 key_spend_limit_reached. Hourly servers that already exist keep billing and count toward the cap, so delete test servers or create them with ttl_hours (an auto-delete timer). In an MCP client you can skip the key entirely and sign in with OAuth, where you pick the permissions, cap, expiry and "own servers only" yourself.

How to check for leaked keys

grep -rnE 'sk-[A-Za-z0-9_-]{20,}' ~/mybot --exclude=.env   # keys in code
git -C ~/mybot log -p | grep -nE 'sk-[A-Za-z0-9_-]{20,}'   # keys in git history
grep -nE 'sk-|0x_live_|API_KEY=' ~/.bash_history             # keys in shell history
sudo find ~ /etc/mybot \( -name '*.env' -o -name '*.key' \) -exec ls -l {} +   # file permissions

The sk- pattern matches OpenAI and Anthropic keys, and 0x.cloud keys start with 0x_live_. Swap in other providers' prefixes as needed. Every file in the last command's output should show -rw-------.

Common mistakes

Mistake Risk Fix
.env committed to the repo anyone with repo access sees the key revoke the key, add .env to .gitignore
mode 644 every user on the server can read it chmod 600 .env
export KEY=... in the terminal key stays in ~/.bash_history use read -s or an editor
Environment=KEY=... in the unit units are world-readable, value shows in systemctl show move to EnvironmentFile= or LoadCredential=
key printed in startup logs lands in journalctl log only the last 4 characters
.env inside the web root nginx may serve it by URL keep it outside the web server root

Prompt for your AI agent

Prompt for an AI agent

Audit my server for leaked keys: find .env and *.key files, show their permissions and fix them to 600, make sure .env is in .gitignore in every repo under ~, and search code and git history for strings that look like API keys. Never print the keys themselves, only their last 4 characters.

It's best to practice on a clean server. The agent can create one itself if its key has servers.create:

Prompt for an AI agent

Create a test s1-1 server on 0x.cloud with Ubuntu 24.04, hourly billing and ttl_hours 3. Run a dry_run first, show me the exact price and wait for my OK.

Three hours of s1-1 cost about $0.09, and the server deletes itself after 3 hours.

FAQ

Where should I store API keys on a server? In a .env file outside git and outside any web root, with 600 permissions, or in /etc/yourapp/ loaded by systemd. Never in source code or in a committed docker-compose.yml.

Are environment variables safe for secrets? For most bots and agents they're fine if the file holding them is mode 600. The systemd docs warn that unit environment variables are visible over D-Bus and inherited by child processes, so use LoadCredential for high-value keys.

What do I do if a key ends up in git or a log? Revoke it with the provider and issue a new one right away. Deleting the commit isn't enough because the key may already be copied. Then rewrite history or recreate the repo.

Does 0x.cloud see my model API keys? Your model keys are yours: you put them on the server yourself, and the For AI agents image ships without any. For the 0x.cloud API, create a separate key: it defaults to servers.*, so remove the permissions you don't need and set a monthly spend cap.

Can I practice this on a throwaway server? Yes. On 0x.cloud an hourly s1-1 in Warsaw costs about $0.030750 an hour. Set up the keys, test, delete the server, and the unused balance comes back. If you break something, an OS reinstall is $0.