Skip to content

Running migrations

A very common task as part of deployment is the ability to run migrations, or other automated prep work prior to starting the new version. There are a number of approaches I’ve seen people take using the primitives Distillery provides, however my favored approach is one that I have not seen people use yet, and it surprises me because it is so easy and feels much more comfortable to use.

The approach is the following:

  • Define a module which will execute the migrations, this is a common requirement of all approaches to running migrations in a release.
  • Define a custom command which will execute this module for you without requiring that you type the module, function, and arguments yourself.

Migration module

The following code is an example of a module which will run your Ecto migrations:

Warning

Remember to put this file under lib, as it must be compiled with the rest of your application, otherwise the code will not be available in the release, and the migrate command will fail.

Custom command

Create the following shell scripts at rel/commands/:

  • rel/commands/migrate.sh
1
2
3
#!/bin/sh

release_ctl eval --mfa "MyApp.ReleaseTasks.migrate/1" --argv -- "$@"
  • rel/commands/seed.sh
1
2
3
#!/bin/sh

release_ctl eval --mfa "MyApp.ReleaseTasks.seed/1" --argv -- "$@"

For more info on the shell API look at the Shell Scripts document.

Tying it all together

Now that we have our custom command and migrator module defined, we just need to set up our config appropriately in the rel/config.exs file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
...

release :myapp do
  ...
  set commands: [
    migrate: "rel/commands/migrate.sh",
    seed: "rel/commands/seed.sh",
  ]
end

...

Now, once you’ve deployed your application, you can run migrations/seeds with bin/myapp migrate and bin/myapp seed.

Thoughts

There are other approaches that may make more sense for your use case, for example, automatically running migrations by defining a pre-start hook which does basically the same thing as above, just in a hook instead of a command. You can even define the command, and execute the command as part of the hook, giving you the flexibility of both approaches.

Custom commands give you a lot of power to express potentially complex operations as a terse statement. I would encourage you to use them for these types of tasks rather than using the raw rpc and eval tasks!