Mastering Secure Automation: A Guide to GitHub Actions with SSH Agent and SSH Keys

Published on October 16, 2023

Zignuts Technolab

Mastering Secure Automation: A Guide to GitHub Actions with SSH Agent and SSH Keys
Software Development

Objective

In the dynamic realm of software development, we often find ourselves navigating the complexities of Continuous Integration and Continuous Deployment (CI/CD) pipelines. As developers, we encounter scenarios where automation is not just a convenience but a necessity, especially when orchestrating tasks on the target server where our projects unfold. This is particularly true in the dichotomy of sandbox and production environments, where precision and efficiency are paramount.

Exploring Crucial Use Cases:

  1. Auto Deployment of Latest Code

Learn how to seamlessly deploy the latest code onto your server directly from the repository, ensuring your applications are always up-to-date.

  1. Containerized Deployment with Docker Images

Delve into the integration of GitHub Actions with SSH Agent and SSH Keys to automate the process of pulling Docker images from the repository and running containers effortlessly.

  1. Automated Code Scanning

Uncover strategies to incorporate automatic code scanning into your CI/CD pipeline, providing an additional layer of security and code quality assurance.

  1. Run Automated Test Cases

Discover the power of running automated test cases automatically after pulling the latest code, ensuring the stability and reliability of your applications.

  1. Custom Bash Scripts for CI/CD

Explore the versatility of GitHub Actions by running custom bash scripts tailored to your specific needs. Whether it's orchestrating complex deployment sequences or executing specialized actions, GitHub Actions has you covered.

In this comprehensive guide, we will unravel the intricacies of GitHub Actions, SSH Agent, and SSH Keys, empowering you to streamline your CI/CD processes efficiently. Let's embark on a journey to master secure automation and elevate your development workflows.

Let’s Get Started

Before we dive into the intricacies of GitHub Actions, SSH Agent, and SSH Keys, let's ensure our environment is ready. For the purpose of this guide, we're assuming you're working with an Ubuntu 22.04 server. However, fear not if your server runs on a different operating system; the principles and commands remain largely transferrable. 

Security is paramount, and one way to bolster it is by using key pairs for authentication. We're assuming that your server is configured to allow access only through SSH key pairs, not passwords. This provides an additional layer of protection, enhancing the overall security posture of your CI/CD setup.

Step 1: Create a separate OS user

1.1 Generate an RSA Key Pair Locally

Begin by creating an RSA key pair on your local machine. This pair will be instrumental in configuring a dedicated OS user on your server.

When prompted for a passphrase, leave it blank for the purpose of this task. The command above generates two files: github-actions (private key) and github-actions.pub (public key).

1.2 Create the OS User on the Server

Now, let's log in to your server and set up the OS user. In this guide, we'll name our user github-actions.

Follow the prompts to provide any additional information you wish to associate with the new user. This step ensures that you have a dedicated user for GitHub Actions, enhancing the security and manageability of your CI/CD workflows.

By isolating processes and permissions to a specific user, you not only bolster security but also streamline the management of tasks related to GitHub Actions. This separation facilitates a more organized and controlled CI/CD environment.

Create the OS User on the Server

1.3 Configure the User with the Generated Key Pair

Now that we have created the OS user, let's configure it to use the key pair generated in the previous steps.

By following these steps, you've successfully configured the GitHub Actions user to use the generated key pair. This establishes a secure and authenticated connection, enabling GitHub Actions to interact with the server seamlessly.

1.4 Optional - Granting sudo Access

In certain scenarios, you might require the GitHub Actions user to have sudo privileges. This step is optional and should be handled with caution to maintain security.

This command appends a line to the sudoers file, granting sudo access to the GitHub Actions user without requiring a password.

Note: While providing sudo access can be convenient for certain tasks, exercise caution and limit permissions to only what is absolutely necessary for your CI/CD workflows. Alternatively, ensure that the scripts and commands you intend to run are accessible and executable by the GitHub Actions user without the need for elevated privileges.

