How to Execute Remote SSH Commands in GitHub Actions

How to Execute Remote SSH Commands in GitHub Actions

Introduction

Hello, tech wizards! In our journey through Cloud and DevOps technologies, today we’re going to explore an exciting topic – executing remote SSH commands using GitHub Actions. GitHub Actions, with its power and flexibility, makes it possible for us to connect and execute commands on remote servers directly from our workflows. This functionality can open up a whole new world of possibilities, from deploying applications to running tests on remote environments, and much more. So, let’s dive in!

Fundamental Concepts

Before we get our hands dirty, let’s first clarify a couple of fundamental concepts:

GitHub Actions

GitHub Actions is a powerful CI/CD (Continuous Integration/Continuous Deployment) service provided by GitHub. It allows you to automate, customize, and execute your software development workflows within your GitHub repository. You can create workflows to build, test, package, release, or deploy any project hosted on GitHub.

SSH (Secure Shell)

SSH is a cryptographic network protocol for secure data communication, remote command execution, and other secure network services between two networked computers. Using SSH, you can control a remote server as if you were sitting right in front of it.

Now, let’s move on to the practical part of this blog.

Step-by-step Guide to Execute Remote SSH Commands in GitHub Actions

We’re going to use an open-source action from the GitHub Marketplace called “SSH Remote Commands” by appleboy. This action allows us to connect to a remote server via SSH and execute commands.

Step 1: Set up SSH Keys

Generate a new SSH key pair on your local machine, and add the public key to the ~/.ssh/authorized_keys file on the remote server. This will allow the GitHub Actions runner to connect to the server.

Step 2: Store the Private Key in GitHub Secrets

In your repository, navigate to “Settings” -> “Secrets”, and add a new repository secret. Name it SSH_PRIVATE_KEY and paste the private key you generated in the previous step. GitHub Secrets are encrypted and can be safely used in workflows.

Step 3: Create a GitHub Actions Workflow

Create a new file under the .github/workflows directory in your repository, let’s call it ssh-remote-commands.yml.

Step 4: Configure the Workflow

Open the ssh-remote-commands.yml file and configure it as follows:

In this example, REMOTE_HOST and REMOTE_USER are also stored as GitHub Secrets. The script section is where you write the commands to be executed on the remote server.

Conclusion

Automating remote server tasks through GitHub Actions is a powerful capability that can greatly streamline your CI/CD processes. It’s an example of how we can harness the power of automation to simplify complex tasks and boost productivity. So keep coding, keep exploring, and as always, happy automating!