For enquiries call:

Phone

+1-469-442-0620

Aage ki Socho

HomeBlogWeb DevelopmentGitHub Actions: Automate Your Workflow [Beginners Guide]

GitHub Actions: Automate Your Workflow [Beginners Guide]

Published
05th Sep, 2023
Views
view count loader
Read it in
16 Mins
In this article
    GitHub Actions: Automate Your Workflow [Beginners Guide]

    Before we get into the main concept, let's define what automation in testing is. Automation testing is a software testing technique that uses special automated testing software tools to execute a test case suite. Manual testing, on the other hand, is carried out by a human sitting in front of a computer and carefully carrying out the test steps. The software can also enter test data into the System Under Test, compare expected and actual results, and generate detailed test reports. Software test automation necessitates significant financial and resource investments.

    Test automation is the most effective way to improve software testing effectiveness, test coverage, and execution speed. The following are the reasons why automated software testing is important:

    • Manual Testing of all workflows, fields and negative scenarios takes time and money.
    • In software testing, test automation does not require human intervention. Unattended automated testing is possible (overnight).

    Introducing GitHub Actions

    You might have used GitHub Actions to automate development tasks like building a CI/CD pipeline or triaging GitHub issues. Let's start with a definition of GitHub Actions.

    GitHub Actions is a CI/CD platform for automating your build, test, and deployment pipeline. You can build and test each pull request to your repository and deploy merged pull requests to production. GitHub Actions extends beyond DevOps by allowing you to run workflows when other events occur in your repository. You can, for example, run a workflow that adds the appropriate labels whenever someone creates a new issue in your repository. To run your workflows, GitHub provides virtual machines for Linux, Windows, and macOS, or you can host your self-hosted runners in your data center or cloud infrastructure.

    GitHub Actions Example

    For each commit sent to the main branch, we'll create a simple Actions workflow that can be executed manually or automatically. GitHub Actions are defined in your repository using the YAML syntax and stored in a directory called GitHub/workflows.

    To begin, fork and clone this repository on GitHub. Make a directory called .GitHub/workflows, then create a new file called hello-world-actions.yml and paste the code below into it.

    name: Hello-World-Actions 
    on: 
      push: 
        branches: [main] 
     
      workflow_dispatch: 
     
    jobs: 
      
      say_hello: 
     
        runs-on: ubuntu-latest 
     
        steps: 
          
          - name: Say Hello 
            run: echo Hello World! 
        
          - name: Say Goodbye 
            run: | 
              echo Job Finished. 
              echo Goodbye! 

    Here, is the example of the first “Hello World” 

    The Concepts Behind a GitHub Actions Workflow

    GitHub Actions is a native CI/CD tool for GitHub that runs alongside your code. You may have noticed a "Actions" tab in a GitHub repository at some point (hint: that's where GitHub Actions is). When you first open this tab, you'll see a brief description of what GitHub Actions is and some suggested workflows for your repository. That's when the fun begins. In the GitHub Marketplace, there are over 13,000 pre-written and tested CI/CD workflows and pre-built automation, as well as the ability to write your workflows (or customize an existing workflow) in simple YAML files.

    A GitHub Actions workflow can be configured to respond to any GitHub webhook event. That means you can use any GitHub webhook as a trigger for automation within your CI/CD pipeline, including third-party webhook events.

    GitHub Actions: Automate Your Workflow

    So, we've talked a little bit about GitHub Actions workflows, but sometimes it's just easier to see one in action:

    GitHub Action Workflow

    The workflow described above is made up of several components. These are some examples:

    The Components of GitHub Actions

    1. Workflows

    It is defined in a repository's .GitHub/workflows directory and a repository can have multiple workflows, each of which can perform a unique set of tasks.

    2. Events

    It is a specific activity in a repository that origin a workflow to run. When a person creates a pull request, opens an issue, or pushes a commit to a repository. for example, activity can come from GitHub.

    3. Jobs

    A job is a collection of workflow steps that run on the same runner. Each step is either a shell script to be executed or an action to be performed. Steps are carried out sequentially and are interdependent. Because each step is executed on the same runner, data can be shared from one step to the next.

    4. Actions

    It is a GitHub actions platform custom application that handles a complicated but frequently repeated task. Reduce the amount of repetitive code in your workflow files by using actions. An action can download your git repository from GitHub and install the toolchain required for your build environment.

    5. Runners

    When your workflows are triggered, they are executed by a runner. Each runner can only run one job at a time. To run your workflows, GitHub provides Ubuntu Linux, Microsoft Windows, and macOS runners; each workflow run executes in a new, freshly provisioned virtual machine. You can host your own runners if you require a different operating system or a specific hardware configuration.

    So, if you are looking for a career in web development and hands-on project experience with industry experts, then take a look at this Web Development complete course.

    Create an Example Workflow

    The workflow is defined by GitHub Actions using YAML syntax. Each workflow is saved in your code repository as a separate YAML file in a directory called .GitHub/workflows.

    In your repository, you can create an example workflow that executes a series of commands whenever code is pushed. GitHub Actions inspects the pushed code, installs the bats testing framework, and executes a simple command to return the bats version: bats -v.

    • Create the .GitHub/workflows/ directory in your repository to store your workflow files.
    • Create a new file called learn-GitHub-actions.yml in the .GitHub/workflows/ directory and add the following code.
    name: GitHub-actions-example 
    on: [push] 
    jobs: 
      check-bats-version: 
        runs-on: ubuntu-latest 
        steps: 
          - uses: actions/checkout@v3 
          - uses: actions/setup-node@v3 
            with: 
              node-version: '14' 
          - run: npm install -g bats 
    Run the files  
                                 - run: bats –v 

    Commit and push these changes to your GitHub repository.

    Essential Features of GitHub Actions (With Example)

    It lets you tailor your workflows to the specific requirements of your application and team. We'll go over some of the most important customization techniques, such as using variables, running scripts, and sharing data and artifacts between jobs, in this guide.

    1. Using the Variable in Your Workflows

    It includes default GitHub actions environment variables for each workflow run. If you want to use the custom environment variables, you can set these in your YAML file. Here, in this example, it demonstrates how you can create a custom variable using POSTGRES_HOST and POSTGRES_PORT. These variables are then available in the node client.js script

    jobs: 
      demo-job: 
          steps: 
            - name: Connect to your PostgreSQL 
              run: node client.js 
              env: 
                POSTGRES_HOST: postgres 
                POSTGRES_PORT: 5432 

    2. Adding Scripts to Your Workflow

    You can also actions to run scripts and shell commands, which gets executed on the assigned runner. This example determines how an action can use the run keyword to execute npm install –g bats on the runner.

    jobs: 
      demo-job: 
        steps: 
          - run: npm install -g bats 

    3. Sharing Data Between Jobs

    If you want to save the files for later use, you can save them as artifacts on GitHub. These are files that are generated when you build and test your code. It could include binary or package files, test results, screenshots, or log files, for example. Artifacts are linked to the workflow run in which they were created and can be reused by other jobs. For example, you can create your own file and upload it on artifacts.

    jobs: 
      demo-job: 
        name: Save output 
        steps: 
          - shell: bash 
            run: | 
              expr 1 + 1 > output.log 
          - name: Upload output file 
            uses: actions/upload-artifact@v3 
            with: 
              name: output-log-file 
              path: output.log 

    Using Expressions and Contexts in GitHub Actions(with Example)

    1. Expressions

    You can evaluate expressions in workflows and actions. It can be any combination of literal values, context references, or functions. With the operators, you can able to combine the literals, context references, and functions. For more details information about the contexts, check the “Contexts”.

    It is mostly used with the conditional keyword i.e. if in a workflow file to determine whether a step should run or not. You need to use the special syntax to tell GitHub to evaluate your expressions rather than a string.

    ${{ <expression> }} 

    For more detailed information about the conditional if keyword, see this “Workflow syntax for GitHub Actions”.

    Here, is an example of expression with if conditions.

    steps:
      - uses: actions/hello-world-GitHub-action@v1.1

      if: ${{ <expression> }} 

    Setting an GitHub environment variable

    env: 
      ENV_VAR: ${{ <expression> }} 

    2. Contexts

    Context information is available in workflows and actions. Through contexts, you are able to access information about the workflow runs, runner environments, jobs, and steps. Contexts, objects, and properties will depend on the workflow run conditions.

    You can access contexts using the expression syntax. For more information, see this “Expressions”.

    ${{ <context> }} 

    You can also access the contexts information using one of two syntaxes:

    • Index syntax: GitHub['sha']
    • Property dereference syntax: GitHub.sha

    Benefits of GitHub Actions

    GitHub Actions uses a comprehensive set of functionality and features to improve your developer experience. Here are a couple of examples:

    • Within the GitHub Flow, Automate Everything: It enables you to directly implement powerful automation in your repositories. You can create your actions or use readily available actions from the GitHub Marketplace to integrate your preferred tools directly into your repository.
    • Virtual Machines Hosted on Multiple Operating Systems: It offers hosted virtual machines (VM) running Ubuntu Linux, Windows, and macOS, allowing you to build, test, and deploy code directly to your preferred operating system—or all three at once.
    • Ready-to-use CI Templates that have already been written: GitHub Actions brings continuous integration (CI) directly to the GitHub flow with templates created by developers for developers.
    • Testing of Simple Containers and Operating Systems: Actions supports Docker and provides access to hosted instances of Ubuntu Linux, Windows, and macOS, making it simple to build and test code across systems—as well as automate build and test workflows.
    • It is Free to Use in Your Public Repository: GitHub Actions is free to use on all public repositories and has a monthly hosted workflow limit of 2,000 minutes on private repositories.

    Use Cases for GitHub Actions

    GitHub actions provide a powerful and adaptable platform for handling complex workflows and operations, such as sending a slack message to anyone when a pull request is ready for review.

    Some of the most common use cases for GitHub Actions are as follows:

    1. Build, test and deploy with the GitHub flow

    The simplest way to understand the functionality of GitHub flow is through continuous integration (CI) and continuous deployment (CD). GitHub actions enable you to run CI/CD workflows in your repository's containers and virtual machines. With the actions, you can also include third-party CI/CD tools in your repository.

    2. Automate repetitive tasks

    GitHub actions also aid in the automation of an infinite number of steps in the software development life cycle. You can automate sorting an issue or assigning a reviewer to a pull request when you create a pull request, a contributor joins your repository, a pull request is merged, or a third-party application is integrated on a given repository.

    3. Manage users easily at scale

    Maintainers frequently use GitHub actions to establish organizational rules such as developer permission, notifying reviewers of new pull requests, and much more. This allows you to manage a repository and all of the contributors in a given project with ease.

    4. Easily add preferred tools and services to your project

    GitHub actions allow you to connect to and integrate third-party tools and services directly into your repository. This was created to make it easier to manage typical workflows, as well as to build, test, and deploy code all within the GitHub flow.

    5. Rapidly review and test code on GitHub

    GitHub actions allow you to integrate a variety of third-party testing tools directly into your repo's workflow. Furthermore, GitHub actions support multi-container testing and "matrix-builds," which allow you to run multiple tests on Linux, Windows, and macOS at the same time.

    6. Keep the path of your projects

    you can use the GitHub actions to observe the application builds, estimate the performance, track errors, and more via integrations with third-party tools. GitHub actions also produce a live log that lets you watch your workflows run in real time.

    GitHub Actions Workflows for CI/CD

    At this point, it should come as no surprise that CI/CD is a powerful and widely used application of GitHub Actions.

    It's not the only CI/CD platform available, but its benefits stem from its tight integration with the rest of the GitHub platform—and the ability to trigger any part of a CI/CD pipeline off of any GitHub webhook.

    To get you started, here are some pre-built GitHub Actions CI/CD workflows:

    1. Node.js continuous integration: This workflow will perform a clean installation of node dependencies, cache and restore them, build the source code, and run tests across different versions of the node to help reduce human error.
    2. Run end-to-end tests on your codebase: A GitHub Actions workflow is available for running end-to-end UI tests on your application with Cypress, Applitools, or Mabl. Include these GitHub Actions in your repository to test your code before committing it to production.
    3. Deploy a container image to Amazon ECR: at the time you push to your default branch, this workflow will create and upload a new container image to Amazon ECR, followed by the deployment of a new task definition to Amazon ECS.

    Creating an Action File [Step-by-Step]

    Here, we will be creating a file to understand the working of the GitHub actions workflows. So, to get started, you will need a GitHub repository to create the GitHub actions.

    Step 1: Setting up the GitHub actions file

    • Create a .GitHub/workflows directory in your repository on GitHub if this directory does not already exist.
    • In the .GitHub/workflows directory, create a file named GitHub-actions-demo.yml. For more detailed information, go this "Creating new files.” it will help you to create files.
    • Copy the following YAML contents into the GitHub-actions-demo.yml file.
    name: GitHub Actions Example 
    on: [push] 
    jobs: 
      Explore-GitHub-Actions: 
     runs-on: ubuntu-latest 
        steps: 
     run: echo " The job was automatically triggered by a ${{ GitHub.event_name }} event." 
    run: echo " This job is now running on a ${{ runner.os }} server hosted by GitHub!" 
    run: echo " The name of your branch is ${{ GitHub.ref }} and your repository is ${{ GitHub.repository }}." 
     name: Check out repository code 
    uses: actions/checkout@v3 
    run: echo " The ${{ GitHub.repository }} repository has been cloned to the runner." 
    run: echo "️ The workflow is now ready to test your code on the runner." 
    name: List files in the repository 
    run: | 
    ls ${{ GitHub.workspace }} 
     run: echo " This job's status is ${{ job.status }}." 
    • select Create a new branch for this commit and start a pull request. Then, to create a pull request, click Propose new file.
    • Committing your workflow file to a branch in your repository triggers the push event and runs your workflow.

    Step 2: Run the files

    • On GitHub.com, navigate to the main page of the repository.
    • Under your repository name, click  Actions.
    • In the left sidebar, click the workflow you want to.
    • Under Jobs , click the Explore-GitHub-Actions job.

    GitHub Actions: Automate Your Workflow

    The log shows you how each of the steps was processed. Expand any of the steps to view its details.

    GitHub Actions: Automate Your Workflow

    Who is GitHub Actions Most Useful for?

    Actions can be used by operational managers or DevOps leaders to create custom paths that are tailored to their policies and strategic culture. GitHub Actions has become an even more powerful force for software release automation as a result of the recent emphasis on CI/CD. The developer community has been extremely positive about Actions since its release. Thousands of Actions and Workflows have been created by the community. With such a positive response from the developer community, Actions appear to be well on their way to becoming a standard feature.

    Summary

    GitHub Actions is an excellent addition to GitHub's already robust feature set. It aids in the automation of your development processes while also allowing you to monitor their execution from within GitHub. GitHub Actions is a CI/CD platform for automating your build, test, and deployment pipeline. You can build and test each pull request to your repository, or you can deploy merged pull requests to production.

    Web developers are at the forefront of all digital transformation in today's digital world, where over 175 websites go live every minute. If creating rich, functional web applications has always been your dream as a junior Front-End developer or a senior Full-Stack developer. So, if you are looking to master the fundamentals of web page development with HTML, CSS, and JavaScript before progressing to the creation of sophisticated web applications with in-demand frameworks such as React and Angular, then look at this KnowledgeHut’s Web Development complete course.

    Frequently Asked Questions (FAQs)

    1. How is GitHub used for building automation?

    When team members work on code on different git branches, the code is merged into a single working branch, which is then built and tested using automated workflows. This helps to ensure that everyone's code has been thoroughly tested and works properly together.

    2. How do I automate GitHub?

    Click the Manage automation button. Select automation preset from the Preset drop-down menu. Choose the workflow automation for the column that you want to configure.

    3. What can you use GitHub Actions for?

    Click Settings under the name of your repository. Click Actions in the left sidebar, then General. Select Allow OWNER, then select non-OWNER, actions, and reusable workflows, and add your required actions to the list.

    4. How do I automate deployment on GitHub?

    GitHub provides deployment starter workflows for a number of popular services, including the Azure Web App.

    5. What is Git in automation testing?

    It is built on the git platform. It enables you to keep local as well as remote copies of your project. A project that you can distribute to your team members so that they can use and update it from there.

    Profile

    Prateek Singh

    Blog Author

    Prateek Singh is a highly-skilled at building front-end interfaces. He loves JavaScript ecosystem and have designed & developed multiple products in his career. He has worked in Fintech, E-Commerce, Healthcare & Semi-conductor industries. Prateek enjoys conversation on Programming, Sports, Art, and Space Science. He is fascinated about origin of the universe, the existential reality & the design around us. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon