Hiding Secrets From Git in SwiftPM | by Cihat Gündüz | Feb, 2022

Modularise your apps

Cihat Gundüz
Photo by FLY:D on Unsplash

I’m sure there’s no single “best” answer to this and others may have smarter ideas than mine. But I like to keep things simple and I also like to use basic features because I know them well & I expect other developers to understand them quickly if needed. Plus I can be sure they’re future-proof.

  1. Let developers duplicate it , remove the .sample extension & add values
  2. Ignore the secrets.json file via .gitignore so it’s never checked in
  3. Provide a simple struct conforming to Decodable to read the secrets

First, let’s add the secrets.json file to our project. As there’s going to be a corresponding secrets.json.sample and a Secrets.swift file, I opt for creating a folder Secrets first, then I create an empty file which I name secrets.json and I add a simple JSON dictionary structure with two keys:

The `secrets.json` file with two actual secrets, added to the project.
The `secrets.json` entry in the `.gitignore` files end. File opened in Atom text editor.
The `secrets.json.sample` file without any secret values, added to the project.
The `secrets.json` file added as resource in `Package.swift` manifest file.
Xcode warns when it finds resource files that are not declared in the Package manifest.
The `exclude` entry in the Package manifest file to silence the warning.

Now that we have our secrets.json resource file, let’s access it in Swift.

let subscriptionKey = ""
let subscriptionKey = try! Secrets.load().microsoftSubscriptionKey

Now that I’m loading secrets from a JSON file, I also want to configure my GitHub CI pipeline to use my secret keys when running the tests on CI.

Adding the secrets to my GitHub repository.
The full test GitHub Action CI job.
Want to Connect?Follow me also on 👾 Twitch, on 🎬 YouTube and on 🐦 Twitter.

Leave a Comment