Using Github Action and some simple SSH commands you can deploy your new scripts/content to the server. Here are the steps:
- Generate SSH key pair
We’ll be using SSH connection and Shimataro’s Install SSH Key for our setup. The first step is to generate a key pair. The command is:
ssh-keygen -t rsa -b 4096 -C "email@example.com" -f $HOME/.ssh/github_action
Customize your command if you whish.
- Add the public key to authorized_keys on the server
The next step is to add the newly generated public key to the authorized_keys
cat $HOME/.ssh/github_action >> $HOME/.ssh/authorized_keys
- Add the private key to your repository’s secrets
Go to your repository on Github and click on Settings, then Secrets. You should see a button that says New repository secret – click on it.
The secret name is used to get the contents later in a Github Actions workflow. In my example I’ll use SSH_PRIVATE_KEY. Copy the content of $HOME/.ssh/github_action.pub file to the Value field and press Add secret.
- Add a correct value to the known_hosts
Now, for the SSH connection you’ll also need the right content for your known_hosts file. The easiest option is to run the following command from a remote server replacing the IP_ADDRESS with your destination server
ssh-keyscan -H IP_ADDRESS
The output of this command will look like this:
# 22.214.171.124:22 SSH-2.0-OpenSSH_7.4
|1|V/L+y8vso2cbrfYO7TfENAyF5H8=|s8VNxQvigrcq30l8wmUYA3o2R+U= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbm…vbSZ4zh0JwJvI9qtyDCrH5Q=
|1|Okxr6I2dqwfBDwIsGwKIhmvRmR8=|VfjTAIym06En6AcBjsYToweCXJc= ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDthg…5BbU8+/hdw7D5BSy9T
|1|bbdHyQMlo3chsltW+TftolUUqec=|xWd5sMsh3c/1hgKKsTlADB4Uw0M= ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAu5J…7XoPKJNZgh3XyvyYkOyEaf5
Go to your repository on Github and click on Settings, then Secrets and New repository secret. The name of the new secret for this example will be SSH_PRIVATE_KEY. Copy the output of ssh-keyscan to the Value field and press Add secret.
- Create a simple workflow with the private key and known_hosts
The last step is now to create a simple Action or Workflow file. Go to your repository on Github and click on Actions tab and then set up a workflow yourself link. Pick a useful name for you new flow and use the template to define all the steps. My workflow with the examples from above will look like this:
Note: as you can see from the script, it’ll run only on Push command to Staging environment. Then will connect to your server (126.96.36.199 replace it with your IP), and run git pull in /var/www/html folder. Customize this!