How to Add a Deploy Key to GitHub: Step-by-Step Guide
Deploy keys are a secure way to grant read or write access to your GitHub repository from a server. Learn how to generate, configure, and test deploy keys in this easy-to-follow tutorial.
Using a deploy key is an efficient and secure method to give a server access to your GitHub repository. Follow these steps to set it up: Check if You already have a SSH key
ls -la ~/.ssh
If you see something like id_rsa.pub Go to step 2, otherwise continue with step 1.
[1. Generate an SSH Key Pair
On the machine where you need the deploy key, generate an SSH key pair by running:
ssh-keygen -t rsa -b 4096 -C "deploy-key"
You’ll be prompted to specify a location for the key. You can press Enter to accept the default or specify a custom path, like:
/home/user/.ssh/deploy_key
When prompted for a passphrase, leave it empty. This is important for automation purposes.
2. Add the Deploy Key to GitHub
Now, copy the public key. Run this command (adjust the path if you used a custom location):
cat ~/.ssh/deploy_key.pub
Next, go to your GitHub repository:
Navigate to **Settings > Deploy keys**.
Click **Add deploy key**.
Paste the public key into the "Key" field.
Provide a meaningful title, such as **"Server XYZ Deploy Key"**.
If your deploy key needs write access, check the box labeled **Allow write access** (optional).
Click **Add key**.
3. Configure SSH Access
You need to add the private key to your SSH agent on your server. Run:
ssh-add ~/.ssh/deploy_key
If your server doesn’t automatically use the correct key for GitHub, you can create or edit the SSH configuration file:
nano ~/.ssh/config
Add the following lines:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/deploy_key
IdentitiesOnly yes
This configuration ensures that your server uses the correct SSH key when connecting to GitHub. 4. Test the Connection Verify that everything works by running:
ssh -T git@github.com
You should see a message like: Hi <username/repo>! You've successfully authenticated, but GitHub does not provide shell access. 5. Update Git Remote URL (if necessary) If you cloned your repository using HTTPS, you’ll need to switch to the SSH format to use your deploy key. Run this command to update your remote URL:
git remote set-url origin git@github.com:<your repo ssh path>
Then verify the change:
git remote -v
This should now show the SSH URL for both fetch and push operations. Summary
Deploy keys are a powerful way to automate access to your GitHub repositories from servers, especially for CI/CD or deployment workflows. Just remember to safeguard your private keys and grant access responsibly.