Home Cloud & Networking Automating Workflows with GitHub Actions

Automating Workflows with GitHub Actions

By Priscila Heller
books-svg-icon Book
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $43.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Learning the Foundations for GitHub Actions
About this book
GitHub Actions is one of the most popular products that enables you to automate development tasks and improve your software development workflow. Automating Workflows with GitHub Actions uses real-world examples to help you automate everyday tasks and use your resources efficiently. This book takes a practical approach to helping you develop the skills needed to create complex YAML files to automate your daily tasks. You'll learn how to find and use existing workflows, allowing you to get started with GitHub Actions right away. Moving on, you'll discover complex concepts and practices such as self-hosted runners and writing workflow files that leverage other platforms such as Docker as well as programming languages such as Java and JavaScript. As you advance, you'll be able to write your own JavaScript, Docker, and composite run steps actions, and publish them in GitHub Marketplace! You'll also find instructions to migrate your existing CI/CD workflows into GitHub Actions from platforms like Travis CI and GitLab. Finally, you'll explore tools that'll help you stay informed of additions to GitHub Actions along with finding technical support and staying engaged with the community. By the end of this GitHub book, you'll have developed the skills and experience needed to build and maintain your own CI/CD pipeline using GitHub Actions.
Publication date:
November 2021
Publisher
Packt
Pages
216
ISBN
9781800560406

 

Chapter 1: Learning the Foundations for GitHub Actions

Independently of your current level of expertise, by the time you have finished reading the last chapter in this book, you will have completed all the steps needed to implement a cohesive Continuous Integration/Continuous Delivery (CI/CD) workflow using GitHub Actions. You will also have familiarity with many other systems and practices that have helped GitHub Actions gain popularity in the software development and DevOps world.

Automation is the heart of most modern DevOps practices. Many tools have been created to allow for automated tests, builds, and deployment, and GitHub Actions is one of those tools. It is an elegant solution that offers the convenience of creating and managing CI and CD workflows from GitHub, the largest code-hosting platform in the world.

It is important to understand the basic concepts of CI and CD before creating and managing GitHub Actions workflows. It is also relevant to learn about some of the technologies that make GitHub Actions possible, such as GitHub—the platform where all GitHub Actions live— and YAML Ain't Markup Language, commonly known as YAML—the markup language that powers GitHub Actions workflows. In this chapter, you will learn more about the following topics:

  • Understanding the basics of CI/CD
  • Introduction to GitHub: creating a user account
  • Discovering the basics of Git and GitHub
  • Introducing YAML
 

Technical requirements

In this introductory chapter, you will create a GitHub account and a GitHub repository and will review a YAML file, as hands-on practice in preparation for the subsequent chapters in this book. To accomplish all that, you will need the following:

  • A computer or laptop with access to the internet, and modern browsers, such as the latest versions of Safari, Firefox, Chrome, and Microsoft Edge.
  • A command-line utility: For macOS and Linux, you will need a system such as Terminal, where you can run shell and Git commands. For Windows, you will need to download and install Git Bash, if you do not already have it installed.
  • An email address, which you will need in order to create a GitHub account.
  • A text editor such as Atom, Visual Studio Code (VS Code), Sublime, and so on.
 

Understanding the basics of CI/CD

Before jumping into the core concepts of CI and CD, it is helpful to understand more about the history and evolution of the software development life cycle. While this section will not present a comprehensive list of all software development methods that may have led to the progress and adoption of CI and CD practices, it will present relevant concepts that will help illustrate why CI and CD are widely adopted today.

A brief trip through the history of software development

Many believe that software engineering dates back to the 1960s. During that time, software engineering and computing in general were costly, which likely nudged software engineers into practicing software development in a similar way to how hardware production was done. In other words, software development started as a slow, cautious, and methodical practice that followed a sequence of steps aimed at delivering perfect products. This method is known currently as the Waterfall model, which is composed of seven phases, each of which depends on the successful and sequential completion of the previous phase. The Waterfall model is known for its inflexible, process-oriented, and sequential nature.

Over time, many issues surfaced in the Waterfall model. For example, extensive and time-consuming planning and approvals were needed before software engineers even had the chance to start writing code. By the time software was written, tested, and deployed, months had passed and customers' needs had changed completely. The Waterfall model did not allow for many iterations, and when changes were needed, this was a long and expensive process that often created bottlenecks and resulted in obsolete or unused features.

While the Waterfall model was predominant between the 1960s and 1980s, there was an awareness that a fast, flexible, lightweight, product-focused, and people-focused—as opposed to process-focused—approach was needed.

In the early 1990s, Extreme Programming (XP) reinforced the concept that tests should be written to describe how code should work, which was also the center of test-driven development (TDD) practices. The XP community then announced a practice that later would help shape what is today known as CI. They announced the use of automated processes to frequently integrate all code across developing teams, with the intention of delivering code that could be sent to production at any given time. This practice has resulted in many builds per day, which improves the predictability and efficiency of the software development life cycle and allows for constant interaction with customers to satisfy their ever-changing needs. This process, in conjunction with other philosophies and software development methods that were gaining traction in the 1990s, later formed the Agile Manifesto.

