Bootstrap FreeKB - GitHub Actions - Run a command on a target server using appleboy ssh-action
GitHub Actions - Run a command on a target server using appleboy ssh-action

Updated:   |  GitHub Actions articles

GitHub Actions can be used to do something whenever something happens in one of your GitHub repositories. If you are not familiar with GitHub Actions, check out my article Getting Started with GitHub Actions.

Following are ways to run a command on a target server.

appleboy/scp-action@master is being used here. Check out my article Public key authentication with OpenSSH on Linux for details on how to configure the target server to allow SSH connections.

In this example the following secrets are created at your repository > Settings > Secrets and variables > Actions.

  • HOSTNAME = target server hostname or IP address
  • PORT = target server SCP port (almost always 22)
  • USERNAME = the username that will be used in the SCP connection to the target server
  • PASSWORD = the users SSH password
name: GitHub Action
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
  push:
    branches:
      - main
jobs:
  restart-docker-container:
    runs-on: ubuntu-latest
    steps:      
      - name: Checking out the repository code
        uses: actions/checkout@v4
      
      - name: create the /tmp/foo directory
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          password: ${{ secrets.PASSWORD}}
          port: ${{ secrets.PORT }}
          script: mkdir /tmp/foo

 

Or, better yet, you can used a SSH keypair. In this example the following secrets are created at your repository > Settings > Secrets and variables > Actions.

  • HOSTNAME = target server hostname or IP address
  • PORT = target server SCP port (almost always 22)
  • USERNAME = the username that will be used in the SCP connection to the target server
  • PRIVATE_KEY = the contents of the users SSH private key file on the target server, such as $HOME/.ssh/id_rsa or $HOME/.ssh/id_ed25519
name: GitHub Action
run-name: ${{ github.workflow }} run by ${{ github.actor }}
on:
  push:
    branches:
      - main
jobs:
  restart-docker-container:
    runs-on: ubuntu-latest
    steps:      
      - name: Checking out the repository code
        uses: actions/checkout@v4
      
      - name: copy foo.jpg to /tmp/foo.jpg on EC2 instance ec2-10-11-12-13.compute-1.amazonaws.com
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.PRIVATE_KEY }}
          port: ${{ secrets.PORT }}
          script: sudo docker restart my-container



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter fc2238 in the box below so that we can be sure you are a human.