Use environment variables from .env file in a Swift Package

Β·

1 min read

You can use Environment variables to pass secret information to a process at runtime instead of hardcoding that information during build time.

Multiple environment variables can be stored in a .env file but should not be committed to your repository.

In my example I want to pass MY_API_KEY variable with value 12345 to my Swift Package.

I will use ProcessInfo.processInfo.environment to access the value in my Swift Package .

public var myApiKey: String? {
    ProcessInfo.processInfo.environment["MY_API_KEY"]
}

But how to pass the environment value in the first place?

Pass a single environment variable

A test case with the following assertion ...

XCTAssertEqual(MySecrets().myApiKey, "12345")

... will fail because of the missing environment variable.

Once I set the individual environment variable and then run the tests ...

export MY_API_KEY='12345'
swift test

... the test will pass successfully.

Pass all environment variables from a .env file

I created the following .env file on my local machine.

MY_API_KEY=12345

I can pass all environment variables with the following utility script setenv.sh

#!/usr/bin/env bash

# Credit: https://zwbetz.com/set-environment-variables-in-your-bash-shell-from-a-env-file/

# Show env vars
grep -v '^#' .env

# Export env vars
export $(grep -v '^#' .env | xargs)

Only two commands are needed to pass all environment variables and run the tests.

source setenv.sh
swift test