Skip to content

Running seeds tasks in a release/production #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
sh41 opened this issue Mar 11, 2021 · 1 comment
Open

Running seeds tasks in a release/production #8

sh41 opened this issue Mar 11, 2021 · 1 comment

Comments

@sh41
Copy link

sh41 commented Mar 11, 2021

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.

@midas
Copy link
Owner

midas commented Mar 13, 2021

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!

sh41 added a commit to sh41/phil_columns-ex that referenced this issue Mar 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants