GitHub Actions Guide Part 1: Introduction and Setup

The first part of our comprehensive GitHub Actions guide covers key concepts, benefits, and how to set up your first workflow for automated CI/CD.

GitHub Actions Guide Part 1: Introduction and Setup

Table of Contents

GitHub Actions Guide Part 1: Introduction and Setup

In today’s fast-paced development environments, automation is no longer a luxury—it’s a necessity. GitHub Actions has emerged as a powerful solution that allows developers to automate workflows directly within their GitHub repositories. This three-part guide will take you from zero to hero with GitHub Actions, covering everything from basic concepts to advanced implementations.

Introduction to GitHub Actions

What is GitHub Actions?

GitHub Actions is an automation platform built directly into GitHub. It allows developers to automate their workflows, perform CI/CD tasks, and streamline repetitive processes, like testing, building, or deploying code.

When you commit code to your repository, you can automatically trigger a series of commands to build, test, and deploy your application. It’s like having a dedicated assistant who watches your repository and performs tasks whenever something happens.

Why is GitHub Actions Used?

  • Automation: Automate mundane tasks such as running tests, code linting, or creating deployments.
  • CI/CD: Enable Continuous Integration (CI) and Continuous Deployment (CD) for building, testing, and releasing applications faster.
  • Workflows: Simplify repetitive actions like managing issues or pull requests.

Benefits for Developers and Teams

  • Integration with GitHub: GitHub Actions is tightly integrated with your repository, making it easy to set up and use.
  • Flexibility: Supports custom workflows tailored to your needs.
  • Scalability: Whether you’re managing a small project or a large-scale application, GitHub Actions scales accordingly.
  • Pre-built Actions: Access thousands of reusable workflows and actions from the GitHub Marketplace.

How GitHub Actions Work

To understand GitHub Actions, it’s essential to grasp its core concepts:

Key Concepts

  • Workflows: A workflow is an automated process defined in a .yml file stored in the .github/workflows/ directory. It consists of one or more jobs.
  • Jobs: A job is a collection of steps that run sequentially or in parallel. Each job runs in its own virtual machine (or container).
  • Steps: Steps are individual tasks within a job. These can be running a script, executing a command, or invoking a pre-built action.
  • Actions: Actions are reusable units of code that perform a specific task. For example, there’s an action for setting up Node.js or deploying to AWS.

Example of a Simple Workflow

Here’s an example workflow that runs a “Hello World” script whenever you push code to the repository:

name: Hello World Workflow # Name of the workflow
on: # Events that trigger the workflow
  push:
    branches:
      - main # Trigger on pushes to the main branch

jobs: # Define jobs
  greet: # Name of the job
    runs-on: ubuntu-latest # Virtual environment for the job
    steps: # Steps for this job
      - name: Checkout code
        uses: actions/checkout@v3 # Action to check out repository code

      - name: Print Hello World
        run: echo "Hello, World!" # Command to execute

Explanation of the Workflow

  1. name: Defines the name of the workflow. This is for display purposes in the GitHub Actions tab.
  2. on: Specifies the event that triggers the workflow. In this case, it’s triggered when code is pushed to the main branch.
  3. jobs: Contains all the jobs that are part of the workflow.
  4. runs-on: Defines the environment where the job will run. Here, it uses ubuntu-latest.
  5. steps: Each job is broken into steps.
    • The first step uses a pre-built action (actions/checkout@v3) to check out the repository code.
    • The second step runs a simple shell command (echo "Hello, World!") and prints “Hello, World!” to the workflow logs.

Outcome

When you push code to the main branch:

  1. The workflow is triggered.
  2. It checks out the repository code.
  3. It prints “Hello, World!” in the logs, which you can view in the Actions tab of your GitHub repository.

YAML-Based Configuration Files

GitHub Actions workflows are defined using YAML. YAML is a human-readable data serialization format.

Why YAML?

  • Easy to read: Even non-developers can understand the configuration.
  • Structured: Clear hierarchy and indentation make it easy to define workflows.

Example: Triggering on Multiple Events

You can trigger workflows on multiple events. Here’s an example:

name: Multi-event Workflow
on:
  push: # Trigger on push
    branches:
      - main
  pull_request: # Trigger on pull request creation
    branches:
      - main

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Run tests
        run: echo "Running tests!"

