DEV Community

S.M. Khalid Mahmud
S.M. Khalid Mahmud

Posted on

How to automatic deployment from GitHub to server via SFTP (GitHub Actions)

We are going to take a look at how we can automate deployment from GitHub to server via SFTP. To do that we have to create some folder and file in project root where .git folder exist. Such as:

Image description

Now, we need to add below code in server-deploy-via-sftp file, which we created before.

name: CI-SFTP

# Controls when the action will run.
on:
  # Triggers the workflow on push or pull request event but only for the main branch
  push:
    branches: [ main ]
  #  pull_request:
  #    branches: [ main ]

  # Allows to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more job that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "SFTP"
  deploy-via-sftp:
    runs-on: ubuntu-latest
    steps:
      # Checkouts repository under $GITHUB_WORKSPACE, so job can access it
      - name: Checkout
        uses: actions/checkout@v3

      - name: SFTP Deploy
        uses: wlixcc/SFTP-Deploy-Action@v1.2.4
        with:
          server: ${{ secrets.SERVER }}
          port: 22 # default is 22
          username: ${{ secrets.USERNAME }}
          ssh_private_key: ${{ secrets.SSH_PRIVATE_KEY }}

          # Puts all file to under this path
          local_path: ./server/* # default is ./*
          # File will copy to under this path
          remote_path: ${{ secrets.REMOTE_PATH }}

          # Arg
          args: "-o ConnectTimeout=5"
Enter fullscreen mode Exit fullscreen mode

Here we need SSH private key, which is basically a method of authenticating GitHub to make changes on deployment server. So for this we are gonna have to generate an SSH key pair and to do that we are gonna have to open up a terminal where need to access deployment server. Then, we need to enter below command:

ssh-keygen -t rsa
Enter fullscreen mode Exit fullscreen mode

Now hit Enter to save the key. And keep empty passphrase.

We need to get public & private key. For that need to write below commands:

cd ~/.ssh
Enter fullscreen mode Exit fullscreen mode
ls
Enter fullscreen mode Exit fullscreen mode

Now, we can see two files, such as

  • id_rsa -> private key
  • id_rsa.pub -> public key

And also we need to create some secrets on GitHub and a new file authorized_keys in .ssh folder in deployment server, where need to write public key (id_rsa.pub content) and for creating GitHub secrets, go to repository Settings, then click on Secrets from sidebar. Secrets are:

SERVER: Your server address
USERNAME: Your server username
REMOTE_PATH: Where GitHub project will be uploaded
SSH_PRIVATE_KEY: Recently created private key on deploment server (id_rsa)
Enter fullscreen mode Exit fullscreen mode

Now push project on GitHub. And check status from Actions in repository.

Top comments (0)