How To Use `dotenv` Files In Production (Don't)

  • Tuesday, Oct 11, 2022

Don’t use .env files in prod

Why?

  • Getting the environment setup for an application is a long-solved problem that is well handled by all deployment systems
  • Getting the .env file onto the specific environment can only make the deployment harder
  • Making the build for each environment have a different .env file means you’re testing on a different version that you are deploying to production, which is not ideal

Oh, you have a great reason? Well let’s go over them…

Objections

The variables HAVE to be set

Then check and return an error message.

from dotenv import load_dotenv

def setUp():
    # Testing requires ENV Vars set
    load_dotenv()
    requiredVars = [ "PGPASSWORD", "PGHOST", "PGDB", "PGUSER" ]
    allGood = True
    for i in requiredVars:
        if not i in environ:
            allGood = False
            print(F"ERROR running tests: {i} must be defined in the environment")

    if not allGood:
        sys.exit(2)

setUp()

We’re deploying by copying files to a computer and running

How are you starting it? If you’re using systemd, then use the correct method:

[Unit]
Description=OpenBSD Secure Shell server
Documentation=man:sshd(8) man:sshd_config(5)
After=network.target auditd.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run

[Service]
####
# The Environment File
EnvironmentFile=-/etc/default/ssh
#####

ExecStartPre=/usr/sbin/sshd -t
ExecStart=/usr/sbin/sshd -D $SSHD_OPTS
ExecReload=/usr/sbin/sshd -t
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartPreventExitStatus=255
Type=notify
RuntimeDirectory=sshd
RuntimeDirectoryMode=0755

[Install]
WantedBy=multi-user.target
Alias=sshd.service

Our deployment runs an agent on the running machine that we interactively send run commands to

Why? Don’t drink the AWS CodeDeploy suicide juice. Deploy this thing for real.

We enjoy making various version of containers and then changing the image name in Kubernetes/Swarm/ECS

If you can change that, you can change the environment directly and only make 1 image.

We don’t know how to do any of these

Call Me