CI/CD from GitHub to AWS EC2 using GitHub action

I have heard about CI/CD for a long time but never tried by myself . But i didn’t knew how much fun is this . Just some line of code can automate the whole test and deployment things. Lets see how i achieved this .

I am not going to describe what is CI/CD and GitHub action in book language. There are lot of resources for that .

According to me CI is checking the application is working or not and CD is deliver the application . Obviously both is in automatic way . But it can do a lots of things. This is just a scratch . GitHub action is a tool which will help us to achieve CI/CD easily and this is also free for certain time limit .

TL;DR

  1. Get public ssh key of EC2 instance
  2. Put the public ssh key in Git repository’s deploy keys
  3. Get the private key , host name and user name of AWS EC2 instance
  4. Create the .yml file in GitHub to build and deploy the application.

We will use this GitHub repository . But to use this repository we need to install docker and docker-compose in our EC2 instance . Docker can be installed from here and docker-compose from here .

Lets start the description . First we need to get the ssh key .

If we do not provide any file name this will create two file named id_rsa and id_rsa.pub in .ssh folder. We will copy the key inside of id_rsa.pub and put it in GitHub deploy key . We will find deploy key in settings of our repository .

add deploy key in github.
add deploy key in github.

Give a tick in “Allow write access ”. We need this so that we do not need to give GitHub username and password every time we pull from EC2 instance . Now clone the repository using SSH .

To connect GitHub action and EC2 instance we need three things .

  1. AWS private key.
  2. EC2 instance’s username
  3. EC2 instance’s Hostname

There are several way to get AWS private key . But we will use the key.pem file of EC2 instance .

For my case ubuntu will be user name and hostname will be EC2’s Public IPv4 address .

ec2 username and hostname
ec2 username and hostname

we will keep all of this in our repository’s secret key .

GitHub secret key
GitHub secret key

Now we will write the CI_CD.yml file which will execute the whole process . This CI_CD..yml file will be written in repository’s .github/workflows folder .

This code is pretty simple . We want to perform CI/CD operation if there is any push in master branch or if a branch is merged in master branch . After deploying the app we can see the app in ec2’s_public_ip:8899 address .

It is a great app . Is not it 😃?.

That’s all for today . Any suggestions are greatly welcomed . Thank you .

Currently working as a software engineer in japan . Passionate about mobile application development .

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store