DEV Community

MetaDave 🇪🇺
MetaDave 🇪🇺

Posted on

Running Heroku CLI commands in an Heroku application

TL;DR

With the Heroku CLI buildpack you can execute CLI commands against an Heroku application.

Setting it up

Add the build-pack and redeploy code.

There are some security credential things you have to do, but they're documented here.

Don't forget that you can connect to your app using heroku run bash -app my-application to run the credentials commands to get an API key to store as the HEROKU_API_KEY environment variable, and to do testing.

What you can do with it

You can run command lines from your Heroku application to do whatever can normally be done from the Heroku command line.

You can run these commands from within your application itself, or by using the Heroku Scheduler add-on, and you with the appropriate credentials you can do this from a different application.

For example:

  • Run a manual backup of your PostgreSQL database.
  • Rescale your dynos without using an add-on.
  • Restart your dynos at a particular time every day, before the working day begins.
  • Run rake tasks from within your system using a one-off run dyno of an arbitrary size.

We are currently using this to scale down one system overnight and scale it back up again before the working day starts, and for restarting another system's dynos at 5am local time.

We do this through a separate application, issuing the commands through the Heroku Scheduler add-on.

Running rake tasks from within your application

I'm very interested in experimenting with this idea.

We have a particular type of batch job that can vary hugely in workload:

  • So small that it can be executed synchronously by the application in a couple of seconds.
  • Too big to be synchronous, but fine for a Standard-2X worker dyno to handle in the background.
  • Too big for a Standard-2X, and too time-consuming to allow a worker to be tied up. Maybe a one hour job on a Performance-M dyno.

I can see us adopting logic that allows us to judge which of these approaches is required, and executing the appropriate logic.

Summary

That's it.

Top comments (0)