Build Heroku apps automatically on every push to Github

651 Views Asked by At

I want to enable automatic builds on Heroku anytime I push to master branch on GitHub just like Heroku would do whenever I push to a branch that is connected to an app on their platform. Is there any way to achieve this?

1

There are 1 best solutions below

0
On

We can achieve this feat with GitHub Actions. We can automate builds on Heroku whenever a push is made hence no need to worry about deploying to Heroku via heroku-cli.

At the root of your application, create a .github folder.

Inside of the .github folder, create a workflow folder

lastly, in the workflow folder, create a yaml file. I'll call mine build-heroku-app.yml. So the file structure is going to look like so:

my-awesome-app
 - .github
    - workflow
       - build-heroku-app.yml

In build-heroku-app.yml file

# .github/workflows/build-heroku-app.yml // Just a comment
name: Build App on Heroku
on:
  push: // type of event
    branches:
      - master // name of branch we want to listen to for event

jobs:
  heroku-pull-request:
    runs-on: ubuntu-latest
    env:
      HEROKU_APP_NAME: my-awesome-app // name of app on heroku

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
          ref: ${{ github.ref_name }}

      - name: Login to Heroku
        uses: akhileshns/[email protected]
        with:
          heroku_email: ${{ secrets.HEROKU_EMAIL }} // Heroku email address
          heroku_api_key: ${{ secrets.HEROKU_API_KEY }} // Heroku API key
          heroku_app_name: ${{ env.HEROKU_APP_NAME }} // Declared above
          justlogin: true

      - name: Add Heroku remote
        run: heroku git:remote --app=${{ env.HEROKU_APP_NAME }}

      - name: Push to master branch app on Heroku
        run: git push heroku ${{ github.ref_name }}:master --force

Visit Github Actions Secrets Documentation to understand how secrets work in Github actions and how to create them.

You can view your Heroku API key by going to the API Key section on your Heroku Account settings page.