author: @kawam tags:#github-actions#linux
Using Key
name: Pull latest code
on:
push:
branches: [ master ]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Pull latest code
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.PRIVATE_KEY }}
script: |
cd /path/to/your/repo
git pullHow to:
- Generate an SSH key pair on your local machine:
ssh-keygen -t rsa -b 4096 - Copy the public key to your server:
ssh-copy-id user@hostname - Configure SSH on your server:
Edit the
/etc/ssh/sshd_configfile on your server and make sure the following settings are configured:
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
- Restart the SSH service:
sudo systemctl restart ssh
Using PEM
To set up SSH key authentication using a .pem file, you can follow these general steps:
- Generate an SSH key pair on your local machine: If you haven’t already done so, generate an SSH key pair on your local machine using the
ssh-keygencommand. This will create a public key file (id_rsa.pub) and a private key file (id_rsa) in your~/.ssh/directory. - Copy the public key to your server: Use the
ssh-copy-idcommand to copy the public key to your server. For example:
> ssh-copy-id -i ~/.ssh/id_rsa.pub -o "IdentityFile ~/.ssh/my_pem_file.pem" username@hostname
This command will copy the contents of your id_rsa.pub file to the authorized_keys file on the server.
- Configure the server to allow SSH key authentication: Open the
sshd_configfile on your server and ensure that the following settings are enabled:
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
Save the file and restart the SSH service using sudo service ssh restart.
- Configure the SSH connection in the workflow file: In the workflow file, use the SSH action to connect to your server and execute the necessary commands. Specify the
private-keyinput parameter to point to your.pemfile. For example:
- name: SSH into server
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
private-key: ${{ secrets.PRIVATE_KEY }}
script: |
cd /path/to/your/repo
git pull
-
Configure the secrets: In your repository settings, define the secrets
PRIVATE_KEY,USERNAME, andHOSTwith the appropriate values. Set thePRIVATE_KEYsecret to the contents of your.pemfile. -
Test the workflow: Once you have set up the workflow, commit and push the changes to your repository. GitHub Actions will automatically run the workflow when the trigger condition is met. Check the logs to ensure that the workflow runs successfully and that the latest code is pulled onto your server.
Note that using a .pem file for SSH key authentication can be less secure than using SSH keys. It’s generally recommended to use SSH keys whenever possible.