Automate GitHub Deployments to Linux using GitHub Actions
To automatically deploy a project from GitHub to a Linux server, you can set up a CI/CD (Continuous Integration and Continuous Deployment) pipeline. Here's a basic guide using GitHub Actions and some shell scripting:
Overview
- GitHub Actions: Set up a workflow that will trigger on certain GitHub events, such as pushes to the main branch.
- SSH Setup: Securely connect to your Linux server via SSH.
- Deployment Script: Deploy the code to your Linux server.
Prerequisites
- A GitHub repository.
- A Linux server with SSH access.
- Basic knowledge of SSH, Linux, and GitHub Actions.
Steps to Set Up Automatic Deployment
1. Set Up SSH Keys
-
Generate SSH Keys on your local machine:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
This will generate a public and a private key. By default, these are stored in
~/.ssh/id_rsa
(private) and~/.ssh/id_rsa.pub
(public). -
Add the Public Key to the Server: Append the contents of
id_rsa.pub
to the~/.ssh/authorized_keys
file on your server. -
Add the Private Key to GitHub:
- Go to your GitHub repository.
- Click on
Settings
>Secrets and variables
>Actions
>New repository secret
- Name it
DEPLOY_KEY
and paste the content of yourid_rsa
file.
2. Create a GitHub Actions Workflow
Create a GitHub Actions workflow file in your repository. It should be located at .github/workflows/deploy.yml
.
Here's a sample deploy.yml
:
name: Deploy to Server
on:
push:
branches:
- main # Triggers the workflow on pushes to the main branch
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup SSH
uses: webfactory/ssh-agent@v0.5.4
with:
ssh-private-key: ${{ secrets.DEPLOY_KEY }}
- name: Deploy to Server
env:
HOST: your.server.ip
USER: your_username
PROJECT_PATH: /path/to/project/on/server
run: |
ssh -o StrictHostKeyChecking=no $USER@$HOST "
cd $PROJECT_PATH
git pull origin main
# Logic to restart your services or perform any additional deployment steps
"
3. Adjust Permissions and Test
-
Make sure that the user running the Action has the appropriate permissions to pull the repository and restart services on the server.
-
Test the setup by pushing a change to the
main
branch or triggering the workflow manually.
Additional Considerations
- Security: Always be cautious when handling SSH keys. Use the least privilege principle to limit the keys’ permissions.
- Secrets Management: Use GitHub secrets to store sensitive data securely.
- Continuous Monitoring: Consider adding monitoring or notification steps to alert you of successful or failed deployments.
This setup provides a basic framework for automatic deployments to a Linux server. Depending on your project's complexity, you might need more steps, such as testing, building, or containerizing your application.