Creating user-defined tasks, or scripting, with config in Phoenix

I want to be able to generate some files such as “nginx config”, “systemd service” and others. Some of the files will be used in the production environment. All that, I guess, should work similar to how Rake tasks work in Ruby.

I may want to run such tasks locally as well as remotely.
It should have its own config files. However, the standard, in /config directory, Phoenix config files could be reused, because I don’t want to copy-paste data accross config and have to maintain its consistent.

For instance:
I want to generate nginx config for my application. I’d want to be able to load Phoenix IEX shell and say something like:

> MyApp123.UserTasks/generate_nginx_config(arg1, arg2, arg3)

and that’d produce a file in, say, rel/var/nginx_my_site123.conf

And the same way it’d work for other tasks:

  • load a Phoenix (not simply Elixir shell) shell
  • run a task I’ve written
  • get a result – as a physical file, text output, something else…

How to approach this?


I won’t want to use any additional, external dependencies unless they’ll be absolutely necessary.

You can take a look at how many of the mix tasks like phx.new are written: phoenix/installer at master · phoenixframework/phoenix · GitHub

It essentially boils down to a bunch of EEx templates + some code to trigger them from a function and handle related concerns like config. I personally like EEx.function_from_file and EEx.function_from_string: EEx — EEx v1.13.4

You can write the results to files with plain old File.write.

Tangentially, this is not a thing. iex is iex, Phoenix does not ship its own shell. You can load a mix project into iex that has phoenix in it, but it’s still just an iex shell.

Those tasks don’t read a config file. I need that. How?

Add @requirements ["app.config"] in the module body of your task.

5 Likes