2021年11月18日 星期四

[github, key, deploy] How to deploy ssh key for each Github repository

How to deploy ssh key for each Github repository

井民全, Jing, mqjing@gmail.com

Back to the Git Main Page

In this document, I'll show you how to generate a dedicated key pair for each repository. The whole idea[1] is simple and just creates ssh alias.


Enjoy!

By Jing.

1. Quick

Purpose

Create two aliases representing repositories repo-0 and repo-1.

Step 1: Create aliases

File: ~/.ssh/config

# Create an ssh alias host for repo-0, if you like, you can create an alias name as XXXX.

Host repo-0

        Hostname github.com

        IdentityFile=/home/user/.ssh/repo-0_deploy_key


# Create an ssh alias host for repo-1

Host repo-1

        Hostname github.com

        IdentityFile=/home/user/.ssh/repo-1_deploy_key


Step 2: Deploy both public keys to the Deploy Key tab on GitHub project setting dashboard (here, the keys are repo-0_deploy_key.pub and repo-1_deploy_key.pub using ssh-keygen command)

Done!


Now, You can clone and access your repos by following instructions.

git clone git@repo-0:jing-tw/repo-0.git


git clone git@repo-1:jing-tw/repo-1.git


git push is ok.


2. Detail

Step 1: Create an ssh key for lab-python

ssh-keygen


Name the key pair: id_rsa_for_lab-python


Step 2: Deploy the key to github

[github] -> [lab-python] -> [Setting]: Deploy keys

 

(Edit)


Copy the output from the following command to the dashboard.

cat ~/.ssh/id_rsa_for_lab-python.pub


Step 3: Create an ssh alias host for the repo 

Create an ssh alias hostname lab-python to represent the host github.com with the key pair id_rsa_for_lab-python

File: ~/.ssh/config

# Create an ssh alias lab-python for the repo lab-python.git

Host lab-python

    Hostname github.com

    IdentityFile=/home/test/.ssh/id_rsa_for_lab-python


Done!


3. Test

3.1. Test Clone

Step 1: Clone the lab-python repository using 

git clone git@${GITHUBHOST}:OWNER/repository

Ex:

git clone git@lab-python:jing-tw/lab-python.git


Result


3.2. Test Write


// Do some modification.


git add .

git commit

git push


Result


4. Reference

  1. https://docs.github.com/en/developers/overview/managing-deploy-keys#using-multiple-repositories-on-one-server