0
votes

For the local development version of my Phoenix app, I would like to import some secret key data from a gitignore/ directory into config.exs. However, there are two things that I am not sure of:

  1. The data that I want to import is just string data - API key, secret key - do I need to define a module, or is there a simpler way to export string data?

  2. What is the appropriate import statement to use in config.exs, given the following file structure:

    MyApp/
      |
      - config/
      |    |
      |    - config.exs
      |
      - gitignore/
           |
           - api_key.exs
           - api_secret.exs
    

I'm familiar with how to accomplish this in Node, but I'm not sure about how to handle this in Phoenix.

To illustrate what I'd like to achieve, an example from one of my Node apps would look like:

index.js

const APISecret = process.env.API_SECRET || require('./gitignore/api_secret.js')
const APIKey = process.env.API_KEY || require('./gitignore/api_key.js')

where the required files look like

module.exports = 'RANDOM_KEY_HERE'

How should the data-to-be-ignored be formatted, and what is the appropriate way to access that data in config.exs?

2

2 Answers

0
votes

And answered my own question...

I added a dev.secret.exs file like so:

use Mix.Config

config :secret_things, 
  api_key: "NUMBERS",
  secret: "STUFF"

and then imported it into dev.exs with

import_config "dev.secret.exs"

and included dev.secret.exs in my .gitignore. Done.

0
votes

I would rather suggest using a .env file a the root of your project where you put all you dev environment variables (Add it to your .gitignore). It can look like this :

export API_KEY=some_api_key
export API_SECRET=some_api_secret

Then, in your config/config.exs, export these variables like this :

config :secret_things,
  api_key: System.get_env("API_KEY"),
  api_secret: System.get_env("API_SECRET")

The cool thing is that Phoenix automatically recognizes the .env file so the System.get_env/1 calls will work without anymore configuration.

You can then access these config variables in your app using Application.get_env(:secret_things, :api_key).

Important : Don't forget to source .env when launching your server or IEx in the current terminal tabs. You don't need to source it in a new tab.