Skip to content

Instantly share code, notes, and snippets.

@exonomyapp
Last active August 27, 2024 15:29
Show Gist options
  • Save exonomyapp/352a8590534d836314bf28d6caf391c3 to your computer and use it in GitHub Desktop.
Save exonomyapp/352a8590534d836314bf28d6caf391c3 to your computer and use it in GitHub Desktop.
GitHub Action to execute script on VPS

GitHub Action can run a shell script on your personal VPS, but it requires a few steps to set up secure communication between GitHub and your VPS. Here’s a general approach on how you can achieve this:

  1. Set Up SSH Access:

    • Ensure that your VPS allows SSH connections. You’ll need to have SSH access set up on your VPS.
  2. Create SSH Keys:

    • Generate an SSH key pair on your local machine (or wherever you are setting up the GitHub Action). You can use the following command:
      ssh-keygen -t rsa -b 4096 -C "[email protected]"
    • This will create a private key (id_rsa) and a public key (id_rsa.pub).
  3. Add SSH Key to Your VPS:

    • Copy the contents of your public key (id_rsa.pub) and add it to the ~/.ssh/authorized_keys file on your VPS.
  4. Store SSH Key in GitHub Secrets:

    • Go to your GitHub repository.
    • Navigate to Settings > Secrets and variables > Actions.
    • Click New repository secret and add a secret named SSH_PRIVATE_KEY with the contents of your private key (id_rsa).
  5. Create a GitHub Action Workflow:

    • Create a GitHub Actions workflow YAML file in your repository’s .github/workflows directory (e.g., deploy.yml).

    Here’s a basic example of a GitHub Actions workflow that connects to your VPS and runs a shell script:

    name: Deploy to VPS
    
    on:
      push:
        branches:
          - main
    
    jobs:
      deploy:
        runs-on: ubuntu-latest
    
        steps:
          - name: Checkout code
            uses: actions/checkout@v3
    
          - name: Set up SSH
            run: |
              mkdir -p ~/.ssh
              echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
              chmod 600 ~/.ssh/id_rsa
              ssh-keyscan -H your-vps-address.com >> ~/.ssh/known_hosts
    
          - name: Run script on VPS
            run: |
              ssh -o StrictHostKeyChecking=no [email protected] 'bash -s' < path/to/your-script.sh

    Replace your-vps-address.com with your VPS address, user with your VPS username, and path/to/your-script.sh with the path to your shell script.

  6. Test the Workflow:

    • Commit and push your workflow file to your GitHub repository. The GitHub Action should trigger and run the shell script on your VPS.

This setup uses SSH for secure communication between GitHub Actions and your VPS. Make sure to handle SSH keys and access with care to avoid security issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment