Configure SSH into AWS EC2
1. Generate SSH Key
cd ~/.ssh
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Enter file name: "key_name"
ls
and list out files of .ssh folder, you should be seeing "key_name" and "key_name.pub"
- Add public key to authroized keys
cat github-actions.pub >> ~/.ssh/authorized_keys
For detailed information on SSH Key generation process check this reference: https://zellwk.com/blog/github-actions-deploy/
2. Set Github Secrets
SSH_PRIVATE_KEY: private key that we created on ec2
HOST_NAME / IP_ADDRESS: Elastic IP or IP of EC2
USER_NAME: user name of the ec2 user.
3. Create a branch_name.yml ( for dev
branch dev.yml
) file under .github/workflows
Update the dev to your branch name
name: Deploy
on:
push:
branches: [ dev ]
jobs:
Deploy:
name: Deploy to EC2
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build & Deploy
env:
PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
HOSTNAME: ${{secrets.SSH_HOST}}
USER_NAME: ${{secrets.USER_NAME}}
run: |
echo "$PRIVATE_KEY" > private_key && chmod 600 private_key
ssh -o StrictHostKeyChecking=no -i private_key ${USER_NAME}@${HOSTNAME} '
# Now we have got the access of EC2 and we will start the deploy .
cd /home/ubuntu/<PROJECT_DIRECTORY> &&
git checkout dev &&
git fetch --all &&
git reset --hard origin/dev &&
git pull origin dev &&
sudo npm i &&
sudo npm run build &&
sudo pm2 stop ./dist/index.js &&
sudo pm2 start ./dist/index.js
'
Gist Ref: https://gist.github.com/raviagheda/c69ae5e884f4490b1af656dbd80c00dd
Enjoy!
If you are here it means you may have enjoyed reading this blog. Just follow me "Ravi Agheda" which will motivate to write more, and contribute to open source. You can make me a coffee☕️ . Small support comes a long way!
Top comments (0)