Skip to content

Perform actions on Server using SSH with Github Actions

Creating Github Action for performing actions on a server over ssh.

This is a quick lookup blog post. Below is an extremely easy template for adding a github actions workflow.

Say your REST API or a website is hosted on virtual machine ( aws ec2, digitalocean droplets etc ). On merging or pushing code to a specific branch is when you want the update dev or prod service

The first thing to do is to create a .github directory in the root directory of your project. Now create a workflows directory in the .github directory.

mkdir .github
cd .github
mkdir workflows

Workflows are written as yaml / yml files.

Create a file with an appropriate filename. I'm going to name it as main.yaml

name: Update Website.

on:
  push:
    branches:
      - main

jobs:
  deploy:
    name: Deploying Website
    runs-on: ubuntu-latest

    steps:
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USERNAME }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ secrets.SSH_PORT }}
          script: |
            bash -e scriptname.sh

Explanation of the above file :

name: Update Website

Defines the name of the workflow. This is what you'll see in the GitHub Actions tab.


on: push -> branches: [main]

This tells GitHub to trigger the workflow only when changes are pushed to the main branch.


jobs: deploy

Defines a job named Deploying Website that runs on the ubuntu-latest virtual machine.


steps:

Contains the tasks that GitHub Actions will perform during the job.


uses: appleboy/ssh-action@v1.0.0

This uses the appleboy/ssh-action to connect to a remote server over SSH and run commands.


SSH Connection Configuration

The connection is securely handled via GitHub Secrets:

  • host: The remote server's IP address or domain.
  • username: Your SSH login username.
  • key: Your private SSH key (id_rsa), stored as a secret.
  • port: The SSH port (commonly 22).
  • script: The shell script or command(s) to run on the remote server.

In this case, the script is:

bash -e scriptname.sh