Recently I discovered the power of using Github workflows to automate dev ops. Github actions allows us to customise and execute workflows from right inside the repository. 

The Github Marketplace is full of pre written actions, we can choose from to implement into a workflow allowing us to create complex development workflows with ease!

Automated Deployment

Automating deployments is super simple with Github actions. Automatically exporting your app from a development environment and deploying the app into your production environment can be achieved by simply adding a YAML config to your workflows directory!

Here's how to do it.

Github Secrets

First we need to understand how Github secrets are going to help us achieve our deployment script. As described by Github, Secrets are encrypted environment variables that you create in an organization, repository, or repository environment. The secrets that you create are available to use in GitHub Actions workflows. GitHub uses a libsodium sealed box to help ensure that secrets are encrypted before they reach GitHub and remain encrypted until you use them in a workflow.

Adding the Required Secrets

In your repositories settings, you will find the Secrets tab. In here we can add key value pair secrets for our repository.

Github Actions interface

From here we can start to add each of our required fields which are:

  • HOST - The I.P/Domain of the server we are connecting to via SSH.
  • USERNAME - Username to use when connecting via SSH.
  • KEY - Private Key used to connect to the server.
  • ROOT_DIR - Directory on the server we are going to navigate to once connected.

You add each secret by pressing the New Repository Secret button.

Deployment YAML

name: Deployment

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
      - name: Deployment
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.KEY }}
          script: |
            cd ${{ secrets.ROOT_DIR }}
            php artisan down
            git checkout main -f
            git pull
            composer update --no-interaction --prefer-dist --optimize-autoloader --no-dev
            php artisan migrate --force
            php artisan cache:clear
            php artisan auth:clear-resets
            php artisan route:cache
            php artisan config:cache
            php artisan view:cache
            php artisan up

Copyright © 2024 | bonnick.dev