DEV Community

Hussein Alamutu
Hussein Alamutu

Posted on

The How, Why and When of Github Actions.

DevOps is a broad field, with what seems like a non ending pool of tools to use.

Github Actions is one of those tools. If you want to automate your code pipeline from integration to delivery without complicating things, Github Actions comes in handy.

At the end of this article you will gain the understanding of why Github Actions is used in DevOps, when to use it and how to get started with it.

Prerequisites

In order to get the most out of this article, you need to have a basic understanding of Github and continuous integration and continuous delivery(CI/CD) pipeline.

Why Use Github Actions?

Github Actions is a CI/CD tool that allows you to automate your workflow by creating custom scripts that can be triggered by different events. These events can include things like code changes, pull requests, or other Github activities.

Note: I will be using workflows a lot as we move along.

In the context of Github Actions, a workflow refers to a set of automated steps or processes that are triggered by an event, such as a code push or pull request, in a Github repository.

A workflow consist of one or more jobs, and each job can have one or more steps that define specific actions to be executed, such as running tests, building a project, or deploying code to a server.

The workflow is defined in a YAML file that is committed to the repository, and Github automatically executes the workflow when the defined event, such as code push or merged pull request occurs.

Github Actions was first launched in 2018, and since then it has been adopted by a large number of organizations and individuals. Github Actions is based on YAML syntax and uses Docker containers to run your code in a variety of different environments(Linux, Windows or MacOS).

Github Actions offers several advantages over other CI/CD tools.

These advantages include:

  1. Integration with Github: Because Github Actions is integrated with Github and Github is very popular amongst programmers as a code hosting platform for version control and collaboration, this makes Github Actions easy to set up and use if you're already familiar with Github.

  2. Scalability: Github Actions is suitable for small teams and can scale to meet the needs of large organisations.

  3. Flexibility: Github Actions is highly customizable, which means you can create workflows that fit your specific needs.

  4. Event-based workflows: With Github Actions, you can set up workflows to run when specific events occur, which can help you automate your workflow more efficiently.

  5. Time-based workflows: You can set up workflows to run at a specific time or on a recurring schedule, rather than being triggered by an event in a Github repository. This is useful for performing tasks like automated backups, running tests on a regular basis, or performing routine maintenance on a server or application.

  6. Github Actions can also be a more cost-effective solution than other CI/CD tools, as it doesn't require any additional infrastructure or third-party services. Additionally, Github Actions provides a wide range of pre-built actions that you can use to get started quickly.

When to use Github Actions?

Github Actions is a powerful tool for automating continuous integration and deployment workflows, but it's not always the best choice for every situation. When considering whether to use Github Actions for your project, it's important to evaluate your needs and compare Github Actions to other CI/CD tools on the market.

This section explores when it's appropriate to use Github Actions, how to evaluate whether it's the right choice for your project, and some examples of successful use cases.

Choosing between Github Actions and other CI/CD tools

When it comes to choosing between Github Actions and other CI/CD tools, there are a few factors to consider. One key factor is the level of customization and control you need over your workflows. Github Actions offers a high level of customisation and control, allowing you to define complex workflows and use a wide range of third-party integrations.

However, other tools may offer more specialised features or integrations that better meet your specific needs.

Another factor to consider is the level of expertise and resources required to set up and maintain your CI/CD pipeline.

Github Actions is relatively easy to set up and use, especially if you're already familiar with Git and Github, other tools may require more expertise or specialised knowledge to configure and maintain.

Evaluating when Github Actions is appropriate

To determine whether Github Actions is appropriate for your project, it's important to evaluate your needs and goals. Here are a few questions to consider:

  1. What level of automation and testing do you need for your project?

  2. What are your deployment goals, and how frequently do you need to deploy code?

  3. What level of customisation and control do you need over your workflows?

  4. What level of expertise and resources do you have available to set up and maintain your CI/CD pipeline?

If you need a high level of automation and testing, frequent deployments, and a high level of customisation and control over your workflows, Github Actions may be a good choice.

However, if you have more specialised needs or require a higher level of expertise to set up and maintain your pipeline, other tools may be a better fit.

Examples of successful use cases

