Github Actions for automating CI/CD

by Daniel Pham
This entry is part 18 of 19 in the series Instructions for using Git and GitHub

GitHub Actions is a powerful feature that enables automation of workflows like Continuous Integration (CI) and Continuous Deployment (CD) directly within your GitHub repository. With GitHub Actions, you can set up workflows that respond to GitHub events like code pushes, pull requests, and issue updates to ensure smooth automation of the CI/CD process. In this article, we’ll guide you on how to use GitHub Actions to automate your project’s CI/CD pipeline, making your development process more efficient and streamlined.

What is GitHub Actions?

GitHub Actions is an automation tool built into GitHub that allows developers to create and customize workflows. These workflows are triggered by GitHub events and can be used to perform various tasks, such as running tests, building code, deploying applications, and more. It enables you to automate tasks like Continuous Integration (CI), which ensures that code changes are tested automatically before merging, and Continuous Deployment (CD), which ensures your application is deployed automatically after passing tests.

Why use GitHub Actions for CI/CD?

Automating CI/CD with GitHub Actions simplifies development workflows and ensures consistency across projects. Key benefits include:

  • Automation: Automatically trigger builds, tests, and deployments with each code change.
  • Customization: Define your workflows in YAML files, giving you full control over the CI/CD process.
  • Integration: Seamlessly integrates with GitHub repositories and third-party services like AWS, Docker, and Kubernetes.
  • Scalability: Handle small to large-scale projects without needing complex setup.

Setting up a CI/CD pipeline with GitHub Actions

To set up a CI/CD pipeline using GitHub Actions, we’ll walk through creating a basic workflow file for a Node.js project that automates testing and deployment.

Step 1: Creating the GitHub Actions workflow

Github Actions for automating CI/CD
Create a workflow file in Github Actions.

Each GitHub Actions workflow is defined in a YAML file inside the .github/workflows/ directory of your repository. To create a new workflow, follow these steps:

  1. In your GitHub repository, create a new directory called .github/workflows/.
  2. Inside this directory, create a new file called ci-cd.yml.

In this file, you will define the steps for your CI/CD pipeline.

Step 2: Defining the CI process

To automate testing, we’ll define a job that installs dependencies, runs tests, and ensures the code passes all checks before deployment. Below is an example configuration for a Node.js project:

name: CI/CD Pipeline

# The workflow will be triggered when there is a push or pull request on the 'main' branch
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

# Define the jobs to be executed
jobs:
  build:
    # The job will run on the latest Ubuntu environment
    runs-on: ubuntu-latest

    # Steps in the job
    steps:
      # Step 1: Checkout the source code from the repository
      - name: Checkout code
        uses: actions/checkout@v3

      # Step 2: Set up Node.js environment version 16.x
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '16'

      # Step 3: Set up caching for the npm directory (speed up build)
      - name: Cache Node.js modules
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      # Step 4: Install the project dependencies
      - name: Install dependencies
        run: npm install

      # Step 5: Run the tests
      - name: Run tests
        run: npm test

In this workflow:

  • The on section defines when the workflow will run. In this case, it runs on pushes and pull requests to the main branch.
  • The build job runs on the latest version of Ubuntu and consists of steps to check out the code, set up Node.js, install dependencies, and run tests.

Step 3: Adding the CD process

To automate deployment after tests pass, we’ll extend our workflow to include deployment steps. For example, if you’re deploying to an AWS environment, you can use AWS CLI commands in the workflow:

      # Step 9: Configure AWS CLI with environment variables from Secrets
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v2
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: 'us-east-1' # Change according to your region

      # Step 10: Deploy code to S3 (example for static app)
      - name: Deploy to S3
        run: |
          aws s3 sync ./dist s3://my-bucket-name --delete
          aws cloudfront create-invalidation --distribution-id your-distribution-id --paths "/*"

In this step:

  • After tests pass, the deployment job uploads the build artifacts to an S3 bucket and invalidates the CloudFront cache to ensure the latest version of the application is served.

Step 4: Using secrets for security

When deploying to external services like AWS, it’s crucial to keep your credentials secure. GitHub Actions allow you to store sensitive information such as API keys and tokens using GitHub Secrets.

