Shred IT!!!!

IT全般について試したこと・勉強したことを綴ったり、趣味について語るブログ

Mac から踏み台サーバ経由(SSHトンネル)で git する方法

踏み台サーバ経由で git する方法をメモしておく。
Linux でも同じ、.ssh/config を編集して踏み台サーバ経由(SSHトンネル)する方。

あくまで Mac(ローカルマシン)から、git コマンドを直接叩きたいときの設定。
踏み台サーバ上で作業する場合の設定ではない。

踏み台サーバ経由(SSHトンネル)する ~/.ssh/config の設定

前提条件

  • bastion(踏み台サーバ)

    • tsuyacchi というユーザを追加済み
    • 公開鍵・秘密鍵を設定/設置済み
      • Mac(ローカルマシン)側には秘密鍵(~/.ssh/tsuyacchi_id_rsa
      • サーバ側には公開鍵(cat tsuyacchi_id.pub >> ~/.ssh/authorized_keys)
  • git_repository(git サーバ)

    • bastion からのアクセスのみ許可
    • gitolite を使っていて、git ユーザで git の操作を行っている
    • 公開鍵・秘密鍵を設定/設置済み
      • ローカルマシン(Mac)側には秘密鍵(~/.ssh/git_tsuyacchi_id_rsa
      • サーバ側には公開鍵 tsuyacchi.pub
        • gitolite 上で tsuyacchi ユーザを追加済み({gitolite_dir}/keydir/tsuyacchi.pub)

設定ファイルの編集

# Mac(ローカルマシン)の ~/.ssh/config
Host bastion  # ホスト名(任意)
  User  tsuyacchi  # ユーザ名
  HostName  xxx.xxx.xxx.xxx  # IP or ホスト名
  Port  22  # ポート番号
  IdentityFile  ~/.ssh/tsuyacchi_id_rsa  # 秘密鍵ファイルパス

Host git_repository  # ホスト名(任意) 
  User  git  # ユーザ名
  HostName  yyy.yyy.yyy.yyy  # IP or ホスト名
  IdentityFile  ~/.ssh/git_tsuyacchi_id_rsa  # 秘密鍵ファイルパス
  ProxyCommand ssh bastion -W %h:%p  # SSHトンネル(bastion)
  # ProxyCommand ssh bastion nc %h %p
  # バージョンによって nc と -W 使い分ける

コマンド

git clone git_repository:hoge.git

git_repository は ~/.ssh/config の Host で設定した名前を利用している。
gitolite 以外でも適時設定を書き換えれば、大体こんな感じの設定で問題ないはず。
注意点があるとしたら、git_repository へのログインアカウントが共有アカウントなのか否か。

おまけ

SSH したい場合

仮に上記で設定した踏み台サーバ経由で WEB サーバに接続したい場合。

# Mac(ローカルマシン)の ~/.ssh/config
Host web_server  # ホスト名(任意) 
  User  tsuyacchi  # ユーザ名
  HostName  zzz.zzz.zzz.zzz  # IP or ホスト名
  IdentityFile  ~/.ssh/web_tsuyacchi_id_rsa  # 秘密鍵ファイルパス
  ProxyCommand  ssh bastion -W %h:%p  # SSHトンネル(bastion 経由)

ユーザ名・IP・秘密鍵等の設定を適時変更して、下記コマンドを叩くだけ。

ssh web_server

ちなみにこんな風にも書ける。

ssh -oProxyCommand='ssh -W %h:%p bastion' tsuyacchi@zzz.zzz.zzz.zzz -i ~/.ssh/web_tsuyacchi_id_rsa
多段SSH(踏み台が複数ある場合)
# Mac(ローカルマシン)の ~/.ssh/config
Host bastion1  # ホスト名(任意)
  User  tsuyacchi  # ユーザ名
  HostName  xxx.xxx.xxx.xxx  # IP or ホスト名
  IdentityFile  ~/.ssh/bastion1_id_rsa  # 秘密鍵ファイルパス

Host bastion2  # ホスト名(任意) 
  User tsuyacchi  # ユーザ名
  HostName yyy.yyy.yyy.yyy  # IP or ホスト名
  IdentityFile ~/.ssh/bastion2_id_rsa  # 秘密鍵ファイルパス
  ProxyCommand ssh bastion1 -W %h:%p  # SSHトンネル(bastion1)

Host goal  # ホスト名
  User tsuyacchi  # ユーザ名
  HostName zzz.zzz.zzz.zzz  # IP or ホスト名
  IdentityFile ~/.ssh/goal_id_rsa  # 秘密鍵ファイルパス
  ProxyCommand ssh bastion2 -W %h:%p  # SSHトンネル(bastion2)

コマンドは下記。

ssh goal

これで bastion1 -> bastion2 -> goal の多段 SSH が行われる。

トンネル(多段)する数が増えても、ProxyCommand でリレーする順番や指定を間違わなければ問題ない。

関連記事

jetglass.hatenablog.jp