Deploy to Server with GitHub Actions

admin
December 22, 2024
November 26, 2024

This guide will show you how to set up a GitHub Actions workflow to automatically update your server content whenever you push your code to GitHub.

Step-by-Step Guide:

  1. Generate SSH Keys:
  2. On your local machine, generate an SSH key pair (if you don't have one) using the command:
    ssh-keygen -t ed25519 -C "[email protected]"
    
  3. This will create a private key (id_ed25519) and a public key (id_ed25519.pub).

  4. Configure the Server:

  5. Copy the contents of the public key (id_ed25519.pub) to the server's ~/.ssh/authorized_keys file:
    cat id_ed25519.pub >> ~/.ssh/authorized_keys
    
  6. Ensure the permissions are set correctly:

    chmod 700 ~/.ssh
    chmod 600 ~/.ssh/authorized_keys
    

  7. Add Private Key to GitHub:

  8. In your GitHub repository, go to SettingsSecrets and variablesActions.
  9. Click on New repository secret to add the SSH private key:
    • Name: SSH_PRIVATE_KEY
    • Value: Paste the contents of your private key (id_ed25519).
  10. Also, add the following secrets:

    • Name: HOST, Value: Your server's IP address or domain.
    • Name: USERNAME, Value: Your server’s username.
  11. Create GitHub Actions Workflow:

  12. In your GitHub repository, create a directory .github/workflows if it doesn't exist.
  13. Create a file named deploy.yml inside the .github/workflows directory with the following content:
name: Deploy to Server

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up SSH
        uses: webfactory/[email protected]
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}

      - name: Copy files to server
        run: |
          ssh -o StrictHostKeyChecking=no ${{ secrets.USERNAME }}@${{ secrets.HOST }} "cd /www/wwwroot/Django_ESP32 && git pull"
  1. Push to GitHub:
  2. Whenever you push changes to the main branch of your GitHub repository, the GitHub Actions pipeline will trigger.
  3. It will check out your code, set up the SSH connection, and execute the command to pull the latest code on your server.

Result:

Upon each push to the main branch of your repository, the latest code will automatically be pulled onto your specified server directory, keeping your server's content updated with your GitHub repository.

This setup allows for a streamlined deployment process, making it easier to manage code updates without manual intervention.

Was this page helpful?
See also