Github Actions - Your secret weapon

Imagine code evolving like a living organism, each tweak and fix captured like snapshots in a digital album. That's the magic of Git, a version control system that tracks your code's history. Think of it as a time machine for your project, letting you rewind, compare, and learn from the past.

But Git needs a home, and that's where GitHub comes in. It's a bustling online platform where developers host their Git repositories, share code, and collaborate on projects. Think of it as a vibrant marketplace for ideas, where you can showcase your work, find inspiration, and join forces with others to build amazing things.

GitHub Actions is your personal code-butler provided by GitHub! This automation platform stitches tasks like building, testing, and deploying into seamless workflows, triggered by every push or pull request. Think "mini-robots" whirring through your project, leaving you free to focus on the creative spark. So, embrace the automation revolution, let GitHub Actions take the wheel, and watch your development process hum smoothly like a well-oiled machine.

What is GitHub Actions

Imagine you're baking a cake. You gather ingredients (your code), mix them (build it), check if it's yummy (test it), and finally share it with everyone (deploy it). But wouldn't you love robots to handle all the mixing and checking while you focus on frosting the masterpiece?

That's what GitHub Actions does! It's like a robot army for your code, automating repetitive tasks in your development process. You tell it what to do in simple steps, like "mix for 5 minutes" or "run all the tests," and it just gets it done, triggered by every new batch of code (code change, pull request). No more manual work, just smooth sailing from baking to dessert!

So, GitHub Actions is your personal kitchen assistant for coding, freeing you to be the creative chef and whip up amazing software!

Learn about GitHub Actions

GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline. You can create workflows that build and test every pull request to your repository, or deploy merged pull requests to production.

Github actions triggered based on the workflows files, let's create a workflow.

  • In your repository, create the .github/workflows/ directory to store your workflow files.

  • In the .github/workflows/ directory, create a new file called learn-github-actions.yml and add the following code.

  •       name: learn-github-actions
          run-name: ${{ github.actor }} is learning GitHub Actions
          on: [push]
          jobs:
            check-bats-version:
              runs-on: ubuntu-latest
              steps:
                - uses: actions/checkout@v4
                - uses: actions/setup-node@v3
                  with:
                    node-version: '14'
                - run: npm install -g bats
                - run: bats -v
    
  • Commit these changes and push them to your GitHub repository.

Your new GitHub Actions workflow file is now installed in your repository and will run automatically each time someone pushes a change to the repository. To see the details about a workflow's execution history go to Actions tab from your repository and in the left sidebar, click the workflow you want to see.

Screenshot of the tabs for the "github/docs" repository. The "Actions" tab is highlighted with an orange outline.

To help you understand how YAML syntax is used to create a workflow file, this section explains each line of the introduction's example:

# Optional - The name of the workflow as it will appear in the "Actions" tab of the GitHub repository. If this field is omitted, the name of the workflow file will be used instead.
name: learn-github-actions
# Optional - The name for workflow runs generated from the workflow, which will appear in the list of workflow runs on your repository's "Actions" tab. This example uses an expression with the `github` context to display the username of the actor that triggered the workflow run. For more information, see "[AUTOTITLE](/actions/using-workflows/workflow-syntax-for-github-actions#run-name)."
run-name: ${{ github.actor }} is learning GitHub Actions

# Specifies the trigger for this workflow. This example uses the `push` event, so a workflow run is triggered every time someone pushes a change to the repository or merges a pull request.  This is triggered by a push to every branch; for examples of syntax that runs only on pushes to specific branches, paths, or tags, see "[AUTOTITLE](/actions/reference/workflow-syntax-for-github-actions#onpushpull_requestpull_request_targetpathspaths-ignore)."
on: [push]

# Groups together all the jobs that run in the `learn-github-actions` workflow.
  jobs:

# Defines a job named `check-bats-version`. The child keys will define properties of the job.
  check-bats-version:

# Configures the job to run on the latest version of an Ubuntu Linux runner. This means that the job will execute on a fresh virtual machine hosted by GitHub. For syntax examples using other runners, see "[AUTOTITLE](/actions/reference/workflow-syntax-for-github-actions#jobsjob_idruns-on)"
    runs-on: ubuntu-latest

# Groups together all the steps that run in the `check-bats-version` job. Each item nested under this section is a separate action or shell script.
    steps:

# The `uses` keyword specifies that this step will run `v4` of the `actions/checkout` action. This is an action that checks out your repository onto the runner, allowing you to run scripts or other actions against your code (such as build and test tools). You should use the checkout action any time your workflow will use the repository's code.
      - uses: actions/checkout@v4

# This step uses the `actions/setup-node@v3` action to install the specified version of the Node.js. (This example uses version 14.) This puts both the `node` and `npm` commands in your `PATH`.
      - uses: actions/setup-node@v3
        with:
          node-version: '14'