By following this optional step, you accommodate scenarios where your CI/CD processes necessitate administrative permissions. However, always prioritize security and adhere to the principle of least privilege when assigning permissions.

1.5 Optional - Adding User to the Docker User Group

If your CI/CD workflows involve Docker operations and you want the GitHub Actions user to perform these tasks, you can add the user to the Docker user group. This step ensures that the user has the necessary permissions to interact with Docker.

This command adds the GitHub Actions user to the Docker group. After executing this command, it's important to log out and log back in for the changes to take effect. You can also use the following command to apply the changes without logging out:

By following this optional step, you empower the GitHub Actions user to seamlessly execute Docker commands. This can be essential if your CI/CD pipeline involves containerization, allowing your workflows to leverage the power of Docker for tasks such as building and deploying applications in containers.

Step 2: Configure Secrets in GitHub Actions 

Secrets play a crucial role in securely managing sensitive information within GitHub Actions. Secrets are variables that you create in an organization, repository, or repository environment. The secrets that you create are available to use in GitHub Actions workflows. GitHub Actions can only read a secret if you explicitly include the secret in a workflow. Follow these steps to configure the necessary secrets for our CI/CD objective.

2.1 Open Organization Settings and Navigate to Secrets

  • Go to your GitHub account and access your Organization Settings (not the profile settings).
  • Navigate to Secrets and Variables > Actions.
Configure Secrets in GitHub Actions 

2.2 Create 3 Repository Secrets

Click on New Repository Secret and define the following three secrets:

  1. SERVER_IP:

Enter the IP address or hostname of your server.

  1. SERVER_KEY:

Enter the private key for the github-actions user that we generated in Step 1.1.

  1. SERVER_USER:

Enter github-actions as the value.

By adding these secrets, you create a secure mechanism for GitHub Actions workflows to access sensitive information without exposing it directly in your workflow files.

Note: It's crucial to securely manage and protect your secrets. Avoid hardcoding sensitive information directly into workflow files, as it poses security risks. Instead, leverage GitHub Secrets to store and retrieve this information securely.

These secrets will be instrumental in the subsequent steps as we integrate GitHub Actions with SSH Agent and SSH Keys to automate CI/CD pipelines on your server.

Create  Repository Secrets

Step 3: Create Your Deployment or Automation Script on the Server

In this step, we'll create a bash script on the server to execute deployment or automation tasks as part of your CI/CD process.

3.1 Create the Bash Script

Run the following commands to create and edit the deployment script:

3.2 Add Script Content

Inside the nano editor, add the following content to your deploy.sh script. This example script prints "Hello World!" for demonstration purposes. You can replace this content with your actual deployment or automation commands.

#!/bin/bash

echo "Hello World!"

3.3 Save and Exit

To save and exit the nano editor, press Ctrl + X, then press Y to confirm changes, and finally, press Enter.

Your deployment script is now ready. This script will serve as the basis for the automation tasks you want to execute as part of your CI/CD pipeline.

Make sure to adapt the script to fit your specific deployment requirements. If your actual deployment involves pulling code from a repository or building Docker images, modify the script accordingly.

In the next sections, we'll integrate this script with GitHub Actions to automate its execution when triggered by specific events.

Step 4: Create a Workflow File

In this step, we'll create a workflow file that instructs GitHub to execute the defined workflow whenever changes are pushed to the specified branch. This workflow will automate the deployment process using the script we created earlier.

4.1 Open your Project and Create Workflow File

Open your project code from any editor of your choice and create a file: .github/workflows/ci-cd.yml

4.2 Add Workflow Content

Paste the following content into your ci-cd.yml file:

name: example-ci-cd

on:

  push:

    branches:

      - sandbox

  workflow_dispatch:

jobs:

  deploy-sandbox:

    if: github.ref == 'refs/heads/sandbox'

    name: Deploy to New Sandbox

    runs-on: ubuntu-latest

    steps:

      - name: Install SSH

        uses: shimataro/ssh-key-action@v2

        with:

          key: ${{ secrets.SERVER_KEY }}

          known_hosts: unnecessary

      - name: Key setup

        run: |

          ssh-keyscan -H ${{ secrets.SERVER_IP }} >> ~/.ssh/known_hosts

      - name: SSH script

        run: |

          ssh ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_IP }} 'sh /apps/scripts/deploy.sh'

