Automatic deploy to AWS with Github Actions

Overview

Word can't express the joy and confidence I feel within me to have automated my AWS deployment such that I just have to merge to develop branch and the GitHub action will do the rest as instructed by my deployment script.

How I Accomplished the whole Automation

  1. Created deploy_to_aws.sh on the root of the application and included the code below

code below

#!/bin/bash
 
echo 'Starting to Deploy...'
ssh ubuntu@52.38.40.75 " sudo docker image prune -f 
        cd tictactoe_rails_react 
        sudo docker-compose down
        git fetch origin
        git reset --hard origin/develop  &&  echo 'You are doing well'
        sudo docker-compose build && sudo docker-compose up -d
        "
echo 'Deployment completed successfully'

The command execute the below

  • login to your EC2 server

  • remove all the unused images

  • cd into the application directory

  • shutdown the running containers

  • update the repository from github

  • reset the current git repository to the updated version

  • build your docker image

  • and start the image

2. Created .github/workflows/aws.yml on the application and includec the commands below in the yml file

name: Deploy EC2
on:
  push:
    branches:
      - develop
  pull_request:
    types: [closed]
jobs:
  merge-PR:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Install SSH key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_KEY }}
          name: id_rsa
          known_hosts: ${{ secrets.KNOWN_HOSTS }}
      - name: rsync over ssh
        run: ./deploy_to_aws.sh

3. I went straight to my repository on github, clicked on Settings, traced the secrets and added the SSH_KEY and KNOWN_HOSTS which I got from my EC2 by running

ssh-keygen -t rsa 

ssh-copy-id ubuntu@52.38.40.75

At this point, I just had to raise and merge a pull request to develop branch and the the deployment process will be triggered by github actions.

Reference

workflow-syntax-for-github-actions

triggering-workflow-on-merge

install-ssh-key

Previous
Previous

Testing Pyramid

Next
Next

First Client Demo