How to run seeds.exs for Elixir/Phoenix App?

Hi Fellow Frequent Flyers! :wave:

We are trying to deploy a Phoenix app to Fly.io that requires some data to be initialised in the PostgreSQL DB.

We followed the Elixir getting started guide: Deploy an Elixir Phoenix Application and have done a bunch of googling/debugging and come to the conclusion that the /priv/repo/seeds.exs file is not available during the mix release:man_shrugging:

So my/our question is: has anyone else faced this issue and how can we seed data into a freshly deployed Phoenix App? (or is there a generic approach to seeding data in any programming language/framework that we can adapt…?) :question:

Thanks! :pray:

1 Like

Hello!

Yes, the seeds aren’t auto-run. That’s a general situation with Elixir releases. Typically, you only want them run once. I like to write my seeds so they can be run multiple times (ie idempotent). However, it’s unique to each project and that means the solution is as well.

What I do is put the seeds into a regular module like MyApp.GlobalSetup. Then define a function like seed/0 or populate_pick_list_options or whatever.

Then SSH into an instance and run it in an IEx shell. Ex: MyApp.GlobalSetup.seed.

I hope that helps!

6 Likes

@brainlid that’s very helpful/insightful. thanks very much. Will try and implement this tonight. :+1:

2 Likes

@brainlid just to clarify, write the seed logic into a module, so not using seeds.exs or similar at all, i.e. don’t run the existing seed script from the new module?

Indeed. What worked for us was following @brainlid’s advice and shifting the database initialisation code out of seeds.exs to a new file lib/init.ex and then invoking it from priv/repo/seeds.exs on localhost.

We didn’t run the seeds.exs on Fly.io rather we created an /init endpoint+controller that would run the Init.main/0 function idempotently. It’s probably more steps than a typical app would require but it meant we could have a nice initialisation (“status”) page for our app:

Bottom line: @brainlid’s advice worked and we managed to overcome our Fly.io deployment block.

(Thanks again Mark!)

2 Likes

Nice, thanks for the response.

Thanks for sharing your process! I like the dev status page too!

2 Likes