Many similar software development practices emerged between the 1990s and early 2000s. A group of 17 independent thinkers representing XP, Scrum, Adaptive Software Development (ASD), and other communities met to find their commonalities in approaches, as well as to try to find a different approach to heavyweight software development practices.

The Agile Manifesto was created at the end of that meeting when, among all the different software development practices, the Agile Alliance was formed.

Agile encompasses many practices that are lightweight, code- and people-oriented, and highly adaptive. Other modern approaches, some of which predate Agile, are also based on the idea that the software development cycle should be highly adaptive and built frequently. Based on these premises, CI and CD have gained more space among software developers across the globe.

The main idea behind CI is that automated processes should be in place to test and build software many times a day. This is important because bugs are commonly introduced at the intersection or integration of two different pieces of code. In other words, CI practices manage processes, which allows software engineers to focus on the code itself.

CD follows in the footsteps of CI. It focuses on gathering all changes to code—such as new features, bug fixes, and configuration changes—and sending them to users—or production—as safely, sustainably, and quickly as possible.

CI in conjunction with CD can be both powerful and challenging, given the shift in culture that must accompany the adoption of these practices. When combined and adopted across a company, they can help ensure high-quality, lightweight, and adaptive software development.

Many tools have been created to help software and operations engineers build a CI/CD pipeline. GitHub Actions is arguably the most popular one: it makes it easier to automate the building, testing, and deployment of code on any platform—including Linux, macOS, and Windows—without leaving the repository where the code lives. All of this can happen while GitHub manages the execution and provides rich feedback and security for every step in your workflow.

Because GitHub Actions happen within a repository hosted on GitHub, a GitHub account is needed. Basic knowledge of GitHub as a platform is also helpful. In the next section, you will learn how to create a GitHub account, as well as how to use some basic Git and GitHub features.

 

Introduction to GitHub: creating a user account

GitHub is the largest code-hosting platform in the world. It uses Git as version control, and most activities happen on a repository hosted on GitHub. This and other features such as pull requests, project boards, and GitHub Actions allow software engineers, operations engineers, product managers, and everybody else involved in software development to collaborate in one place.

To start hosting code on GitHub, a user account is needed. Different accounts can be created on GitHub. While some account types are paid for, such as Team and Enterprise accounts, it is also possible to create a free user account. You can learn about all the different account types offered by GitHub, as well as the features offered with each account, by accessing https://docs.github.com/en/free-pro-team@latest/github/getting-started-with-github/types-of-github-accounts.

While the GitHub Free account type will be used throughout this book, learning about the features offered in other account types may help you choose an account that is appropriate for the scope of your project.

In the next few sections, you will learn how to create a free user account, as well as set up authentication options such as personal access tokens (PATs) and a Secure Shell (SSH) key.

Creating a free user account on GitHub

If you already have a GitHub account, you will not need to follow the steps in this section.

When you create a personal user account on GitHub, you have access to features such as unlimited public and private repositories and 2,000 actions minutes per month. After you create a user account, you can use a few different authentication methods to retrieve data related to your account and its resources, outlined as follows:

  • On the web browser, you can provide your username and password.
  • On the application programming interface (API), you can use a PAT.
  • On the command line, you can use an SSH key.

The next steps will show you how to create a GitHub Free user account. You will also learn how to generate a PAT and an SSH key that will be used in upcoming sections and chapters.

To sign up for a GitHub Free personal user account, follow these steps:

  1. Navigate to https://github.com/join.
  2. Fill in the blank fields with your information. Note that you will need to choose a unique username. An existing email address will also be needed, as well as a password.
  3. Solve the verification puzzle and click Verify. Then, click on Create account.
  4. Follow the prompts on the next page and click Complete setup. An email will be sent to the email address you provided in Step 2.
  5. The next screen will ask you to verify your email address. Although the account creation does not depend on having your email verified, you will not be able to use certain features—such as GitHub Actions—without a verified email address. For this reason, verifying your email address is required for the scope of this book.
  6. Open your email account. You should see an email that looks like this:
    Figure 1.1 – An example of the email sent by GitHub requesting you to verify your email address

    Figure 1.1 – An example of the email sent by GitHub requesting you to verify your email address

  7. Click on Verify email address.

Great job! Your personal user account has been created on GitHub, and you should be able to find it by navigating to https://github.com/your-username, where your-username is the unique username that you chose in Step 2.

Creating a PAT

Many popular GitHub Actions workflows use a PAT or an SSH key. This section will walk you through the creation of a PAT, in preparation for future chapters where one will be needed.

A PAT is a string of characters that can be used in place of a password against the GitHub API and on the command line. Different scopes can be attributed to a PAT to specify exactly what level of access is needed. Scopes are often chosen to limit access: nothing beyond the selected scopes can be accessed.

The next steps will guide you in creating a PAT with the repo, user, and workflow scopes. Understanding all the available scopes on GitHub is not part of what will be covered in this book. However, it is helpful to learn what kinds of access each scope grants. To learn more, see this documentation: https://docs.github.com/en/free-pro-team@latest/developers/apps/scopes-for-oauth-apps#available-scopes.

