IaC/Configuration Management

Git에서 2개의 계정(SSH Key) 사용하기

Somaz 2024. 6. 13. 16:42
728x90
반응형

Overview

보통 회사의 Github 계정과 자신의 Github 계정을 분리하지 않고 사용하는 사람들이 꽤 있다.

 

따라서 Git에서 2개의 계정을 사용하는 방법에 대해서 알아본다. 

 


Git에서 2개의 계정(SSH Key) 사용하는 방법

 

1. 2개의 계정 생성 후 2개의 SSH Key 생성

# Key 생성
ssh-keygen -t rsa -C "somaz94@email.com" -f "id_rsa_somaz94"
ssh-keygen -t rsa -C "somazcompany@email.com" -f "id_rsa_somazcompany"

# 확인
ls -l
-rw------- 1 somaz somaz 2610 Mar 31 10:15 id_rsa_somaz94
-rw-r--r-- 1 somaz somaz  574 Mar 31 10:15 id_rsa_somaz94.pub
-rw------- 1 somaz somaz 2602 Mar 20 14:23 id_rsa_somazcompany
-rw-r--r-- 1 somaz somaz  570 Mar 20 14:23 id_rsa_somazcompany.pub

 

2. `.ssh/config` 수정

cat ~/.ssh/config
Host github.com-somaz94
  Hostname github.com
  User somaz94
  IdentityFile ~/.ssh/id_rsa_somaz94 # private key 저장

 

 

3. `.gitconfig` 와 `.gitconfig-private` 수정

cat ~/.gitconfig
[user]
        email = somazcompany@somazcompany.com
        name = somazcompany

# PrviateWork 디렉토리 사용
[includeIf "gitdir:~/PrivateWork/"]
    path = ~/.gitconfig-private
    
 
cat ~/.gitconfig-private
[user]
    email = somaz94@somaz94.com
    name = somaz94

 

 

4. 사용법

회사의 github를 클론할땐 `~/PrivateWork` 폴더를 제외하고 기존과 동일하게 클론뜨면 된다.

git@github.com:{user}/tmp-test.git

 

 

그리고 Private한 개인 작업을 할때는 `~/PrivateWork` 폴더로 접속해서 아래와 같이 사용할 수 있다.

# 틀린예시
git@github.com:{user}/tmp-test.git : X

# 맞는 예시
cd ~/PrivateWork
git@github.com-somaz94:somaz94/tmp-test.git # -{User} 입력 : ~/.ssh/config

 

아래와 같이 확인 가능하다.

# 확인
git config -l
user.email=somazcompany@somazcompany.com
user.name=somazcompany
includeif.gitdir:~/PrivateWork/.path=~/.gitconfig-private
core.editor=vi

 

 


Reference

https://gist.github.com/jexchan/2351996

https://gist.github.com/oanhnn/80a89405ab9023894df7

728x90
반응형