Access Private GitHub Repositories on an EC2 Server
On This Page
Step 1: Generate an SSH Key on EC2
To securely authenticate with GitHub, generate an SSH key on your EC2 instance.
Connect to your EC2 instance via SSH:
ssh ec2-user@your-ec2-public-ip
Generate an SSH key:
ssh-keygen -t rsa -b 4096 -C "your-email@example.com"
- Press Enter to save the key in the default location (
~/.ssh/id_rsa
). - Set a passphrase or leave it empty.
- Press Enter to save the key in the default location (
Start the SSH agent and add the key:
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_rsa
Step 2: Add the SSH Key to GitHub
Display the public key:
cat ~/.ssh/id_rsa.pub
Copy the output and add it to GitHub:
- Go to GitHub → Settings → SSH and GPG keys link
- Click New SSH key.
- Paste the key and save.
Step 3: Test SSH Connection to GitHub
Verify that the connection is successful:
ssh -T git@github.com
Expected output:
Hi your-github-username! You've successfully authenticated, but GitHub does not provide shell access.
Step 4: Clone a Private Repository
Now that authentication is set up, clone the private repository:
git clone git@github.com:your-username/private-repo.git
Replace your-username
and private-repo
with the actual repository details.
Step 5: Configure Git (Optional)
To avoid re-entering your username and email, configure Git globally:
git config --global user.name "Your Name"
git config --global user.email "your-email@example.com"
Alternative: Using a Personal Access Token
If you prefer HTTPS authentication instead of SSH:
Generate a Personal Access Token (PAT) on GitHub:
- Go to GitHub → Settings → Developer Settings → Personal Access Tokens.
- Generate a token with repo permissions.
Use the token instead of a password:
git clone https://your-username:your-token@github.com/your-username/private-repo.git