Skip to content

Instantly share code, notes, and snippets.

@hectorperez
Last active March 18, 2022 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hectorperez/34c37bc5c4496669264d686036252e07 to your computer and use it in GitHub Desktop.
Save hectorperez/34c37bc5c4496669264d686036252e07 to your computer and use it in GitHub Desktop.
How to run a mix task on Gigalixir using distillery #Elixir #Phoenix
# Run task in development:
mix whatever
# Run task in staging/production:
gigalixir run bin/my_app whatever --app_name=...
# /my_app/rel/config.exs
...
release :my_app do
set version: current_version(:my_app)
set applications: [
:runtime_tools
]
set commands: [
migrate: "rel/hooks/pre_start/migrate.sh",
seed: "rel/commands/seed.sh",
whatever: "rel/commands/whatever.sh"
]
end
# my_app/mix/tasks/whatever.ex
defmodule Mix.Tasks.Whatever do
@moduledoc "Run in dev: `mix whatever; run in staging/prod: gigalixir run bin/my_app whatever --app_name=...`"
use Mix.Task
@start_apps [
:crypto,
:ssl,
:postgrex,
:ecto,
:ecto_sql # If using Ecto 3.0 or higher
]
@repos Application.get_env(:my_app, :ecto_repos, [])
# Instead of calling `Mix.Task.run("app.start")` at the beginning of `run()`, use `start_services()` and `stop_services()` like in `release_tasks.ex`
@shortdoc "Whatever this does"
def run(_) do
start_services()
actual work
stop_services()
end
defp start_services do
IO.puts("Starting dependencies..")
# Start apps necessary for executing migrations
Enum.each(@start_apps, &Application.ensure_all_started/1)
# Start the Repo(s) for app
IO.puts("Starting repos..")
# pool_size can be 1 for ecto < 3.0
Enum.each(@repos, & &1.start_link(pool_size: 2))
end
defp stop_services do
IO.puts("Success!")
:init.stop()
end
end
# /my_app/rel/commands/whatever.sh
#!/bin/sh
release_ctl eval --mfa "Mix.Tasks.Whatever.run/1" --argv -- "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment