Creating a CI/CD Pipeline With GitHub API and Actions (r)

Sep 28, 2023

GJHtwAWwSTnwTtHNwZYV

-sidebar-toc>

Why you should use CD/CI?

A reason for this is that in a collaborative environment that has several developers involved in the same project, automatic deployments triggered due an individual developer's alteration of the repository can cause instability as well as unexpected problems. In the absence of proper validation and testing the slightest change to the code may disrupt the site's live version, creating downtime along with a bad customer experience.

This is where a CD/CI pipeline is a must. With a meticulously orchestrated CI/CD workflow, developers are able to assure that their code modifications undergo testing and validation before going live on sites. There are numerous tools for the implementation of CI/CD within software development. In this tutorial we'll be using one of them, the GitHub Actions to guide us through this.

What is GitHub actions?

GitHub Actions is a efficient automated tool provided by GitHub. It helps developers automate various tasks processes and workflows within their software development initiatives. It is compatible with GitHub repositories. This makes it a breeze to work with.

With GitHub Actions and with the API it is possible to define specific workflows that will meet the requirements of your project. You can set up the CI pipeline to run tests on your application and triggers deployment on .

Beginning with GitHub Actions

GitHub Actions operates on the idea of workflows. It is a set of automated tasks which are triggered by specific circumstances or scheduled to be run on a regular schedule. The events could include pull requests, code pushes, as also issue creation, and many more. In the event that one of these events happens, GitHub Actions automatically runs the workflow associated with it, then executes a series of predefined steps.

Each stage of the workflow is a specific procedure, for example, developing the code, testing and deployment or perhaps sending out the necessary notifications. Let's build a workflow with three actions:

  1. Check syntax with ESLint
  2. Run tests
  3. Re-install the application

Step 1: Set Up Your GitHub Repository

To get started with GitHub Actions, you need an account on GitHub. GitHub repository.

It is possible to connect to the repository by visiting it on GitHub by selecting: Use this template > Start with a brand fresh repository.

With this React application, unit tests are created for every component to verify its functionality. ESLint can also help ensure the syntax is right and to enforce code formatting. The CI pipeline blocks any release in the event that an pull request, or merge code that is put into a repository does not pass testing of the workflow.

Step 2: Create a Workflow Document

Set up your workflow using a YAML file inside the repository's .github/workflows directory. This directory should be at the root of your repository. The naming convention for workflow files is name-of-the-workflow.yml.

  1. In your repository, create an .github directory.
  2. Within the .github directory, start a brand-new directory called workflows.
  3. Inside the workflows directory, create a new file with a name like build-test-deploy.yml.

Step 3: Write the Workflow for CI/CD.

Now that you have created the workflow file, create an appropriate workflow that contains the necessary steps to verify syntax using ESLint. Test the workflow, and finally launch the application.

Create CI Event

When creating the CI pipeline, the initial step is to give the workflow a name, and decide on the trigger events that initiate the workflow. For this example there are two events that could be pull requests or push to the branch that is in charge.

name, Create test and deploy to the pushbranches "main" request to pullbranches "main"

If you prefer scheduling regular jobs (CRON jobs) to perform specific tasks you can add them to your workflow. For instance, you may need to set up specific tasks like backups of databases, data cleaning, or any other routine maintenance tasks.

Here's an illustration of how to incorporate a CRON task into the workflow.

on: # Existing triggers that trigger events like pull or push request. Set a schedule of CRON jobs that use"0 0. * "0 zero. * *"

This scenario will start the daily process at midnight (UTC time) as the cron scheduling schedule is configured as this 1: 0.. The cron schedule is modified to suit your particular requirements. The schedule can be adjusted to your specific needs.

A second scenario consider that you wish to establish the C/C workflow for each Monday's morning at around 8 a.m. It is possible to create a CRON task with an event in the timetable that follows:

name Create, Test and deployon the following branches: pushbranches "main" pull_request:branches "main" branches "main"The workflow should be scheduled to start every Monday morning starting at 8:30 a.m. (UTC time) schedule:"cron: "0 8 * * 1" jobs:# Create jobs

The schedule syntax that is utilized to generate the scheduling event in the GitHub Actions workflows is based on the UNIX cron syntax. This syntax allows you to define specific intervals and times to allow your workflow to operate automatically. The syntax consists of five fields, which are various aspects of the scheduling. Each field is separated by the space. The syntax for scheduling syntax is:

* * * + + +| |  --  Day in the week (0 7) (Sunday through Saturday in which both 7 and 0 represent the Sunday) | +--- month (1 12) +----- Day (1 1 - 31) | +------- Hour (0 23) Minute (0 between 59 and)

Then, let's take a glance at every field:

  • Minute (0 to the 59th minute): The minute that the cron task will be initiated. In this case, 15 means that the workflow will be active in the 15th minute of in the hour.
  • Hour (0 23): The hour at which the cron job begins to begin to run. In this instance, 8 means the workflow begins around 8 a.m.
  • A day in the month (1 1 to 31): The day of the month when the cron task will be active. As an example, 1 means that the workflow will be initiated at the start of the month.
  • Month (1 - 12-): The month in which the cron task will trigger. For example, 6 means that the workflow is scheduled to begin in June.
  • The day of the week (0 7): The day which falls on a weekday during the time when the cron task will begin to trigger. It's because Zero and 7 are each Sunday. 1 signifies Monday, and the list goes on. As an example, 4 means that the process will begin at the time of Thursday.

Special characters:

  • * (asterisk): matches any value in that field. In this case, * in the field for minute indicates that the workflow is active each minute.
  • */n (slash): It defines an interval. In this case, */5 in the minute field indicates that the workflow will trigger every five minutes.
  • , (comma): Specifies multiple particular values. For instance, 1,15,30 in the field for minutes means that the workflow starts at the 1st, 15th, and 30th minutes of the hour.
  • (hyphen) (hyphen) - (hyphen): The the hyphen signifies a certain number of values. In this particular case, 1-5 in the day of the week field means that the workflow starts between Monday through Friday (1 up to 5).
  • ? (question mark) It is used to define the absence of a specific value. This is typically used in the field for the day of the week in which the month's day is stated. In this case, ? in the field for the day of the week as well as 15 within the monthly day field, means the field will become active on the fifteenth day the month, regardless of the day of the week.

Create an CI Job to Verify Syntax Using ESLint

To begin the CI process, we will create the necessary assignments or jobs. Each task should be given the clearest and most understandable title. Let's say the job is the eslint job as it involves reviewing the syntax of code using ESLint.

jobs: eslint name to check Syntax by using ESLint runs-on: ubuntu's latest strategy: matrix Node-version [18.x, 20.x]

In the next step, determine what procedures that the "ESLint" task is to run. This involves checking your code to ensure that you have the correct Node.js version to execute ESLint as well as caching NPM packages, setting up project dependencies, and finally employing ESLint to verify how your code is structured.

 steps: - name: Checkout code uses: actions/checkout@v3 - name: Use Node.js $ matrix.node-version to Check Lint uses: actions/setup-node@v3 with: node-version: $ matrix.node-version cache: 'npm' - name: Install Dependencies run: npm ci - name: Run ESLint run: npm run lint

The workflow described above has each step is given the description and a number to make it easy to identify the source of the problem or bug when looking at the workflow using GitHub Actions. In particular, during the third step, we use the the npm the ci command for installing dependencies. This method is preferred over npm install because it allows for an easy installation. Additionally, the third step, performing ESLint with the npm run lint command requires that you have installed this command into the package.json file.

Below is the entire job of checking syntax using ESLint.

jobs: eslint: name: Check Syntax with ESLint runs-on: ubuntu-latest strategy: matrix: node-version: [18.x, 20.x] steps: - name: Checkout code uses: actions/checkout@v3 - name: Use Node.js $ matrix.node-version to Check Lint uses: actions/setup-node@v3 with: node-version: $ matrix.node-version cache: 'npm' - name: Install Dependencies run: npm ci - name: Run ESLint run: npm run lint

Create CI Job that runs Tests

For adding the CI job that runs tests, begin by dedefining the task, then assigning it a descriptive title, such as test. Also, we'll specify the fact that this job is contingent on testing the tests ESLINT job. This implies that the test job is run prior to the time that the tests task is completed. This ensures that the code is inspected for any syntax errors before running the tests.

test: Name"Run Tests"needs to be eslint runs on: Ubuntu-latest

Next, we need to establish the specific steps to follow in this tests test. As with the first job you'll go through the source code and configure Node.js Version 18.x to run the tests. Install the dependencies of the project using the npm ci command. Next, run tests by using the "run test" command.

 steps: - name: Checkout code uses: actions/checkout@v3 - name: Use Node.js 18.x to run Test uses: actions/setup-node@v3 with: node-version: 18.x cache: 'npm' - name: Install Dependencies run: npm ci - name: Run Tests run: npm run test

Create CI Jobs To deploy Using API

 deploy: name: Re-Deploy Application needs: [eslint, tests] runs-on: ubuntu-latest

The API: Learning API

Create an API key: API key:

  1. Login to your My Dashboard.
  2. Navigate to your API Keys page ( Your name > Settings for your company > API Keys).
  3. Click to Create API Key.
  4. Choose an expiration or set a custom start date and the number of hours that the key to expire.
  5. The key should have a distinctive name.
  6. Click to generate.
Create API Key on My
Create your API Key by logging into My.

How do I best to trigger deployment using API

For an application to be deployed through the API there are two parameters that are required including the ID of the application and the branch. You can find the ID of your application using a search engine to find the list of your apps that will give you information regarding every application and its ID.

curl -i -X POST \ https://api..com/v2/applications/deployments \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d ' "app_id": "", "branch": "main" '

Trigger Deployment with cURL the CI/CD Pipeline

To trigger deployment by using the API API For deployment to trigger using the API Simply incorporate the command in the running command within the CI pipeline. However, it's important to store your API key as well as the application's ID secure.

  1. Browse to the repository that you'd like to post the information.
  2. Visit the Settings tab in the menu for the repository.
  3. The left-hand sidebar is where you can go to Secrets under the Option category.
  4. Click here to access The new repository secret.
  5. Choose a distinctive name for your secret (like _API_KEY) and enter your API key in the value field.
  6. After you've entered the name and the value, you can click the"Add secret. "Add secret" option to store it.
  7. Repeat the process to learn additional ways.
