Access Private GitHub Repositories on an EC2 Server
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.
or with new key path
ssh-keygen -t ed25519 -f ~/.ssh/github_key -C "your-email@example.com" - 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 # or cat ~/.ssh/github_key.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.
-
On GitLab: Go to Settings > Repository > Deploy Keys.
-
On Bitbucket: Go to Repository settings > Access keys > Add key.
-
Step 3: Test SSH Connection to GitHub
Verify that the connection is successful:
ssh -T git@github.com
# or with new key
ssh -T git@github.com -i ~/.ssh/github_keyExpected output:
Hi your-github-username! You've successfully authenticated, but GitHub does not provide shell access.
Git isn't automatically using that specific key (If used except default one). You just need to tell it to use it.
Create a config file:
vi ~/.ssh/configAdd the following to the config file:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/github_keychmod 600 ~/.ssh/configStep 4: Clone a Private Repository
Now that authentication is set up, clone the private repository:
git clone git@github.com:your-username/private-repo.gitReplace 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
Be the first to comment.