4.3 Save and Commit

Save the file and commit it to the repository, specifically in the sandbox branch. Pushing the changes to this branch will trigger the GitHub Actions workflow.

4.4 Monitor the Workflow

As soon as you push the code, navigate to the GitHub Actions console to monitor the workflow's progress. You should see the workflow being triggered and the deployment process automated by GitHub Actions.

Congratulations! You have successfully set up a CI/CD pipeline using GitHub Actions with SSH Agent. This workflow will execute the deployment script whenever changes are pushed to the specified branch, facilitating an automated and efficient development pipeline.

linkedin-blog-share-iconfacebook-blog-share-icontwitter-blog-icon

Portfolio

Recent

SaaS-Based Digital Solution

SaaS-Based Digital Solution

Dynamic Digital Furniture Assembly Manuals

eCommerce & Retail

Backend & APIs

Web Application

UX/UI Design

Say goodbye to confusing and messy furniture assembly! Zignuts helped a client build a solution that dynamically brings furniture assembly manuals to life digitally....

View Details

Shopping with Entertainment

Shopping with Entertainment

Social Media Cum eCommerce Platform

Social & Networking

Mobile Apps

Web Application

UX/UI Design

A creative & futuristic platform that combines the joy of shopping with the fun of watching reels and browsing social media in a single mobile application. Users can browse through reels…

View Details

Co-Tasker App

Co-Tasker App

On-Demand App for Local Services

On-demand Services

Mobile Apps

Backend & APIs

UX/UI Design

Co-Tasker is an on-demand services and task marketplace application that helps connect people who require additional expertise & outsource their tasks with local experts and service providers.

View Details

Pocomos

Pocomos

Custom Pest-Control CRM

CRM Solution

Custom Software Development

Mobile Apps

Web Application

A comprehensive CRM platform for pest control service providers to manage their entire lead management, service operations, and billing. The platform consists of a white label component allowing admins to monetize the platform.

View Details

Good For The Swole

Good For The Swole

Fitness Platform for Pregnant Women

Fitness & Wellness

Mobile Apps

Web Application

Backend & APIs

The perfect fitness platform that guides women with the right exercise & fitness regime to follow during the different phases of pregnancy. The app prepares women for pregnancy and includes follow-along workout videos to help women stay fit & healthy during and after pregnancy.

View Details

New2

New2

Information & Networking Platform

Social & Networking

Mobile Apps

Web Application

UX/UI Design

A one-stop platform that assists expats, students, and migrants adapt to a new place by helping them with local information that can be of use in their day-to-day lives. It also helps people connect with the latest & happening events.

View Details

Hire Ad-Hoc Staff Online

Hire Ad-Hoc Staff Online

SaaS Modern Medical Staffing Solution

Healthcare

Web Application

Backend & APIs

Custom Software Development

Ensuring that a clinic’s or hospital’s staff is at its optimum efficiency based on the number of appointments is a very challenging task. With our client, we created a platform that…

View Details

Buy & Sell Properties

Buy & Sell Properties

Real Estate Listing Application

Real Estate & Property

Web Application

Mobile Apps

Microservices

A new age real estate platform that is built to serve the needs of all parties including customers, brokers and real-estate developers alike. The platform aims to help…

View Details

Plan Travel With Experts

Plan Travel With Experts

Cloud-Based Travel Itinerary Planner

Travel & Hotels

Web Application

Mobile Apps

UX/UI Design

Traveling to a new place and want to make the best of your travel experience? We helped our client in building a solution that helps you plan the perfect itinerary for your trip based on…

View Details

Measure Noise Pollution

Measure Noise Pollution

Noise Levels Mapping App

Healthcare

Mobile Application

UX/UI Design

IoT Development

