Using GitHub Actions to deploy on push is pretty simple. There are a few requisites:
In your repo create the file .github/workflows/deploy.yml
with the content below. Then in Github go to Settings, Secrets and variables, Actions and define repository secrets for REMOTE_HOST, REMOTE_PATH, REMOTE_USER, SLACK_WEBHOOK_URL, SSH_PRIVATE_KEY
You can ignore the Slack one if you are not confirming to a Slack channel (you’ll need to have added the webhook integration in your Slack channel). Then when you push it will update just the changes files. Note that rsync is set to delete any files on the server that aren’t in the repo so be careful! You can add them to the exclude below or remove the delete flag if you prefer.
name: Deploy to EC2 via Rsync
on:
push:
branches:
- main
jobs:
deploy:
name: Deploy Files
runs-on: ubuntu-latest
steps:
# 1. Checkout the repository code
- name: Checkout Code
uses: actions/checkout@v4
# 2. Sync changed files to server via rsync
- name: Sync files
uses: burnett01/rsync-deployments@7.1.0
with:
switches: -avzr --delete
--exclude='.git/'
--exclude='.github/'
--exclude='vendor/'
path: ./
remote_path: ${{ secrets.REMOTE_PATH }}
remote_host: ${{ secrets.REMOTE_HOST }}
remote_user: ${{ secrets.REMOTE_USER }}
remote_key: ${{ secrets.SSH_PRIVATE_KEY }}
# 3. Send Slack notification on success
- name: Slack Notification on Success
if: success()
uses: act10ns/slack@v2
with:
status: success
message: Deployment was successful! 🎉
webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }}
# 4. Send Slack notification on failure
- name: Slack Notification on Failure
if: failure()
uses: act10ns/slack@v2
with:
status: failure
message: Deployment failed! 🚨
webhook-url: ${{ secrets.SLACK_WEBHOOK_URL }}