Skip to contentcloudvix
cloudvix
GuideDevelopers & AI

Secrets and .env files when an assistant writes and deploys your code

Denys DunaievskyiFounder, Cloudvix
  • 14 min read
  • Published
  • LevelIntermediate
Guides
On this page

Key takeaways

  • A secret file that git never sees cannot be committed by mistake, by you or by an assistant that runs git add ..
  • A key that was ever committed and pushed counts as leaked.
  • Replace a key in this order, so that the service keeps working: create a new key at the provider, type it into /etc/myapp.env with sudoedit, recreate the service, check the log, and only then revoke the old key.

An assistant that writes and deploys code has to know where the secrets are, and that is exactly how keys end up in chats, in git history and in log lines. This guide keeps the real values in one place: a file on the server that only root can read. On your computer it makes git ignore secret files, searches the code and the whole history for keys that slipped in, and shows what to do when one did.

Before you start

You need a project in git on your computer. For the server steps you need an Ubuntu 24.04 server with a user with sudo and Docker Compose, as in the Docker guide. The commands marked "On your computer" run in the project folder. Nowhere do you type a secret into a chat: you type it into a file, yourself.

  • a project in git on your computer
  • an Ubuntu 24.04 server with Docker Compose and a user with sudo
  • the names of the keys the project uses (not their values)

The steps

Make git ignore secret files

A secret file that git never sees cannot be committed by mistake, by you or by an assistant that runs git add .. The first line adds a missing newline at the end of .gitignore, so that the new patterns do not stick to its last line. The second line adds three patterns: every .env file, except .env.example. git check-ignore -v shows which rule matches. It says nothing for a file that git already tracks, which is what the last pipeline looks for; it must print nothing.

On your computerbash
[ -s .gitignore ] && [ -n "$(tail -c1 .gitignore)" ] && echo >> .gitignore
printf '%s\n' '.env' '.env.*' '!.env.example' >> .gitignore
git check-ignore -v .env
git ls-files | grep -E '(^|/)\.env' | grep -v '\.example$'
Warning

If the last command prints a file, run git rm --cached FILE and commit. That stops tracking the file from now on, but it stays in the history, so continue with the history step, and treat the key as leaked if the repository was ever pushed.

Search the code for keys that slipped in

git grep searches the files that git tracks. The pattern looks for the shapes of common keys: sk- followed by a long string, ghp_ (a GitHub token), AKIA (an AWS key id) and the header of a private key. It finds shapes, not every secret: a password written as an ordinary word is not found, so read the code for words such as password and token too. Run it again after every larger change by an assistant.

On your computerbash
git grep -n -I -E '(sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{30,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)'

Search the history as well

Deleting a key from a file leaves it in older commits. The first command lists the commits that ever added a .env file. The second lists commits whose changes match the key shapes; it can take a while on a large repository. A hit means that the key is known to everyone who can read the repository.

On your computerbash
git log --all --oneline --diff-filter=A -- .env '*.env'
git log --all --oneline -G'(sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{30,}|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----)'
Warning

A key that was ever committed and pushed counts as leaked. Replace it at the provider first (see the last step), and clean the history afterwards if you want to. Rewriting history does not undo copies that others already have.

Publish the names, not the values

.env.example lists every variable with an empty value. It belongs in git: it tells you and your assistant which settings exist without exposing any. sed keeps the name of each NAME=value line (also when it starts with export), drops the value and skips comments and blank lines. The second command shows the result, which must contain names only. Only when it does, add the file to git with git add .env.example.

On your computerbash
sed -nE 's/^(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=.*/\2=/p' .env > .env.example
cat .env.example

Put the real values on the server

The first command creates an empty file that only root can read, before any secret is written into it. sudoedit opens it in your editor with the rights of root; type the values there yourself. Do not paste them into a chat and do not hand them to the assistant: this file is the one place where they are written down. The last command must show -rw------- and root root.

On the serverbash
sudo install -m 600 -o root -g root /dev/null /etc/myapp.env
sudoedit /etc/myapp.env
sudo ls -l /etc/myapp.env

Hand them to the program