Github Actions for automating CI/CD
Create secrets for Github Actions to use.

To add secrets:

  1. Navigate to your repository’s Settings.
  2. Under Security, select Secrets and variables.
  3. Click New repository secret to add secrets like AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.

These secrets can then be referenced securely in your workflow using ${{ secrets.YOUR_SECRET_NAME }}.

Github Actions for automating CI/CD
Enter the name and value of the secret you need to create for Github Actions.
Github Actions for automating CI/CD
In the example, 2 secrets were created, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.

Here is a complete Github Actions file that you can refer to.

name: CI/CD Pipeline

# The workflow will be triggered when there is a push or pull request on the 'main' branch
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

# Define the jobs to be executed
jobs:
  build:
    # The job will run on the latest Ubuntu environment
    runs-on: ubuntu-latest

    # Steps in the job
    steps:
      # Step 1: Checkout the source code from the repository
      - name: Checkout code
        uses: actions/checkout@v3

      # Step 2: Set up Node.js environment version 16.x
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '16'

      # Step 3: Set up caching for the npm directory (speed up build)
      - name: Cache Node.js modules
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      # Step 4: Install the project dependencies
      - name: Install dependencies
        run: npm install

      # Step 5: Run the tests
      - name: Run tests
        run: npm test

  # Define the deploy job, which will run after the build job succeeds
  deploy:
    # The deploy job will only run if the build is successful
    runs-on: ubuntu-latest
    needs: build

    steps:
      # Step 6: Checkout the source code for deployment
      - name: Checkout code
        uses: actions/checkout@v3

      # Step 7: Set up Node.js environment for deployment
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '16'

      # Step 8: Install AWS CLI for deployment
      - name: Install AWS CLI
        run: |
          sudo apt-get update
          sudo apt-get install awscli -y

      # Step 9: Configure AWS CLI with environment variables from Secrets
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v2
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: 'us-east-1' # Change to your region

      # Step 10: Deploy code to S3 (example for static app)
      - name: Deploy to S3
        run: |
          aws s3 sync ./dist s3://my-bucket-name --delete
          aws cloudfront create-invalidation --distribution-id your-distribution-id --paths "/*"

Best practices for GitHub Actions CI/CD

To ensure smooth and efficient CI/CD workflows with GitHub Actions, follow these best practices:

1. Use caching to speed up builds

GitHub Actions allow you to cache dependencies between workflow runs, which speeds up your build times. Here’s an example of caching Node.js dependencies:

      - name: Cache Node.js modules
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

This step will cache node_modules, speeding up the workflow on subsequent runs.

2. Keep workflows modular

Break down complex workflows into smaller, modular jobs. For example, you can separate testing, building, and deployment into different jobs. This makes your workflow easier to maintain and allows for better monitoring of each step.

3. Leverage matrix builds

Matrix builds allow you to test your project across different environments or configurations. For example, you can test your application on multiple Node.js versions:

strategy:
  matrix:
    node-version: [12, 14, 16]

This ensures compatibility across different versions without having to manually configure each test environment.

4. Monitor workflows with GitHub Actions logs

GitHub provides detailed logs for each workflow run. Use these logs to monitor the progress of your CI/CD pipeline and troubleshoot any issues that arise during the build or deployment process.

Github Actions for automating CI/CD
You can click on each pipeline in the Actions tab to see its logs and progress.

5. Set up notifications

To stay informed about the status of your workflows, you can set up notifications to alert you when workflows fail or succeed. GitHub Actions can be integrated with tools like Slack or email notifications to ensure you’re always up-to-date.

Conclusion

Using GitHub Actions to automate your CI/CD pipeline is a game-changer for development teams. By setting up workflows that automatically test and deploy your code, you can save time, reduce manual errors, and maintain code quality across your project. Whether you’re deploying a Node.js application or integrating with other services like AWS, GitHub Actions provides a flexible and powerful solution for automating your development workflows. Follow the best practices outlined in this guide to create efficient CI/CD pipelines and take full advantage of GitHub Actions in your projects.

Instructions for using Git and GitHub

Pull Request creation and management Secure Github Access and Management
0 0 votes
Article Rating

You may also like

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

0
Would love your thoughts, please comment.x
()
x

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.