GitHub Actions - Run a command on a target server using SSH
                
            
            
            
             
            
            
                           
                
            
            
            
                
    
    
     
            
                
                    by
                    Jeremy Canfield  |  
                    Updated: November 25 2024
                    
                          |  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.
- Using the built-in run command (this article)
- Using appleboy ssh-action
Check out my article Public key authentication with OpenSSH on Linux for details on how to configure the target server to allow SSH connections.
The built-in run command can be used to run a command on a target server. In this example, the mkdir /tmp/foo command will be run on the target server to create the /tmp/foo directory on the target server.
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: setup SSH key
        run: |
          install -m 600 -D /dev/null ~/.ssh/id_rsa
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa        
        
      - name: SSH command
        run: ssh -o StrictHostKeyChecking=no john.doe@server1.example.com "mkdir /tmp/foo"               
Did you find this article helpful?
If so, consider buying me a coffee over at 