This ingenious mobile application helps users measure the noise level in their surroundings and also allows users to view the noise pollution levels in different areas…

View Details

SaaS Loan Officer Platform

SaaS Loan Officer Platform

Online Loan Quotation Generator

Finance & Banking

Web Application

UX/UI Design

Microservices

This platform helps improve the efficiency of a loan officer's business through tracking and reporting, and increases the chances of conversion through custom quotations and…

View Details

Green Jello

Green Jello

Advanced Gaming Application

Sports & Entertainment

Mobile Apps

UX/UI Design

QA/Testing

Enjoy your time with family and friends with a fun and amusing game app. The app blends the delight of tech and in-person games through a mobile-based charades game.

View Details

Smarpees

Smarpees

Innovative e-Commerce Platform

eCommerce & Retail

Web Application

Mobile Apps

QA/Testing

An innovative eCommerce platform that directly connects buyers with sellers for a more personalized & enhanced buying experience. Buyers can directly chat with sellers to solve their questions & queries.

View Details

Silvatree

Silvatree

Innovative Digital Trading Platform

Finance & Banking

Web Application

Mobile Apps

UX/UI Design

A creative digital trading platform that allows local businesses to trade their products & services with each other in exchange for digital tokens. The tokens can be transferred through the platform and redeemed for other products or services.

View Details

Fitness & Wellness App

Fitness & Wellness App

Online Fitness & Wellness App

Fitness & Wellness

Web Application

Backend & APIs

UX/UI Design

A platform that allows fitness enthusiasts to find the best gyms and fitness classes nearby. The admin software allows business owners to manage their businesses by tracking members, memberships, payments & more.

View Details

Virtual Queuing App

Virtual Queuing App

Smart Queuing for the Modern World

Bookings & Appointments

Web Application

Mobile Apps

Microservices

With the coming of social distancing and even busier work schedules, no one has the time to stand in long queues. The smart-queuing app solves this challenge by allowing virtual & and reducing wait time.

View Details

Booking App

Booking App

Grooming Services Booking

Fitness & Wellness

Mobile Apps

Backend & APIs

UX/UI Design

We have created a modern on-demand beauty application that brings all types of beauty and grooming services to your fingertips. The app allows users to book and manage appointments with local beauticians with ease.

View Details

Needs App

Needs App

Doorstep Delivery of Daily Essentials

On-demand Services

Mobile Apps

Backend & APIs

UX/UI Design

The Needs App is the single-stop solution for the delivery of all essential items and services. You can now have medicines, dairy, groceries, laundry, & other provisional items delivered to your doorstep.

View Details

Smoove

Smoove

List & Search Local Properties

Real Estate & Property

Mobile Apps

Backend & APIs

UX/UI Design

It is the ultimate solution for all renting and sharing needs. The platform allows renters to find listed properties near them and connect with other people to find a suitable flatmate.

View Details

Hamilton

Hamilton

Certified-Trainers Fitness Platform

Fitness & Wellness

Web Application

Backend & APIs

QA/Testing

It is a  fitness platform that allows certified trainers to provide their service through online training for fitness enthusiasts. The platform helps fitness accessible to all, 24x7, from any place.

View Details

QK Sports

QK Sports

Adventure Management & Booking

Sports & Entertainment

Web Application

Mobile Apps

UX/UI Design

Zignuts has created a one-stop centralized system for adventure and tourism. The app uses the latest technologies & automation to digitalize booking and managing adventure activities for both users and admins.

View Details

Hobi

Hobi

Online Skill Sharing Platform

Fitness & Wellness

Mobile Apps

Backend & APIs

QA/Testing

An innovative skillshare networking people allows people to discover, share and learn new skills and hobbies and connect with like-minded people who share the same interests.

View Details

Matcho Web

Matcho Web

Recruitment & Referral Platform

CRM Solution

Web Application

Backend & APIs

Cloud Computing

Taking a unique approach to job search and recruitment, the app helps both job seekers and recruiters find the right match. It also allows candidates to match others seekers with a job opening.