There are many successful use cases for Github Actions, including:

  1. Automating testing and deployment for web applications
    Building and deploying Docker images.

  2. Running linters and other code quality checks.

  3. Automating documentation generation and publishing
    In each of these cases, Github Actions provides a powerful and flexible tool for automating complex workflows and ensuring that code is tested, built, and deployed reliably and efficiently.

In conclusion, Github Actions can be a powerful tool for automating CI/CD workflows, but it's important to evaluate your needs and compare Github Actions to other tools before making a decision.

By carefully considering your requirements and goals, you can choose the tool that best meets your needs and ensures that your development process is efficient, reliable, and scalable.

The How of GitHub Actions

This section explores how to set up Github Actions, including a step-by-step guide, an explanation of workflows and actions, and examples of YAML syntax.

Step-by-Step Guide to Setting up Github Actions

  1. Create a new repository in Github, or select an existing repository.

For this step, I am using an existing repository(devops_hands-on)

Selecting an existing repository

  1. Navigate to the "Actions" tab in your repository and click "set up a workflow yourself" to create a new YAML file for your workflow.

You should see something similar to what's in the image below, Github will suggests some sample workflow depending on what's in your repository.

Setting up a workflow on Github actions

  1. Define your workflow by specifying the event that will trigger your workflow, the jobs that will be executed, and the steps that will be performed within each job.

This is what the workflow YAML file looks like.

Creating a workflow

  1. Test your workflow by committing changes to your repository and observing the actions taken by Github.

This image shows what goes on underneath the specified workflow, basically, anytime I push to my repo or merge a pull request, this workflow runs and perform the actions "echo Hello, world!" and some other multi-line script that was defined in the workflow.

What the workflow does underneath

Explaining Workflows and Actions

A workflow in Github Actions is a set of automated steps or processes that are triggered by an event, such as a code push or pull request, in a Github repository.

A workflow can consist of one or more jobs, and each job can have one or more steps that define specific actions to be executed, such as running tests, building a project, or deploying code to a server.

An action is a specific step that is executed within a job in a workflow. Actions can be defined using pre-existing actions from the Github Marketplace, or by writing custom actions in Docker containers.

Examples of YAML Syntax

Here are some examples of YAML syntax that you might use when defining your workflow:

  • Specifying a trigger for your workflow:
on:
  push:
    branches: [ main ]

Enter fullscreen mode Exit fullscreen mode

When you push any changes to your main branch, your workflow fires up.

  • Defining a job that runs a command:
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Install dependencies
        run: npm install
      - name: Build project
        run: npm run build
Enter fullscreen mode Exit fullscreen mode

This code defines a single job in a Github Actions workflow called "build". The job runs on the latest version of the Ubuntu operating system, as specified by the runs-on key.

The job consists of three steps:

The first step, named "Checkout code", uses the actions/checkout action to fetch the latest version of the repository code. This action is commonly used in Github Actions workflows as a first step to ensure that the code being built or tested is up-to-date.

The second step, named "Install dependencies", runs the npm install command to install any dependencies required by the project. This step assumes that the project is a Node.js application and uses the Node Package Manager (npm) to install the dependencies.

The third and final step, named "Build project", runs the npm run build command to build the project. This step assumes that the project has a build script defined in its package.json file, and that running npm run build will produce a compiled version of the project ready for deployment.

Overall, this code defines a simple Github Actions job that checks out the latest code, installs dependencies, and builds the project.

This is a common workflow for many types of projects and can serve as a starting point for more complex workflows that incorporate testing, deployment, and other tasks.

  • Defining a job that uses a pre-existing action:
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Deploy to server
        uses: easingthemes/ssh-deploy@v2.1.1
        with:
          server: ${{ secrets.SERVER }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.KEY }}
          port: ${{ secrets.PORT }}
          source: "dist/"
          dest: "/var/www/my-app"
Enter fullscreen mode Exit fullscreen mode

This code defines a Github Actions job called "deploy" that runs on the latest version of Ubuntu operating system.

The job consists of two steps.

The first step, named "Checkout code", uses the actions/checkout action to fetch the latest version of the repository code. This step is similar to the first step in the previous example, and ensures that the code being deployed is up-to-date.

The second step, named "Deploy to server", uses the easingthemes/ssh-deploy action to deploy the code to a server. This action allows for secure SSH-based deployment of a project to a remote server. The action takes several parameters that are stored as secrets in Github, including the server's ip address, the username to log in with, and the path to the SSH key file.