To create a PAT, follow these steps:

  1. Navigate to https://github.com/settings/tokens and click on Generate new token, as illustrated in the following screenshot:
    Figure 1.2 – Generating a new PAT

    Figure 1.2 – Generating a new PAT

  2. On the next screen, type a note that will help you identify what the PAT will be used for. Next, select the repo, workflow, and user scopes. Then, click on Generate token. The PAT scopes are shown in the following screenshot:
    Figure 1.3 – PAT scopes

    Figure 1.3 – PAT scopes

  3. On the next screen, make sure to copy your PAT and store it somewhere so that you can access it later.

Great work so far! You will use your newly created PAT in future sections of this book.

About SSH keys

An SSH key is an identification method that you can use to authenticate against a server. SSH keys are used as an access credential in the SSH protocol, which is a secure method for remote login from one server to another. SSH keys are often used in shell scripting, which is commonly used in GitHub Actions. Another common use of SSH keys is as an access tool while using the SSH protocol to clone a repository hosted on GitHub down to your local computer. Future sections will provide more details about cloning a repository hosted on GitHub.

Checking for existing SSH keys

As best practice and in case you are not sure whether you already have an SSH key, you should check for existing keys, as follows:

  1. Open Terminal (if you're using Linux or macOS) or Git Bash (if you're using Windows).
  2. Enter the following command, which will list all files in the ./~ssh directory (if they exist) and press Enter on your keyboard:
    $ ls -al ~/.ssh
  3. Look for an output that might resemble this:
total 64
drwx------   2 user group  4096 Dec 26  2018 .
drwx--x--x 127 user group 16384 Mar 14 04:41 ..
-rw-------   1 user group  1675 Sep 15  2008 id_rsa
-rw-r--r--   1 user group   394 Mar  7  2010 id_rsa.pub 

If no files are listed, stop here. You will need to generate a new SSH key. Follow the instructions in the Creating an SSH key section.

If you see a list of files like the ones in Step 3, stop here. You will not need to generate a new SSH key, but you may need to add your existing key to the SSH agent. Follow the instructions in the Adding the SSH key to the SSH agent section.

Creating an SSH key

The next steps will help you generate an SSH key on your local device and add it to your GitHub user account. These steps are important to grant your device remote access to the GitHub servers to execute operations such as cloning a repository hosted on GitHub down to your local device.