Storing secrets on GitHub
You can keep secrets safe on GitHub.

Once you have added the secrets, you can reference them in your GitHub Actions workflow by using the $secrets.SECRET_NAME |syntax.|secrets.SECRET_NAME} syntax.

We're now ready to finish the deploy job for the Actions on GitHub CI/CD pipeline. Create the steps as previously, but with only one method to deploy it to . First, specify the secret in the command env command. After that, add the cURL command in order to execute the deployment.

 steps: - name: Deploy to env: _API_KEY: $ secrets._API_KEY APP_ID: $ secrets.APP_ID run: | curl -i -X POST \ https://api..com/v2/applications/deployments \ -H "Authorization: Bearer $_API_KEY" \ -H "Content-Type: application/json" \ -d ' "app_id": "'"$APP_ID"'", "branch": "main" '

When you run the command cURL, you'll see that variables for the environment are added to the command. This enables confidential information to be protected accessible during the process of deployment.

This is what your final workflow for CI/CD should be like:

name: Build, Test, and Deploy on: push: branches: "main" pull_request: branches: "main" jobs: eslint: name: Check Syntax with ESLint runs-on: ubuntu-latest strategy: matrix: node-version: [18.x, 20.x] steps: - name: Checkout code uses: actions/checkout@v3 - name: Use Node.js $ matrix.node-version to Check Lint uses: actions/setup-node@v3 with: node-version: $ matrix.node-version cache: 'npm' - name: Install Dependencies run: npm ci - name: Run ESLint run: npm run lint tests: name: Run Tests needs: eslint runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Use Node.js 18.x to run Test uses: actions/setup-node@v3 with: node-version: 18.x cache: 'npm' - name: Install Dependencies run: npm ci - name: Run Tests run: npm run test deploy: name: Re-Deploy Application needs: [eslint, tests] runs-on: ubuntu-latest steps: - name: Deploy to env: _API_KEY: $ secrets._API_KEY APP_ID: $ secrets.APP_ID run: | curl -i -X POST \ https://api..com/v2/applications/deployments \ -H "Authorization: Bearer $_API_KEY" \ -H "Content-Type: application/json" \ -d ' "app_id": "'"$APP_ID"'", "branch": "main" '

Copy the given workflow and paste it into your build-test-deploy.yml file. Following that, make an open pull-request to add this file to the first section of your repository. Be sure to mention that this pull request will automatically start the process.

It lets you review any changes made to your repository. You can ensure that any new change in the pull request passes the requirements prior to deciding whether or not you want to incorporate the change into your codebase.

Storing secrets on GitHub
Store secrets in GitHub.

When you merge the pull request. It is possible to access the actions tab of your GitHub repository. You'll be able to see the CI/CD workflow moving.

GitHub Actions summary
GitHub Summary of Actions.

Click each job for more information on the work (this is why that you must describe every phase of your work in a concise description of the job).

CI steps details
CI steps details.

Insuring Pull Request Workflows are enforced on GitHub

For effective control of code and collaboration in GitHub repositories it's important to implement a pull request process and prevent direct commits to branches that do not belong to the main branch. This process creates a well-controlled and regulated development process which demands that all changes be reviewed and pulled requests prior to merging with the branch that is primary.

If they adhere to this approach developers can increase the performance of their code and reduce the chance of creating bugs and keep unrecorded records of adjustments made.

This is the way to configure a workflow for pull requests to enforce:

  1. Go to on the settings tab within your repository in GitHub.
  2. Under Automated and Code Select The Branches menu is located on the menu in the sidebar choices.
  3. If there's not a rule in place, then click on the Add Branch Protection Rule.
  4. Give a name to the rule. After that, you can opt to check the need for an pull request prior to merging. After that, you'll see additional options to set up.
  5. Additionally, make sure to mark the box which says "Checks on status" that require to pass before merging.
  6. Customize additional options based on your requirements and preferences.
  7. Hit on the button to activate the button in order to save the rule.
Enforcing pull request workflow on GitHub
Workflows to pull requests need to be enforced on GitHub.

If you follow these steps, you have established a policy to govern the procedure of pulling pull requests from the GitHub repository. The rule ensures that each change will be reviewed as well as automated verification before it is integrated into the main branch. This results in a more efficient and productive environment for development.

Summary

By combining the power through the combination of GitHub Actions together with the API to streamline your development workflow and foster a collaborative and efficient environment for your team of developers.

Developers can be confident in the submission of their code knowing they will be thoroughly tested prior to releasing it for production. In addition, everyone that are affected can relax at ease knowing that the process of deployment is safe and properly controlled.

     How do you use the API? Which API endpoints do you wish included in the API? What API-related tutorial do you would like to see in near future?

Joel Olawanle

Joel is a Frontend developer working at as Technical Editor. He is an ardent educator who is passionate about open source and has published more than 200 technical articles mostly on JavaScript as well as the frameworks it uses.

Article was posted on here