The action also specifies the source and destination paths for the deployment. In this case, it is deploying the contents of the "dist/" directory to the "/var/www/my-app" directory on the remote server.

Overall, this code defines a simple Github Actions job that deploys a project to a remote server using SSH-based deployment. This is a common workflow for many types of projects that require deployment to a remote server, and can be modified to suit different deployment scenarios.

What a final workflow looks like

The final workflow for Github Actions will depend on the specific needs and goals of your project.

However, to give you an idea of what a final workflow might look like, here's an example:

name: Build and Deploy

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Install dependencies
        run: npm install
      - name: Build project
        run: npm run build
  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Setup SSH
        uses: webfactory/ssh-agent@v0.4.1
        with:
          ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
      - name: Deploy to server
        run: ssh user@server "cd /var/www && git pull"

Enter fullscreen mode Exit fullscreen mode

This workflow is triggered by a push to the main branch or a pull request on the main branch.

It consists of two jobs: a build job that installs dependencies and builds the project, and a deploy job that deploys the project to a server. The deploy job has a dependency on the build job, meaning it won't be executed until the build job has completed successfully.

In the deploy job, the workflow sets up an SSH connection to the server using a private key stored as a secret in Github. It then uses SSH to run a command on the server that pulls the latest changes from the Github repository.

This is just one example of a Github Actions workflow, and yours will likely look different depending on your specific needs.

However, by following the steps outlined in this article, you can create powerful and flexible automation for your Github repository.

Bonus: Best practices for Github Actions

Github Actions is a powerful tool that can help automate many aspects of software development, from continuous integration and deployment to testing and monitoring.

However, with great power comes great responsibility, and it's important to follow best practices when writing Github Actions workflows to ensure that they are efficient, effective, and secure.

This section covers some of the best practices for Github Actions that you should keep in mind when creating workflows.

  • Keep workflows simple and focused.

One of the best practices for writing Github Actions workflows is to keep them simple and focused on a specific task. This means that each workflow should only do one thing, such as running tests or deploying code, and should not try to do too many things at once. This approach makes it easier to understand and maintain the workflow, and reduces the risk of errors or failures.

  • Use caching to speed up workflows.

Github Actions provides caching functionality that can be used to speed up workflows by caching files and dependencies between workflow runs.

This can significantly reduce the time it takes to run a workflow, especially if the workflow requires downloading and installing dependencies or compiling code. To use caching, you can add a caching step to your workflow that specifies which files or directories to cache.

  • Use reusable actions.

Github Actions allows you to create and reuse actions, which are reusable steps that can be used in multiple workflows.

Reusing actions can help simplify your workflows and make them more modular, as you can reuse the same action in multiple workflows rather than writing the same steps multiple times. You can create your own actions or use actions from the Github Marketplace.

  • Keep secrets and sensitive information secure.

Github Actions allows you to store secrets and sensitive information as encrypted variables, which can be used in your workflows. However, it's important to keep these secrets and sensitive information secure, as they can be accessed by anyone with access to your repository.

To keep them secure, you should only grant access to authorised users, limit the scope of the secrets and sensitive information, and avoid storing them in plain text in your workflows.

  • Test and validate workflows.

Github Actions workflows should be thoroughly tested and validated before they are deployed to production. This includes testing the workflows on different platforms and environments, validating the inputs and outputs of the workflows, and ensuring that the workflows are reliable and error-free.

You can use Github Actions' built-in testing functionality, such as the jobs.<job_id>.steps.run syntax, to test and validate your workflows.

In conclusion, Github Actions is a powerful tool that can help automate many aspects of software development, but it's important to follow best practices when writing workflows to ensure that they are efficient, effective, and secure.

By keeping workflows simple and focused, using caching, reusing actions, keeping secrets and sensitive information secure, and testing and validating workflows, you can create robust and reliable workflows that help streamline your development process.

Congratulations! You have gotten to the end of the guide.

Iā€™m currently in search of paid technical writing gigs related to cloud & devops, if you got one, reach out or refer me.

You can check out - My portfolio.

Top comments (1)

Collapse
 
solomonawah profile image
Solomon Awah

Great write up!