LoginSignup
7
5

More than 5 years have passed since last update.

GitLabへ公開鍵を登録したい

Last updated at Posted at 2018-06-06

はじめに

GitLabを使えるようにするときの環境構築。

環境

  • Windows 10
  • Git Bash

Readme(公式)

今から書くこと、全部公式に書いてあることです。
Readme · Ssh · Help · GitLab
https://gitlab.com/help/ssh/README

SSH鍵の生成 CUI Ver.

公式のとおり、Git Bashを起動して次のコマンドを実行する。対話形式で、保存先のパスとパスフレーズが聞かれる。保存先は空のままEnterを押すとデフォルトのパスとなる。(~/.ssh/id_rsa)

なお、コマンドの、your.email@example.com部分は、GitLabへ登録している自分のメールアドレスである必要がある。

$ ssh-keygen -t rsa -C "your.email@example.com" -b 4096
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/username/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/username/.ssh/id_rsa.
Your public key has been saved in /c/Users/username/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx your.email@example.com
The key's randomart image is:
+---[RSA 4096]----+
|   oo=+&X=o. E.  |
|  . ..Oo*+ oo .oo|
|     +=oo o..o.oO|
|     .+= . ...+oB|
|        S   .  =.|
|                o|
|                .|
|                 |
|                 |
+----[SHA256]-----+

GUIでやる場合(Puttygen利用)。TortoiseGitをインストールしていれば、インストールフォルダに.\bin\puttygen.exeが入っているので、鍵を生成してそれぞれ保存する。puttygen.exeがない場合はダウンロードする。

コマンドの時と同じく、Key Comment欄にはGitLabへ登録しているメールアドレスを入力しておく。普通に、Save private keyボタンで、秘密鍵を保存すると、Putty形式の鍵なので、OpenSSH用の鍵も保存しておいたほうがいいかも。

メニューバーのConversions-> Export OpenSSH keyから、ファイルへ保存できる。保存しない場合は、生成結果の画面の、Public key for pasting in to OpenSSH authorized_keys file:の下の箇所をコピペしておく。

GitLabへ公開鍵を登録する

GitLabのSettings -> SSH Keysメニューから、公開鍵の登録する。

接続テスト

デフォルトの保存先パスの場合は何も無しに次のコマンドでテスト。

$ ssh -T git@gitlab.com
Enter passphrase for key '/c/Users/UserName/.ssh/id_rsa':
Welcome to GitLab, UserName!

デフォルトパス以外(~/.ssh/id_rsa)へ鍵を作成していると、接続できないので、いちいちパスを指定しないとだめ。

$ ssh -T git@gitlab.com -i /path/to/private.key

デフォルトのパス以外の鍵を使用する場合

デフォルト以外のパスへ鍵と作成し、その鍵を利用したい場合、次のエラーが発生するので、ssh-addで鍵を登録する必要がある。

git@gitlab.com: Permission denied (publickey).

ほかの鍵を登録する

ssh-agentを起動して、ssh-addコマンドで登録する。

$ eval $(ssh-agent -s)
$ ssh-add ~/.ssh/other_id_rsa
Enter passphrase for /c/Users/UserName/.ssh/other_id_rsa:
Identity added: /c/Users/UserName/.ssh/other_id_rsa (/c/Users/UserName/.ssh/other_id_rsa)

ssh-add -lで鍵の登録状況を確認できます。

$ ssh-add -l
2048 SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx /c/Users/UserName/.ssh/other_id_rsa (RSA)

Git Bashを終了すると元に戻るため、.bash_profileを作成して、上記コマンドを書いておくと起動時に実行されるので楽です。

.bash_profile
eval $(ssh-agent -s)
ssh-add ~/.ssh/other_id_rsa

~/.ssh/configの編集

.ssh/configの設定も編集が必要。

Host gitlab
 User git
 HostName gitlab.com
 IdentityFile ~/.ssh/other_id_rsa

ここまでできれば、pushとかcloneとかできるはず。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5