DEV Community

C I R L O R M ⚡
C I R L O R M ⚡

Posted on

How to deploy to an AWS ec2 machine using Github Actions

I recently needed to set up an automatic or continuous deployment to a project I was working on and I needed to use Github actions. Being my first time I went online to read up on it a bit and also watched some Youtube videos, however I couldn't understand everything well so I explained my need to chatGPT, it's answer was enough to get me started but I needed to do some important changes on my own before my CI worked.

Here are my steps.

  1. Create a Github workflow directory in the root of your project ./github/workflow
  2. Add a yml file for you workflow deploy.yml I'm using deploy because the workflow is for deploying my project
  3. Now you need to define your workflow in the deploy.yml file `name: Deploy Website

on:
push:
branches:
- main # Change this to your main branch name if different

jobs:
deploy:
runs-on: ubuntu-latest

steps:
- name: Checkout code
  uses: actions/checkout@v2

- name: SSH into EC2 instance and deploy
  uses: appleboy/ssh-action@master
  with:
    host: ${{ secrets.EC2_HOST }}
    username: ${{ secrets.EC2_USERNAME }}
    key: ${{ secrets.EC2_SSH_KEY }}
    script: |
      cd /path/to/project
      git pull
      sudo pm2 stop app
      sudo yarn build
      sudo pm2 restart app
Enter fullscreen mode Exit fullscreen mode

`

  1. Now the easy part is over, lets get into some ssh madness
  • Set up ssk key
    login to your ec2 instance ssh and run the following commands to generate ssh key pair
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

  • you need to get your secret key to add to your github actions. Open the private key file (~/.ssh/id_rsa) with a text editor and copy its contents. Then, go to your GitHub repository and navigate to Settings > Secrets. Click on "New repository secret" and add a new secret with the name EC2_SSH_KEY and paste the contents of the private key file into the value field.

  1. Finally, Add Secrets to GitHub Repository: In your GitHub repository, go to Settings > Secrets and add the following secrets: EC2_HOST: The IP address or domain name of your EC2 instance. EC2_USERNAME: The username to log in to your EC2 instance.

Top comments (0)