When you are using scripts to automate your builds (which you should do), you most probably want to keep the definition of your environment variables in an external file.

For example, in our builds, we are using multiple versions of Xcode and therefor need to set the proper DEVELOPER_DIR environment variable.

You can store these in a file as follows:

.env

DEVELOPER_DIR=/Applications/Xcode-v12.1.app/Contents/Developer

If you are using plain shell scripts, loading the variables is easy:

source .env
echo $DEVELOPER_DIR

To load them into a Makefile, you can use the following trick:

Makefile

include .env
export

build:
    @echo $(DEVELOPER_DIR)

Since we have some older build scripts which are based on Apache Ant, you can use the same file in Apache Ant by using the loadproperties task:

<?xml version="1.0" encoding="UTF-8"?>
<project name="builder" default="init" basedir=".">
    <target name="init">
        <loadproperties srcFile=".env" />
        <echo message="${DEVELOPER_DIR}" />
    </target>
</project>

If you want to read them from Python, you can do:

import os

def read_properties_from_file(path):
    return dict(l.rstrip().split('=', maxsplit=1) for l in open(path) if not l.startswith("#"))

def load_env_vars_from_properties_file(path):
    props = read_properties_from_file(path)
    for k, v in props.items():
        os.environ[k] = v

def main():
    load_env_vars_from_properties_file(".env")
        print(os.environ.get("DEVELOPER_DIR")

if __name__ == '__main__':
    main()

Voila, a neat way to have all your build scripts share the same environment variables.

Related Posts

  • Pretty-print JSON with Go
  • Define your own function in a Makefile
  • Generating slugs and redirects with Django
  • NetNewsWire TechNotes
  • Migrating your Wagtail site to a different database engine