How to Set Up CI/CD with GitHub Actions

Problem
Manually building, testing, and deploying applications can be time-consuming and error-prone. Continuous Integration and Continuous Deployment (CI/CD) streamline these processes, ensuring that changes are automatically tested and deployed. GitHub Actions provides a powerful, native solution for implementing CI/CD in your projects.
Solution
Using GitHub Actions, you can automate your CI/CD pipeline directly within your GitHub repository. Here's a step-by-step guide to setting it up.
Step 1: Create a Workflow File
GitHub Actions workflows are defined in YAML files located in the .github/workflows directory of your repository. Create a file named ci-cd.yml:
name: CI/CD Pipeline
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '14'
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
- name: Build project
run: npm run build
deploy:
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy
run: echo "Deploying your application"
Step 2: Configure Workflow Triggers
In the workflow above, triggers are set for push and pull_request events on the main branch. This means the workflow will run every time you push changes to main or open a pull request targeting main.
Step 3: Define Jobs and Steps
The workflow is split into jobs. Jobs can run sequentially or in parallel. In our example:
- Build Job: Checks out the code, sets up Node.js, installs dependencies, runs tests, and builds the project.
- Deploy Job: Depends on the build job and executes only after the build job succeeds.
Step 4: Secure Secrets
If your deployment process requires secrets (like API keys), store them in your repository's settings under "Secrets and variables". Use these secrets in your workflow by referencing them with secrets.MY_SECRET.
Key Concepts
- GitHub Actions: Automates workflows based on events in your Git repository.
- Workflow: Defined in YAML, it contains the automation instructions.
- Job: A set of steps executed by a runner.
- Runner: A server that runs your workflows when they're triggered.
- Secrets: Securely store sensitive information like tokens and passwords.
By setting up CI/CD with GitHub Actions, you ensure your code quality remains high by automating the testing and deployment processes, allowing you to focus more on writing code and less on manual tasks.