The steps to create an SSH key are different depending on your device's operating system. The following steps will provide instructions on how to create an SSH key on Windows, Linux, and macOS:

  1. Open Terminal (if you are using Linux or macOS) or Git Bash (if you're using Windows).
  2. Enter the following command, replacing your_email@example.com with the email address you used to create your GitHub user account:
    $ ssh-keygen -t ed25519 -C "your_email@example.com"
  3. Press Enter on your keyboard. This command creates a new SSH key, and you will see the following output on your screen:
    Generating public/private ed25519 key pair.
  4. Follow the prompts on the screen. When asked to enter a file in which to save the key, press Enter on your keyboard to accept the default location or type the directory where you would like the key to be saved to.
  5. Although a passphrase is optional, it is recommended to enter it. Without a passphrase, anyone who gains access to your computer can also gain access to other systems that use your SSH key. When prompted, type a passphrase and press Enter on your keyboard. The output will look like this:
Enter file in which to save the key (default-file-path):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in (default-location-or-user-entered-location).
Your public key has been saved in (filesystem-location).
The key fingerprint is:
SHA256:[redacted] your-email@example.com

Excellent! Your SSH key has been generated. Next, you will need to add this newly generated key to the SSH-agent.

Adding the SSH key to the ssh-agent

Although this step is not mandatory, adding the SSH key to the SSH agent is a best practice that will help keep your SSH key safe.

The SSH-agent is an SSH key manager. It helps keep your SSH key safe because it protects your SSH key from being exported. The SSH agent also saves you from having to type the passphrase you created in Step 5 of the previous section every time your SSH key is used.

Proceed as follows:

  1. Start the SSH-agent in the background, by entering the following command in Terminal or Git Bash and hitting Enter on your keyboard:
    $ eval "$(ssh-agent -s)"
  2. If you are using Windows or Linux, proceed to Step 3. If you are using macOS Sierra 10.12.2 or later, you will need to edit your ~/.ssh/config file to include the UseKeychain option.

    First, verify that the ~/.ssh/config file exists. In Terminal, type the following command, then press Enter on your keyboard:

    $ open ~/.ssh/config 
  3. If the file exists, proceed to the next step. If the file does not exist, use the following command to create it:
    $ touch ~/.ssh/config
  4. Make sure the content of your ~/.ssh/config file looks like that shown in the following code snippet. You may have other lines in your file with different options, and that is OK. For this step, ensure that the AddKeysToAgent line is added to your file:
    Host *
    AddKeysToAgent yes
    Add your SSK key to the SSH-agent:
  5. If you are using macOS, skip this step and proceed to Step 5. If you are using Linux or Windows, open your Terminal or Git Bash, type the following command, and press Enter on your keyboard:
    $ ssh-add ~/.ssh/id_ed25519
  6. If you are using macOS and you are using a passphrase to protect your SSH key, you will need to pass the -K option with the ssh-add command, as shown in the following code snippet. If you are not using a passphrase, you do not need to pass the -K option.
  7. Open your Terminal, type the following command, and press Enter on your keyboard:
$ ssh-add -K ~/.ssh/id_ed25519

Well done! Your SSH key has been added to the SSH agent. Next, you will need to add your newly generated SSH key to your GitHub account on GitHub.

Adding your SSH key to your GitHub user account

When you add your SSH key to your GitHub user account, you have another secure authentication alternative to interact with GitHub features. For example, when you use the SSH protocol and SSH key to clone a GitHub-hosted repository, you will not need to provide your username and PAT. Although you can use other means to clone a repository, such as HyperText Transfer Protocol (HTTP), SSH is more secure and convenient.

To add your SSH key to your GitHub user account, follow these next steps:

  1. Copy your SSH key to the clipboard. The following command will work for both Terminal and Git Bash:
    $ cat ~/.ssh/id_ed25519.pub 
  2. Navigate to your GitHub user account at https://github.com/settings.

    On the left-hand side menu, click on SSH and GPG keys, as illustrated in the following screenshot:

    Figure 1.4 – The SSH and GPG keys menu option on your GitHub account settings page

    Figure 1.4 – The SSH and GPG keys menu option on your GitHub account settings page

  3. On the next screen, click on New SSH key, as illustrated in the following screenshot:
    Figure 1.5 – The SSH keys section of your GitHub account settings

    Figure 1.5 – The SSH keys section of your GitHub account settings

  4. Next, add a Title that will help you identify your SSH key. Then, paste your SSH key that you copied in Step 1 into the Key textbox, as illustrated in the following screenshot:
    Figure 1.6 – Adding a new SSH key

    Figure 1.6 – Adding a new SSH key

  5. Lastly, click on Add SSH key. Once you click the button, you may be prompted to enter your GitHub user account password.

Excellent work! You have configured the basic functionalities of your GitHub user account. Although it is out of the scope of this book, you can customize other features of your GitHub account by navigating to https://github.com/settings.

In the next section, you will learn the basic Git commands and read more about a few more GitHub features that will help build the foundation needed to create GitHub Actions workflows.

 

Discovering the basics of Git and GitHub

Git is a version control system created in 2005 by Linus Torvalds to improve code versioning and collaboration. Git is commonly used by software developers for file version control locally. Although there are many ways to use Git—including graphical user interface (GUI) applications—this book will only cover the basic commands as run on a command-line interface (CLI), to help you manipulate files locally and work with repositories hosted on GitHub.

Independently of the operating system that you are currently using, if you are using Git for the first time, you will need to configure it first. The next steps will walk you through this configuration, which only needs to be done once on your machine.

Configuring Git

Git is installed by default on Terminal and Git Bash. If you are not using one of these options to access the command line, ensure the option you are using has Git installed. If it does not, you can download Git by navigating to https://git-scm.com/book/en/v2/Getting-Started-Installing-Git.

One of the many commands in Git is git config, which will allow you to set configuration variables to control how Git operates and how it looks. You can then see these variables in either the ~/.gitconfig file or the ~/.config/git/config file. Although there are many variables that you can customize, this book will only cover the basic ones.

Proceed as follows:

  1. First, start by setting your name and email address, which Git uses for every commit you create.

    Important note

    It is highly recommended to use the same email address you used to create your GitHub user account.

  2. Open Terminal or Git Bash and enter the following commands, replacing your name and email address accordingly. Then, press Enter on your keyboard:
    $ git config --global user.name "Priscila Heller"
    $ git config --global user.email testesdapri@gmail.com
  3. Next, configure your default branch name—available for Git versions 2.28 onward—as follows:
    $ git config --global init.defaultBranch main
  4. To verify that all your settings are correct, use the git config --list command. The output will look similar to this:
$ git config --list
user.email=testesdapri@gmail.com
user.name=Priscila Heller
core.bare=false

Great! Now that you are done configuring Git, it's time to investigate the main Git commands commonly used in software development.

Basic Git commands

The basic Git commands that will be used throughout this book are listed here:

  • git init
  • git status
  • git checkout -b <branch-name>
  • git add
  • git commit -m "your message goes here"
  • git remote add
  • git push
  • git pull
  • git clone

git init and git status

Imagine that you have a folder on your computer, with many files containing code to create an application. This code was never version-controlled because you had not heard of Git up until now. Git allows you to transform that folder into a Git repository, by simply running git init from within that folder.

In the following example, the name of the folder is soon-to-be-a-github-repo. From within that folder, running git status will show a message explaining that the folder is not a Git repository:

$ git status
fatal: not a git repository (or any of the parent directories): .git

Transforming this folder into a Git repository is as simple as running git init. After running git init, the output of git status is also different, as can be seen here:

$ git init
Initialized empty Git repository in /Users/testesdapri/Desktop/soon-to-be-a-github-repo/.git/
$ git status
On branch main
No commits yet
Untracked files:
  (use "git add <file>..." to include in what will be committed)
            README.md
            index.html
            style.css
nothing added to commit but untracked files present (use "git add" to track)

The preceding output shows that git init transformed the soon-to-be-a-github-repo folder into a Git repository. Note the .git extension in the folder path. Considering that this folder is now a Git repository—also known as a local repository, git status also shows a different output: the status of the working repository. Note how it now shows untracked files, the files within the repository, the working branch, and recommended next commands.

git checkout and git add

The output of the git status command also shows On branch main. In Git, if the repository is a tree, a branch is—as its name suggests—a branch off that tree. Branches are created to allow for changes to be safely added to the code. Generally, those changes will eventually be merged back into the main branch of the repository, which is often called the master or main. It is considered best practice to create branches in order to work on code, and not work directly on the main branch. This will help ensure the safety and stability of your project.

In the next example, a branch will be created to add some changes to the code that lives inside the soon-to-be-a-github-repo repository. To do that, the git checkout -b read-me-feature command will be used. This command will check out from the main branch and create a new branch called read-me-feature, as illustrated in the following code snippet:

$ git checkout -b read-me-feature
Switched to a new branch 'read-me-feature'

Now that a new branch has been created, new lines of code can be added to a file of your choice. As an example, I am adding the line "Look! This repository has a new branch!" to the README.md file, as you can see here:

Figure 1.7 – Adding a line of code to the README.md file

Figure 1.7 – Adding a line of code to the README.md file

Once those changes are completed, they can be added to staging using the git add . command. The dot (".") is used in this case to add all changed files to staging.

Note that the git add . command did not produce any output. This is expected. To verify that your editions have been added to staging, use git status, as illustrated in the following code snippet:

$ git add .
$
$ git status
On branch read-me-feature
No commits yet
Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
     new file:   README.md
      new file:   index.html
      new file:   style.css

All changes have been added to the index, or staging, which is the area that holds a snapshot of all changes made to the working tree (also known as the working directory, or repository). The next step, as the preceding output suggests, is to commit those changes.

git commit

In Git, the term commit refers to recording changes to the repository. After running git add, this is a suggested next step, which can be accomplished by running git commit -m "short message to describe your change".

The changes to the files within the soon-to-be-a-github-repo repository have already been added to the index. The following output shows what happens once the git commit command is run:

$ git commit -m "Added a few generic lines"
[read-me-feature (root-commit) 53bd7bf] Added a few generic lines
 3 files changed, 17 insertions(+)
 create mode 100644 README.md
 create mode 100644 index.html
 create mode 100644 style.css

Typically, the next step after running git commit is to run git remote add in some cases, and then run git push to push the local changes up to the upstream remote repository, which—in this case—will be hosted on GitHub.

Important note

Before proceeding with the git remote add and git push commands, make sure you have created a repository on GitHub.

A public repository called a-github-repo was created on GitHub. Because this repository was created on a remote host, it is often referred to as the remote repository.

The git remote add command will create a connection between your soon-to-be-a-github-repo local repository and your https://github.com/user/a-github-repo remote repository. This connection will allow you to track changes that are happening on the remote repository, as well as send changes made to your local repository to the remote repository upstream on GitHub.

The git remote add command does not return anything when it is completed successfully. You can use the git remote -v command to list the remotes and confirm that everything worked as expected. Your output should look like this:

$ git remote add origin https://github.com/testesdapri/a-github-repo.git
$ git remote -v
origin    https://github.com/testesdapri/a-github-repo.git (fetch)
origin    https://github.com/testesdapri/a-github-repo.git (push)

Now that both the local repository and the remote repository are connected, you can push your changes to the remote repository. However, observe here the results of running git push:

$ git push
fatal: The current branch read-me-feature has no upstream branch.
To push the current branch and set the remote as upstream, use
    git push --set-upstream origin read-me-feature

Important note

The git push --set-upstream origin <new-branch> command will need to be run every time you create a branch locally that does not have a remote counterpart. If you don't remember this in the future, do not worry. Git will remind you with a message similar to the one shared previously.

To fix this, follow the instructions on the preceding output and run git push --set-upstream origin read-me-feature. This command will push your local changes to the remote repository, as well as create a remote read-me-feature branch in the remote repository. Any subsequent changes made locally to the read-me-feature branch can be pushed to the remote repository by simply running git push origin read-me-feature. The git push --set-upstream origin read-me-feature command is shown in the following snippet:

$ git push --set-upstream origin read-me-feature
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (5/5), 564 bytes | 564.00 KiB/s, done.
Total 5 (delta 0), reused 0 (delta 0)
To https://github.com/testesdapri/a-github-repo.git/
 * [new branch]      read-me-feature -> read-me-feature
Branch 'read-me-feature' set up to track remote branch 'read-me-feature' from 'origin'.

Now that your changes have been pushed to GitHub successfully, your remote repository should look similar to this:

Figure 1.8 – A remote repository on GitHub

Figure 1.8 – A remote repository on GitHub

You have learned how to push code from your local repository to the remote repository on GitHub. Next, you will learn how to pull code from a remote repository to your local repository.

git pull

If any changes are made directly on the web interface of GitHub, they will not automatically reflect in your local repository. To see those changes reflected on your local repository, you can run the git pull command. This command will incorporate the changes from the remote repository into the local repository.

The following output shows how git branch -a was used to list all the available branches and how git checkout main was used to move from the read-me-feature branch to the main branch. The asterisk (*) next to the branch indicates that it is in use:

$ git pull
From https://github.com/testesdapri/a-github-repo
 * [new branch]      main       -> origin/main
Already up to date.
$ git branch -a
* read-me-feature
  remotes/origin/main
  remotes/origin/read-me-feature
$ git checkout main
Branch 'main' set up to track remote branch 'main' from 'origin'.
Switched to a new branch 'main'
$ git branch -a
* main
  read-me-feature
  remotes/origin/main
  remotes/origin/read-me-feature

git clone

The git clone command is commonly used to clone a repository hosted on GitHub down to your local machine. As an example, consider that you want to contribute to an Open-source project such as the https://github.com/github/docs repository. Although you could use the web interface to add your contributions, it is often preferred to have the code stored locally. To copy the remote repository down to your local machine, navigate to your repository page and click on Code, as illustrated in the following screenshot:

Figure 1.9 – Retrieving the Uniform Resource Locator (URL) to clone a remote repository

Figure 1.9 – Retrieving the Uniform Resource Locator (URL) to clone a remote repository

Then, copy either the HTTP Secure (HTTPS) link or the SSH link to your clipboard.

Important note

If you copy the HTTPS link, you will need to use your PAT in the next step. If you copy the SSH link, you will need to use your SSH key in the next step.

Next, open your Terminal or Git Bash and navigate to the directory where you want the copy of the remote repository to live. Then, enter the https://github.com/github/docs.git git clone command if you copied the HTTPS link in the last step, or the git clone git@github.com:github/docs.git command if you copied the SSH link. Hit Enter on your keyboard.

You should see an output like this, which confirms that the clone was successful:

# HTTPS clone
$ git clone https://github.com/github/docs.git
Cloning into 'docs'...
remote: Enumerating objects: 68677, done.
remote: Total 68677 (delta 0), reused 0 (delta 0), pack-reused 68677
Receiving objects: 100% (68677/68677), 167.24 MiB | 7.23 MiB/s, done.
Resolving deltas: 100% (46006/46006), done.
Checking out files: 100% (27024/27024), done.
#SSH clone
$ git clone git@github.com:github/docs.git
Cloning into 'docs'...
remote: Enumerating objects: 68677, done.
remote: Total 68677 (delta 0), reused 0 (delta 0), pack-reused 68677
Receiving objects: 100% (68677/68677), 167.24 MiB | 15.41 MiB/s, done.
Resolving deltas: 100% (46006/46006), done.
Checking out files: 100% (27024/27024), done.

Once the clone is complete, you can use the cd github/docs command to work from within the repository directory and start contributing code to this project.

Well done! You have learned the basics of Git. It's now time to read more about the basics of GitHub.

Basics of GitHub

GitHub is a platform globally known and used among software developers who need to host and collaborate on code.

Git repositories are the center of software development, and they are also the center of GitHub. GitHub repositories have their own features, such as issues, pull requests, project boards, and actions. GitHub Actions workflows live within a repository and, many times, will automate activities that happen within that same repository. Therefore, having a firm grasp of the main features of a repository will allow you to confidently implement creative CI/CD workflows.

A GitHub repository is a cloud-based directory where you can host files and folders. To create a repository on GitHub, you will need a user account. Follow the instructions in the Creating a free user account on GitHub section if you haven't already created your account.

To create a repository on GitHub, navigate to https://github.com and sign in using your username and password. Then, click on Create repository, as illustrated in the following screenshot:

Figure 1.10 – Creating a repository on GitHub

Figure 1.10 – Creating a repository on GitHub

On the next page, choose a repository name and add an optional description for your repository.

Only public repositories will be used throughout this book. Therefore, select the Public option.

Next, check the Add a README file option if you would like to create a README file to your repository.

A README is a file that can be added in order to communicate important information about how to use your repository, how to collaborate, what a project is about, licensing information, and so on. In cases where you have a local repository with a README file that you will later push up to the remote repository, it is best to leave the Add a README file option unchecked. You can also check this option now and edit the README file once the repository is created. In any case, it is considered best practice to add a README file to your project.

Once you are done selecting your preferences, click on Create repository.

In the next section, you will learn more about these tabs in a GitHub repository:

  • Issues
  • Pull requests
  • Settings

The Actions tab will not be covered here, because Chapter 2, Deep Diving into GitHub Actions, will provide in-depth information about GitHub Actions, including the contents of the Actions tab in the repository.

Issues

Issues are created to suggest improvements, report bugs, discuss new ideas, set tasks, or ask questions about the repository and how to contribute to it. It is possible to assign labels, milestones, and assignees to issues, as well as filter issues based on those options.

To create an issue in the a-github-repo repository, navigate to the repository home page at https://github.com/user/a-github-repo/ and click on the Issues tab. Then, click on New issue, as illustrated in the following screenshot:

Figure 1.11 – Creating a new issue

Figure 1.11 – Creating a new issue

On the next page, enter an issue title and a description. The body of the issue accepts Markdown, as the following screenshot shows:

Figure 1.12 – Adding an issue title and description

Figure 1.12 – Adding an issue title and description

The following options can be attributed to an issue:

  • Assignees: Often used to assign the issues to one or more contributors who will work on the bug report or task.
  • Labels: These are usually added to issues and pull requests as a way to categorize them.
  • Projects: Project boards organized in columns that help organize pull requests and issues.
  • Milestone: This helps track progress on group issues and pull requests.
  • Linked pull requests: Issues are commonly created to report bugs. A pull request with a fix can be linked to the issue to show that the fix is being worked on and to automatically close the issue once the pull request is merged.

Add any options you like to the issue and click Submit New Issue.

Very good! You have successfully created an issue. To close an issue, click on the Close issue button at the bottom of the page.

Pull requests

In modern software development cycle practices, pull requests are used to propose changes to files within a repository. On GitHub, a pull request is created when a contributor wants to incorporate their changes into another branch in the same repository or in a parent repository.

To create a pull request, you will first need to add a change to a file that already exists in the repository or propose adding a new file to the repository. For this example, a quick edit will be added to the README file, where the line "This line was added through a pull request > merge process" will be added at the end of the file. Here is what the README file looks like before the edit:

Figure 1.13 – README file before being edited

Figure 1.13 – README file before being edited

To edit the README file, navigate to https://github.com/testesdapri/a-github-repo/edit/main/README.md. Then, add "This line was added through a pull request > merge process" to the end of the file.

Then, enter a commit message, select the option to create a new branch (remember: it is advisable not to commit directly to the main branch of the repository in order to keep the code safe and healthy), and click on Propose changes.

Note how the commit message you created in the previous step is now the title of this pull request. To finish creating the pull request, add a description that will help the code reviewer understand what your changes will introduce.

You can link the pull request to an issue by using the fixes #number automation expression, as shown in the next screenshot. number is the number of the issue that the automation will close once the pull request is merged.

Similar to the options you can add to an issue, you can also add assignees, labels, projects, and milestones to a pull request, as well as adding reviewers and link issues.

Once you have finished creating a description and adding labels, or assigning contributors or reviewers, click on Create pull request. This is what the pull request will look like:

Figure 1.14 – A newly created pull request

Figure 1.14 – A newly created pull request

Note how the issue you mentioned in the body description for the pull request is now linked under Linked issues.

Typically, the next steps of the software development cycle would include a code review, a feedback loop, and code quality tests. This example assumes that those steps have been completed. Next, it's time to merge these changes into the default branch. To do that, click on Merge pull request.

The result will look like this:

Figure 1.15 – A merged pull request

Figure 1.15 – A merged pull request

Now that the pull request has been merged, notice here how the issue linked to the pull request was automatically closed:

Figure 1.16 – A closed issue

Figure 1.16 – A closed issue

The checkboxes on both the Issues and Pull requests pages were checked manually.

Settings

The Settings tab allows the repository owner to configure most features within a repository.

Although many settings are out of the scope of this book, you will learn more about the ones that are most commonly used in best practices of software development. You will also become familiar with settings needed in the implementation of some GitHub Actions workflows.

To see all the available settings, click on the Settings tab.

This subsection will cover the following settings:

  • Manage access
  • Branches
  • Actions
  • Secrets

Branches

This option allows you to perform important tasks, such as defining the default branch for your repository and creating branch protection rules.

As mentioned previously, it is important not to commit directly to the default branch, to keep code safe and healthy. To ensure this is the case, repository owners can create branch protection rules.

To do that, click on Add rule. Then, enter the name of the branch you want to protect. In the following example, the main branch was used:

Figure 1.17 – Adding a branch protection rule

Figure 1.17 – Adding a branch protection rule

Next, check the checkboxes that best apply to your scenario and then click on Create, as illustrated in the following screenshot:

Figure 1.18 – Selecting branch protection rules

Figure 1.18 – Selecting branch protection rules

From now on, before pull requests are merged into the main branch, at least one review will be needed. As the preceding screenshot shows, this branch protection rule does not apply to repository administrators who can merge code to main freely, although doing that is not recommended.

Actions

These settings allow you to adjust options related to GitHub Actions, and you can set Actions permissions. For example, if you only want to allow the use of actions created by GitHub, you would select the Allow select actions option and then check the Allow actions created by GitHub checkbox, as illustrated in the following screenshot:

Figure 1.19 – Actions settings

Figure 1.19 – Actions settings

You can also set artifact and log retention, as well as add a self-hosted GitHub Actions runner, which will be covered in more detail in future chapters.

Secrets

Some GitHub Actions workflows will require the use of environment variables. To keep sensitive information safe, you can add it as secrets. This will encrypt that information before passing them to workflows.

Secrets will be covered in more detail in future chapters.

Well done! In the past couple of sections, you have created an issue, added options such as labels and assignees, and closed the issue. You have also proposed changes to a file by using the GitHub web interface to create a new branch, edit a file, commit changes, create a pull request, and merge the pull request. You have also learned how to manage some repository settings.

Next, you will learn the basics of YAML, another foundational piece to review before diving into GitHub Actions.

 

Introduction to YAML

GitHub Actions workflows must be written using the YAML syntax. For this reason, having a strong understanding of how YAML works is essential to create successful workflow runs.

According to the website YAML.org, "YAML is a human friendly data serialization standard for all programming languages." YAML is commonly used in configuration files, much like the files used to create GitHub Actions and workflows.

Basic rules

The following file, copied from the open source repository found at https://github.com/actions/starter-workflows, shows how a YAML file is used to create a GitHub Actions workflow:

name: Close as a support issue
on:
  issues:
    types: [labeled]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: Close Issue
      uses: peter-evans/close-issue@v1
      if: contains(github.event.issue.labels.*.name, 'support')
      with:
        comment: |
          Sorry, but we'd like to keep issues related to code in this repository. Thank you 
          
          If you have questions about writing workflows or action files, then please [visit the GitHub Community Forum's Actions Board](https://github.community/t5/GitHub-Actions/bd-p/actions)
          If you are having an issue or question about GitHub Actions then please [contact customer support](https://help.github.com/en/articles/about-github-actions#contacting-support)

Key-value pairs and case sensitivity

Most elements in YAML are based on key-value pairs, commonly noted as KVPs. You can observe the KVP syntax in the preceding file and it is shown again here:

name: Close as a support issue

KVPs must be written in following the key: value syntax. Note how there is a space between the colon and the value. Neglecting to include the space will cause failures when your configuration or job runs.

If the key-colon-space-value syntax is respected, KVPs in YAML can be quite flexible.

YAML is also case-sensitive. Therefore, keys such as Another-Boolean and another-boolean are considered valid.

Indentation and the use of tabs

Note the following excerpt from the YAML file shared previously:

on:
  issues:
    types: [labeled]

Indentation in YAML is used to denote structure. In other words, items with the same indentation are considered siblings, while items with indentation are considered a child or a parent. In the preceding example, on is the parent of issues, which is the parent of types.

Important note

YAML does not use tabs. Indentation is created by using spaces. You may want to consider configuring your text editor to show white spaces, which may be helpful while writing YAML files.

Comments

YAML accepts comments. To add a comment, start by adding a hashtag, or pound sign (#). For example, this is what adding a comment to the YAML file pasted previously would look like:

#adds a name to the workflow
name: Close as a support issue
on:
  issues:
    types: [labeled]
#creates the job and build
jobs:
  build:
    runs-on: ubuntu-latest
    steps:

YAML components

While this book will not cover a comprehensive list of YAML components, three of the most used ones are outlined next.

Scalars

Scalars are defined by integers, floats, strings, and Booleans. Given the flexibility that YAML provides, all the following are acceptable:

integer: 10
#different ways to write booleans
boolean: true
another-boolean: yes
yet-another-boolean: off
a key with spaces: a value with spaces
#different ways to write strings
string-with-quotes: "a string with quotes"
string-without-quotes: a string with quotes
new-lines-are-kept-as-new-lines: |
  This is line number 1, and it will show exactly this way
  This is line number 2, and it will show exactly this way
  This is line number 3… you get it
multi-lines-here-that-will-render-as-one-line: >
  When you want a block of text made of many lines
  To show all in one single line
  You can use the special character greater than

Sequences

Sequences are also known as lists of data. Items in a sequence are identified by the dash-space-item syntax. The following workflow file has an example of a block sequence:

    runs-on: ubuntu-latest
    steps:
    - name: Close Issue

Mappings

Mappings allow for the creation of more complex structures, using a combination of sequences and scalars. Note how the following example has scalars (strings) and a sequence (list):

    steps:
    - name: Close Issue
      uses: peter-evans/close-issue@v1
      if: contains(github.event.issue.labels.*.name, 'support')
      with:
        comment: |
          Sorry, but we'd like to keep issues related to code in this repository. Thank you 
          
          If you have questions about writing workflows or action files, then please [visit the GitHub Community Forum's Actions Board](https://github.community/t5/GitHub-Actions/bd-p/actions)
          If you are having an issue or question about GitHub Actions then please [contact customer support](https://help.github.com/en/articles/about-github-actions#contacting-support)

Well done! You have reached the end of Chapter 1. The knowledge you have gathered in this chapter will be fundamental in understanding core concepts of GitHub Actions and successfully putting them into practice.

 

Summary

In this chapter, you read about the history of how software development practices evolved, and why CI/CD became a popular practice. You also learned the basics of Git—the most used version control system in the world—and GitHub, the largest code-hosting platform in the world. Lastly, you learned about YAML and its syntax, which is used to write GitHub Actions workflow files.

In upcoming chapters, you will put your newly learned skills into practice by writing GitHub Actions workflow files using the YAML syntax. You will also use your knowledge of GitHub, CI, and CD to create logical and productive workflows that will allow you to automate many tasks of your software development life cycle.

Chapter 2, Deep Diving into GitHub Actions, will present more specific and advanced concepts and components of GitHub Actions.

About the Author
  • Priscila Heller

    Priscila Heller was born and raised in Brazil, where she obtained a bachelor's degree in Journalism. She moved to the United States in 2011, where she has been living ever since. After working in many different fields, she found a career opportunity in Tech, and went back to school to pursue a degree in Information System Technology. In 2016 Priscila joined GitHub as an Enterprise Support Agent. Over the years she was promoted a few times, and today she is a Senior Manager of Premium Support. Priscila believes in the power of technology, education, and communication. She considers the democratization of knowledge and information to be invaluable for the cultural, social, economic, and scientific development of society and humanity.

    Browse publications by this author
Automating Workflows with GitHub Actions
Unlock this book and the full library FREE for 7 days
Start now