Using Mix.env pre-start release tasks

I need to seed my database with different values based on the environment I’m deploying to. This is pretty straight forward when my application is running, but I need to run these scripts in my pre-start hooks. I’m currently using something like this.

I can’t quite figure out how to detect the environment during this phase. Anyone have experience with this?

Since Mix is a build task, not a deploy task, the concept of a Mix environment doesn’t exist in a release. You would need to set the release configuration based upon the Mix (or other) environment at build time. Maybe something like this is config.exs:

config :my_app,
  seed_module: seeder(Mix.env)

def seeder(:dev), do: Seeder.Dev
def seeder(:prod), do: Seeder.Prod

Or better still refactor out to dev.exs and prod.exs. Then in your pre-start scripts you would do:

seeder = Applcation.get_env(:my_app, :seed_module)
seeder.do_seeding_stuff

The point being "Mix.env()` is only a build time thing, not a release time thing.

4 Likes

Word to the wise, application configuration is only available to applications included in your distillery config.exs file.

I had initially set the deployment environment in a config file for an applications shared as a dependency across my umbrella projects. The obvious play from a DRY standpoint.

config :common,
  env: Mix.env()

This didn’t work. It was coming up as nil when I accessed it in my pre_start hook scripts. I had to put the variable into a config file that was included in an application in my release, explicitly.