Explanation:

  1. The workflow runs when there’s a push or a pull request to the main branch.
  2. In the job named test, a simple command is executed to simulate running tests.

Real-world Example

Imagine you’re developing a JavaScript application and want to ensure your code is always linted (checked for errors) before merging into the main branch. Here’s a workflow:

name: Lint JavaScript Code
on: pull_request

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: "18"

      - name: Install dependencies
        run: npm install

      - name: Run linter
        run: npm run lint

What this workflow does:

  1. Runs every time a pull request is opened.
  2. Sets up Node.js and installs project dependencies.
  3. Runs the linter (npm run lint) to check the code for issues.

Outcome: If the linter finds any issues, the workflow will fail, ensuring that only clean, linted code is merged.

Setting Up GitHub Actions

Getting Started with GitHub Actions

Before diving into workflows, let’s set up the basics.

Prerequisites

  1. GitHub Account: Make sure you have an active GitHub account. If not, sign up for free.
  2. A GitHub Repository:
    • You can either create a new repository or use an existing one.
    • To create a repository:
      • Go to GitHub, click the + icon in the top-right corner, and select New Repository.
      • Name your repository, set its visibility (public or private), and click Create Repository.

Accessing the GitHub Actions Tab

Once you have a repository:

  1. Navigate to your repository on GitHub.
  2. Click on the Actions tab in the top navigation bar. You’ll see a message saying, “Get started with GitHub Actions.”
  3. From here, you can explore pre-configured workflow templates or set up a custom one.

First Steps: Setting Up a Basic Workflow

To create your first workflow:

  1. Go to the Actions tab.
  2. Click Set up a workflow yourself to create a blank workflow file.
  3. GitHub creates a default main.yml file under .github/workflows/. Edit it to define your workflow.

Here’s an example of a basic workflow:

name: Basic CI Workflow
on: push # Trigger the workflow on code pushes
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Run a simple script
        run: echo "Hello, GitHub Actions!"

Explanation:

  1. name: The name of the workflow. This helps identify it in the GitHub Actions dashboard.
  2. on: Specifies when the workflow will run. Here, it triggers on every push event.
  3. jobs: Defines tasks (jobs) to be run.
  4. runs-on: Specifies the environment for the job (e.g., ubuntu-latest).
  5. steps: Lists individual tasks in the job.
    • The first step checks out the repository code.
    • The second step runs the command echo "Hello, GitHub Actions!", which prints the text in the logs.

Understanding .github/workflows

This directory is where all your workflow files are stored. Let’s break it down:

What is .github/workflows?

  • It’s a folder in your repository where GitHub looks for workflow YAML files.
  • These YAML files define the automation tasks for your repository.

How to Create the Directory?

  1. If the .github/workflows directory doesn’t exist, create it manually.
    • Navigate to your repository in GitHub and click Add file > Create new file.
    • Name the file .github/workflows/<workflow-name>.yml.

Naming Conventions for Workflow Files

  • Workflow files must have the .yml or .yaml extension.
  • Use descriptive names like build-and-test.yml or deploy.yml to indicate the workflow’s purpose.

Directory Structure Example

your-repository/
├── .github/
│   ├── workflows/
│   │   ├── build.yml
│   │   ├── deploy.yml
├── README.md
├── src/

Example Workflow in the Directory

Here’s a sample directory structure with a build.yml file:

name: Build Workflow
on: pull_request # Trigger on pull request creation
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository code
        uses: actions/checkout@v3
      - name: Install dependencies
        run: npm install
      - name: Run tests
        run: npm test

What it does:

  • Triggers the workflow when a pull request is created.
  • Installs dependencies using npm install.
  • Runs tests using npm test.

Common Questions About GitHub Actions Setup

Why do we need .github/workflows?

  • This directory centralizes your automation scripts. GitHub automatically detects files here, making it seamless to manage workflows.

Can I use a single workflow file for multiple tasks?

  • Yes, but it’s better to split complex workflows into smaller files for better maintainability.

What happens if my YAML file has an error?

  • GitHub provides error logs in the Actions tab to debug the issue. For example, if you forget to include on or jobs, GitHub will flag the YAML as invalid.

Real-world Use Case

Imagine you’re building a Python project and want to ensure your code is tested automatically. Here’s a setup:

  1. Create a file .github/workflows/python-tests.yml.
  2. Add the following workflow:
name: Python Tests
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: Set up Python
        uses: actions/setup-python@v3
        with:
          python-version: "3.8"
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        run: pytest

Explanation:

  1. Installs Python 3.8.
  2. Installs dependencies listed in requirements.txt.
  3. Runs tests using pytest.

Outcome: Whenever code is pushed, the workflow tests the Python application, ensuring it’s error-free.

Anatomy of a GitHub Actions Workflow

GitHub Actions workflows are defined in YAML files and dictate what tasks run, when they run, and how. Let’s explore the components in detail.

Workflow Syntax and Structure

A workflow file has a specific structure. Here’s an example:

name: CI Workflow # Name of the workflow
on: # Events that trigger the workflow
  push:
    branches:
      - main # Trigger on pushes to the 'main' branch
jobs: # Defines jobs to execute
  build: # A job named 'build'
    runs-on: ubuntu-latest # Environment to run the job
    steps: # Steps within the job
      - name: Checkout code # Step 1: Check out code from the repo
        uses: actions/checkout@v3
      - name: Print message # Step 2: A custom command
        run: echo "Hello, GitHub Actions!"

Let’s break it down:

name

  • What it does: Gives your workflow a name.
  • Example:
    name: Build and Test Workflow
    
  • Outcome: Appears in the GitHub Actions dashboard for easy identification.

on

  • What it does: Specifies events that trigger the workflow.

  • Common Events:

    1. push: Runs the workflow whenever new code is pushed to the repository.
    2. pull_request: Runs when a pull request is opened, updated, or merged.
    3. schedule: Runs at specific intervals (like a cron job).
    4. workflow_dispatch: Runs manually via the GitHub UI.
  • Example:

    on:
      push:
        branches:
          - main
    

    Outcome: This workflow triggers only when you push changes to the main branch.

jobs

  • What it does: Defines tasks to run. Each job runs in its own environment and can be executed in parallel or sequentially.

  • Example:

    jobs:
      build:
        runs-on: ubuntu-latest
    

    Outcome: Creates a job named build that runs on an Ubuntu environment.

steps

  • What it does: Specifies individual tasks within a job.

  • Each step can:

    1. Use pre-built actions.
    2. Run custom shell commands.
  • Example:

    steps:
      - name: Checkout code
        uses: actions/checkout@v3
    
      - name: Install dependencies
        run: npm install
    

    Outcome: The first step checks out your code. The second installs dependencies using npm install.

Triggers and Events

Triggers specify when a workflow should run. Let’s explore the most common types:

1. Push Trigger

  • What it does: Runs the workflow whenever new code is pushed to the repository.

  • Example:

    on:
      push:
        branches:
          - main
          - feature/*
    

    Outcome: The workflow triggers on any push to the main branch or branches starting with feature/.

2. Pull Request Trigger

  • What it does: Runs when a pull request is opened, updated, or merged.

  • Example:

    on:
      pull_request:
        branches:
          - main
    

    Outcome: Ensures that code changes are tested before merging into main.

3. Manual Trigger (workflow_dispatch)

  • What it does: Allows you to trigger workflows manually via the GitHub UI.

  • Example:

    on:
      workflow_dispatch:
        inputs:
          environment:
            description: "Environment to deploy to"
            required: true
            default: "staging"
    

    Outcome: Adds a button in the Actions tab to manually start the workflow. The user can specify inputs like the environment.

4. Scheduled Trigger

  • What it does: Runs workflows at specific intervals using cron syntax.

  • Example:

    on:
      schedule:
        - cron: "0 0 * * *"
    

    Outcome: Runs the workflow daily at midnight UTC.

Conclusion and Next Steps

In this first part of our GitHub Actions guide, we’ve covered:

  • The fundamentals of GitHub Actions and its key components
  • How to set up your first workflow
  • Understanding the structure and syntax of workflow files
  • Common triggers and events that can start your workflows

GitHub Actions is a powerful tool that can significantly streamline your development process. By automating repetitive tasks, you can focus on what really matters—writing great code.

In Part 2, we’ll dive deeper into building practical workflows, customizing them with environment variables and secrets, and implementing matrix builds for testing across multiple environments.


Continue to Part 2: Building Advanced Workflows

Table of Contents