In Compose, env_file: loads the file into the container when it is created. Docker reads it as root, so the file can stay unreadable for everyone else. The second block, run in the project folder on the server (where compose.yaml is), starts the service and prints only the names of the variables the container sees, not their values, so you can check that yours are there. For a program that runs as a systemd service, the same file works with EnvironmentFile=; the systemd guide shows how.

On the server · compose.yamlyaml
services:
  app:
    image: IMAGE
    env_file:
      - /etc/myapp.env
    restart: unless-stopped
On the serverbash
sudo docker compose up -d
sudo docker compose exec -T app env | cut -d= -f1 | sort
Warning

Anyone who can run Docker commands can read the values with docker inspect. Do not add users to the docker group who should not see the secrets.

Keep secrets out of commands and history

A secret given as a command-line argument is visible to every user on the server while the program runs, and it lands in the shell history. pgrep -af lists running programs whose command line matches the words; the grep -c line counts the lines of your shell history that match. The history file ~/.bash_history is written when a shell exits, so a command of the current session shows up there only after you log out. Both should be empty or zero, or show only things you recognise. If the first command prints a secret, do not copy it into a chat. Pass secrets through the settings file instead.

On the serverbash
pgrep -af -i 'token|password|secret|api[_-]?key'
grep -c -i -E 'token|password|secret|api[_-]?key' ~/.bash_history

Find forgotten copies on the server

Copies of .env files outlive their projects: a backup, an old folder, a file copied for a test. This looks in the usual places for files whose names start with .env, skips the example file and prints the owner and the mode of each with -ls. A file that is not needed any more should be deleted, and one that is needed should be owned by root with -rw-------; chmod 600 fixes the mode. 2>/dev/null hides the errors for folders that do not exist.

On the serverbash
sudo find /home /opt /srv /root -maxdepth 4 -name '.env*' -not -name '.env.example' -ls 2>/dev/null

Replace a leaked or old key

Replace a key in this order, so that the service keeps working: create a new key at the provider, type it into /etc/myapp.env with sudoedit, recreate the service, check the log, and only then revoke the old key. The last command shows the last lines of the service log from the last five minutes. If it shows errors about login or authorisation, the new value is wrong and the old key is still valid, so you can go back. Run the last two commands in the project folder on the server.

On the serverbash
sudoedit /etc/myapp.env
sudo docker compose up -d --force-recreate
sudo docker compose logs --since 5m app | tail -n 20

If something goes wrong

.env is already tracked by git

git check-ignore stays silent for tracked files. Run git rm --cached .env, commit, and then continue with the history step: the file is still in older commits.

The program does not see my variable

Check the names with the env | cut command of the Compose step. The lines in the file must be plain KEY=value without spaces around =, because Compose and systemd read the file themselves and do not run a shell. After editing the file, recreate the service: a restart alone does not reload an env_file.

git grep finds nothing, but I pasted a key into the code

It reads only the files that git tracks and matches only the shapes in the pattern. A file that is not added yet, a key of another shape or a password in plain words is not found. Read git status and git diff as well, and search for the variable names your project uses.

A key was pushed to a public repository

Assume that someone has copied it. Revoke or replace it at the provider now, before you touch git, and look at the provider's usage log for calls you did not make. Cleaning the history comes last and does not bring the key back under your control.

Questions people ask

Is a .env file on the server safe enough?

For one server it is a sensible middle: only root can read it, it is not in git and not in the image. It is still a file, not a vault: anyone with root or Docker access can read it, and it ends up in your backups unless you leave it out. Teams with many servers move to a secrets manager.

Should the assistant see my .env file?

Better not. Give it .env.example and the names of the variables, and let it write code that reads them. If it needs a real key to test something, create a separate key just for that, with the least rights and a spending limit where the provider offers one, and revoke it when the work is done.

How do I deploy without typing the secrets on the server every time?

You type them once, into the file, and the file stays on the server between deployments because it lives outside the project folder. A deployment replaces code and images and leaves /etc/myapp.env alone.

Where to go next

For the steps before a project goes live, use the twelve checks for an app an assistant built. To run the program as a service with its settings file, read systemd services, and to give an assistant a login that cannot change the server, see read-only access.

About the author

Denys Dunaievskyi

Founder, Cloudvix

Runs Cloudvix and is responsible for the guides published here.

Related guides

Your server is a few clicks away.

Choose the plan and the system in one order form; the location too, when there is more than one.

Create server