You have a custom mix task for your project. In that task, you want to interact with your project’s Ecto Repo.

When you do, you get the following error…

$ mix my_custom_task
** (ArgumentError) repo MyProject.Repo is not started, please ensure it is part of your supervision tree

The Fix

Import Mix.Ecto. It includes “Conveniences for writing Mix.Tasks in Ecto.”

Checkout the very readable source here.

The most relevant function for this scenario is ensure_started/2.

Example Task

Here’s an example task that puts it to use.

defmodule Mix.Tasks.MyCustomTask do
  use Mix.Task
  # setup so we can use Ecto in a mix task
  import Mix.Ecto

  @shortdoc "Description of my_custom_task"

  def run(_) do
    # start the Repo for interacting with data
    ensure_started(MyProject.Repo, [])

    # code that uses MyProject.Repo


Want More Examples?

If you’d like to see more examples of working with an Ecto Repo in your mix tasks, check out the elixir-ecto project’s mix tasks used for creating the existing tasks like mix ecto.create.