Skip to main content

จัดการ SSH key ส่วนตัวแยกกับของบริษัทแบบง่ายๆด้วย .gitconfig

·2 mins

ปัญหา 🤷‍♂️ #

หลายครั้งที่ผมพยายามใช้ clone repository หรือใช้ private npm module ที่ต้องติดตั้งผ่าน SSH ก็มักจะเจอกับ error แบบนี้

Permission denied
Permission denied ทั้งๆที่ผูก SSH Key กับ Github แล้วแท้ๆ

จะเอา SSH key ตัวเดียวกันกับที่ผูกไว้กับ Github Account ของบริษัทก็ทำไม่่ได้ เพราะ Github ไม่อนุญาตให้ใช้ SSH key เดียวกันในหลาย account

Github SSH Keys
SSH Key ที่ถูก add เข้าไปใน Github แล้ว

แล้วแบบนี้ผมจะทำยังไงกับ project บน organization ที่สร้างขึ้นมาเองส่วนตัวแบบนี้ล่ะ?

private repository
นี่คือ Private repository ของผม

วิธีแก้ปัญหา 💡 #

1. สร้าง SSH key ใหม่สำหรับ account ของคุณเอง #

1.1 เริ่มจากเปิด terminal ขึ้นมาแล้วสร้าง SSH key ใหม่สำหรับ Github account ของคุณเองก่อน

ssh-keygen -t ed25519 -C "[email protected]"

เปลี่ยน [email protected] เป็นเมล์ส่วนตัวของคุณเอง

1.2 หลังจากนั้นก็ระบุ location ที่จะเก็บ SSH key ใหม่ แต่ถ้าไม่ระบุก็จะเก็บไว้ที่

~/.ssh/id_ed25519

แต่ผมแนะนำว่าให้ใส่ชื่อที่สื่อความหมายได้ดีกว่า เช่น

~/.ssh/id_ed25519_personal_github

1.3 ใส่ passphase หรือไม่ใส่ก็ได้ แต่ถ้าใส่ก็จดไว้ดีๆนะครับ

1.4 ทำแบบนี้วนไปเรื่อยๆ ถ้ามี Github account อีกหลายๆตัว

2. สร้าง Git Config สำหรับ Github ส่วนตัว #

2.1 สร้างไฟล์ .gitconfig-personal ของตัวเองขึ้นมาใหม่ใน home directory ของคุณ

nano ~/.gitconfig-personal

หลังจากนั้นก็ copy ข้อมูลด้านล่างไปใส่ในไฟล์ .gitconfig-personal ของคุณ

[user]
	email = "[email protected]"
    name = "Your name"
[core]
	sshCommand = "ssh -i ~/.ssh/id_ed25519_personal_github"

แก้แล้วอย่าลืม save นะครับ 💾

private repository
สร้าง .gitconfig สำหรับ account ส่วนตัว

2.2 แก้ไขไฟล์ .gitconfig ให้เรียกใช้ .gitconfig-personal ที่เพิ่งสร้างขึ้นมา

nano ~/.gitconfig

แก้ไขให้เหมือนด้านล่างนี้

[user]
	name = Your name
	email = [email protected]
[core]
	editor = nano

[includeIf "gitdir:~/Work-company/"]
	path = .gitconfig-ava
[includeIf "gitdir:~/Work-personal/"]
	path = .gitconfig-clonezer

สามารถแบ่งออกไปได้หลายโฟลเดอร์ตามต้องการได้เลยนะครับ การทำแบบนี้จะเป็นการกำหนดไปเลยว่าในแต่ละโฟลเดอร์จะใช้ SSH key ตัวไหน เพื่อให้สะดวกในการทำงานหลาย account

ตั้งค่า .gitconfig
เพิ่ม gitconfig ตาม folder งานต่างๆ

3. ใช้งาน 🚀 #

หลังจากทำตามขั้นตอนทั้งหมดแล้วก็ลอง clone repository ของคุณเองดู ในโฟลเดอร์ที่กำหนดเอาไว้ใน .gitconfig เราก็จะได้ผลลัพธ์อย่างในรูปครับ

private repository
นี่คือ Private repository ของผม

ตามภาพผมเข้าไป clone project นี้จากในโฟลเดอร์ Work-area51 ตามที่ [includeIf "gitdir:~/Work-area51/"] นั่นเองครับ

วิธีนี้จะใช้ได้ผลรวมไปถึงการพยายามใช้ npm module หรือ dependency package manager อื่นๆที่เป็น private repository ด้วยนะครับ อย่างเช่นกรณีแบบนี้

{
    "dependencies": {
        {
            "pdfmake": "git+ssh://[email protected]:your-account/pdfmake-thai-prompt#0.3.1-th",
        }
    }
}

แบบนี้ npm install ก็จะทำงานได้เลยครับ