phil_columns-ex icon indicating copy to clipboard operation
phil_columns-ex copied to clipboard

Running seeds tasks in a release/production

Open sh41 opened this issue 4 years ago • 1 comments

Thanks for the package, it's already been really useful.

When we use mix release to deploy to production the resulting package no longer has mix itself available for running tasks, so the example in the README doesn't work if you use releases in production.

Taking inspiration from the examples in the README and in the Ecto.Migrator documentation at https://hexdocs.pm/ecto_sql/Ecto.Migrator.html#module-example-running-migrations-in-a-release I've created a seeder task like this:

defmodule MyApp.Deployment.Seeder do
  import Ecto.Migrator, only: [migrations_path: 2, with_repo: 2]

  @app :my_app

  def seed(opts \\ [], seeder \\ &PhilColumns.Seeder.run/4) do
    load_app()
    # set env with current_env/0 overwriting provided arg
    opts = Keyword.put(opts, :env, current_env())
    opts = Keyword.put(opts, :tags, [])

    opts =
      if opts[:to] || opts[:step] || opts[:all],
        do: opts,
        else: Keyword.put(opts, :all, true)

    opts =
      if opts[:log],
        do: opts,
        else: Keyword.put(opts, :log, :info)

    opts =
      if opts[:quiet],
        do: Keyword.put(opts, :log, false),
        else: opts

    for repo <- repos() do
      {:ok, _, _} = with_repo(repo, &seeder.(&1, migrations_path(&1, "seeds"), :up, opts))
    end
  end

  defp current_env do
    ## Add this to config/config.exs:
    ##
    ## config :my_app, env: config_env()
    Application.fetch_env!(@app, :env)
  end

  defp repos do
    Application.fetch_env!(@app, :ecto_repos)
  end

  defp load_app do
    Application.load(@app)
  end
end

which can be run from the release like this:

bin/my_app eval "MyApp.Deployment.Seeder.seed"

Does this sound like the right approach? If so, would this be a useful addition to the README? Happy to provide a PR if it's like to useful to someone.

sh41 avatar Mar 11 '21 08:03 sh41

I do something very similar to this. IT would be a nice addition to the README. I will accept a PR if you submit one. Thanks!

midas avatar Mar 13 '21 18:03 midas