GitHub Actions SSH into AWS EC2

This tutorial shows ways to SSH into AWS EC2 without third-party actions.

Before you start, make sure you have the three things and make sure you can connect to EC2 with them:

  1. AWS EC2 remote hostname
  2. AWS EC2 username
  3. AWS EC2 SSH private key

Add Private Key to GitHub

GitHub allows you store sensitive information in "Secrets", click "New repository secret" to add your private key and save it.
github-add-secret

If you want to add a new user for EC2 to separate users, you can check this tutorial.

Add Workflows

Under your repository's directory ".github", add directory "workflows". Then create a yml file to define GitHub actions, put the following content in the yml file, and replace all string starts with "!!" to your own value. Now you can trigger the GitHub Actions by pushing or pulling request to "main" branch.

name: ssh-into-aws-ec2
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
# bucket_name: "<example-bucket-name>"
AWS_REGION: !!your-aws-region
REMOTE_HOST: "!!replace with your aws remote host"
REMOTE_USER: "!!replace with your ec2 username"
permissions:
contents: read
id-token: write
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Git clone the repository
uses: actions/checkout@v3
- name: Configure SSH
run: |
mkdir -p ~/.ssh/
echo "$SSH_KEY" > ~/.ssh/github-actions-key
chmod 600 ~/.ssh/github-actions-key
cat >>~/.ssh/config <<END
Host ec2
HostName $SSH_HOST
User $SSH_USER
IdentityFile ~/.ssh/github-actions-key
StrictHostKeyChecking no
END
env:
SSH_HOST: ${{ env.REMOTE_HOST }}
SSH_USER: ${{ env.REMOTE_USER }}
SSH_KEY: ${{ secrets.!!secrets_key_name }}
- name: List home directory
run: ssh ec2 'ls -la'