View Details

Social Parenting & Networking Application

Social Parenting & Networking Application

Find Parents & Schedule Playdates

Social & Networking

Web Application

Backend & APIs

UX/UI Design

The app helps parents with young children to find fellow parents nearby and allows them to network with each other and set up playdates. It is a solution that aims to make life easier for parents, especially new ones.

View Details

Home Financing Application

Home Financing Application

Easily Manage Home Loans

Finance & Banking

Web Application

Backend & APIs

QA/Testing

The app provides a secure platform for customers in Australia to negotiate their existing home loans with their banks hassle-free, anytime, and anywhere.

View Details

Social Dating App

Social Dating App

Redesigned Dating Experience

Social & Networking

Mobile Apps

Backend & APIs

UX/UI Design

A Dating app that helps users find like-minded people near them. The app goes beyond just dating and seeks to bring together new and interesting people together.

View Details

Serenity

Serenity

Wellness Through Music

Fitness & Wellness

Mobile Apps

Backend & APIs

UX/UI Design

An innovative wellness and mental fitness application that uses music and interactive features to keep a check on the user's mental well-being. The app monitors heart rate, BMI, water consumption, etc. to calculate health.

View Details

Umami Recipe

Umami  Recipe

Recipe Sharing & Reviewing

eCommerce & Retail

Web Application

Backend & APIs

UX/UI Design

A unique web application that allows users to search, view, rate, save and share recipes online. Users can provide their valuable feedback on recipes and even share them with friends and family.

View Details

Planet.info

Planet.info

Fleet Management & Accounting

CRM Solution

Web Application

Backend & APIs

QA/Testing

The platform includes a custom CRM solution that helps the client manage and track their fleet of sensors used to map air quality. It also consists of a user reward program every time a sensor sends valid data.

View Details

Dentware

Dentware

Dentist Booking & Management App

Healthcare

Web Application

Backend & APIs

UX/UI Design

We have developed a SaaS product designed to help dentists manage all areas of their practice with ease and efficiency. The app allows the management of patient booking, records, services, & other information.

View Details

Controlcast

Controlcast

Easy Local TV Advertising

Marketing & Ads

Web Application

Backend & APIs

UX/UI Design

A complete digital out-of-home marketplace app that makes advertising on local TV screens simple in just a few clicks. Advertisers can instantly push their advertisements on digital screens through a simple dashboard, thus increasing marketing efficiency.

View Details

Es Student Mobile Application

Es Student Mobile Application

IELTS Test Preparation App

Education & eLearning

Web Application

Backend & APIs

UX/UI Design

A language training app that lets users hone their English language skills to prepare themselves for the popular IELTS English proficiency test. The solution also includes a job board for applying for jobs.

View Details

Video-Sharing App with Social Editing

Video-Sharing App with Social Editing

Entertaining Short Video Sharing

Social & Networking

Mobile Apps

Backend & APIs

UX/UI Design

Create the next trend through a hip video-sharing app. Entertain millions by sharing short videos. The app also has built-in editing features powered by social editing, ML, and AI video editing to help create sensational short videos.

View Details

Ajo Application

Ajo Application

Garmin Integrated Fitness App

Fitness & Wellness

Mobile Apps

Backend & APIs

IoT & Wearable

A robust fitness application that allows users to keep track of their health and fitness status by measuring caloric intake, physical activity, and more. Users can earn reward points redeemable at local stores.

View Details

B2B On-Demand Services

B2B On-Demand Services

B2B Services Booking Platform

On-demand Services

Web Application

Mobile App

UX/UI Design

This platform aims to provide small to large businesses easy access to handyman and other on-demand services for specific requirements right at their fingertips…

View Details

Reduce Operational Risks

Reduce Operational Risks

SaaS Risk Management Platform

Custom Software Development

QA/Testing

CRM Solution

Web Application

Conduct your business worry-free by doing away with unforeseen operational risks. We helped our client build a single-stop solution that ensures that vendors are compliant with…

View Details
explore-projects