# The `run` keyword tells the job to execute a command on the runner. In this case, you are using `npm` to install the `bats` software testing package.
      - run: npm install -g bats

# Finally, you'll run the `bats` command with a parameter that outputs the software version.
      - run: bats -v

What can you do with Github Actions Actually

Here is a list of task you can do with Github Actions and you can find a list of events from here.

Build and test your code:

  • Run your build scripts and tools (e.g., Maven, Gradle, npm)

  • Execute unit and integration tests

  • Perform code coverage analysis

  • Generate documentation

Deployment and release:

  • Deploy your code to various platforms (e.g., cloud providers, servers)

  • Automate release processes like tagging, versioning, and publishing

  • Trigger notifications on successful deployments

  • Rollback deployments in case of errors

Continuous Integration and Continuous Delivery (CI/CD):

  • Set up automated pipelines for your build, test, and deployment process

  • Trigger actions on every push, pull request, or schedule

  • Track the progress of your pipelines and visualize their status

  • Integrate with other CI/CD tools and platforms

Other automation tasks:

  • Run security scans and vulnerability checks

  • Manage project dependencies

  • Perform code formatting and linting

  • Send emails and notifications

  • Run database migrations

  • Back up your code repositories

  • Generate reports and dashboards

  • Interact with external APIs

  • Run actions on a schedule

  • ... and much more!

Okay, enough learning let's build something.

Examples

Here are some examples about Github Actions.

Run a test

Imagine we have a react application, and every time we push a new changes we want to check that, the test is perfectly work or not.

So for this we should create a YAML file in the .github/workflows directory (e.g., react-tests.yml) and put the code below in the workflow file.

name: React Tests

on: [push]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 20
      - run: npm ci
      - run: npm test

Push the changes in your Github repository and see the magic.

Build and deploy

Okay let's make an application to build and deploy a javascript application to GitHub pages.

As before create a new file in your project at .github/workflows/deploy.yml and paste in the YAML below.

name: Deploy to GitHub Pages

on:
  # Trigger the workflow every time you push to the `main` branch
  # Using a different branch name? Replace `main` with your branch’s name
  push:
    branches: [ main ]
  # Allows you to run this workflow manually from the Actions tab on GitHub.
  workflow_dispatch:

# Allow this job to clone the repo and create a page deployment
permissions:
  contents: read
  pages: write
  id-token: write

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout your repository using git
        uses: actions/checkout@v3
      - name: Install, build, and upload your site
        uses: withastro/action@v1
        # with:
          # path: . # The root location of your Astro project inside the repository. (optional)
          # node-version: 18 # The specific version of Node that should be used to build your site. Defaults to 18. (optional)
          # package-manager: pnpm@latest # The Node package manager that should be used to install dependencies and build your site. Automatically detected based on your lockfile. (optional)

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v1

Your site should now be published! When you push changes to your Astro project’s repository, the GitHub Action will automatically deploy them for you.

Deploy and run actions on server

Now let's create a deployment actions for a PHP (Laravel) application.

name: Deploy to DO

# Trigger the workflow on push and
# pull request events on the production branch
on:
  push:
    branches:
      - main

# Authenticate to the the server via ssh
# and run our deployment script
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to server
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          port: ${{ secrets.PORT }}
          password: ${{ secrets.PASSWORD }}
          script: |
            cd /var/www/taksme
            source ~/.nvm/nvm.sh
            sh ./deploy.sh

To run this you have to need set some env variables in your GitHub repository.

HOST="ip-address-of-server"
USERNAME="deploy-user"
PORT="21" # by default 21, use your port of diff.
PASSWORD="user-password"

You can find Digital Ocean deployment article from here.

Run a schedular

This is an interesting actions, this workflow generate a GitHub contribution graph as animation in your repository.

name: gitartwork from a contribution graph
on:
  push:
  schedule:
    - cron: '* */24 * * *'
jobs:
  build:
    name: Make gitartwork SVG
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: jasineri/gitartwork@v1
        with:
          # Use this username's contribution graph
          user_name: 4msar
          # Text on contribution graph
          text: MSAR
      - uses: jasineri/simple-push-action@v1

This actions will trigger everyday at 12:00 AM and generate a artwork like below.

Okay, hope you enjoy the examples and got an idea what you can do with GitHub actions.

Conclusion

In conclusion, GitHub Actions stands as a transformative tool in the world of software development, emerging as a secret weapon for streamlining workflows, automating tasks, and fostering collaboration within teams.

Its seamless integration with the GitHub ecosystem empowers developers to create, customize, and deploy workflows that suit their unique project needs. The versatility and flexibility of Actions not only enhance productivity but also elevate the overall quality of software by enabling continuous integration, testing, and deployment.

Embracing GitHub Actions isn't just adopting a tool; it's embracing a culture of efficiency, innovation, and collaborative development in the modern software landscape.


Resources