LoginSignup
5
3

More than 5 years have passed since last update.

DockerでSSH keyを使ってbitbucketの非公開レポジトリをクローン

Posted at

TL;DR

結論からいうと、下記2つコマンドを覚えば話は終わりです。

$ ssh-keyscan -t rsa bitbucket.org >> /root/.ssh/known_hosts
$ ssh-agent bash -c 'ssh-add /PATH/TO/KEY.pem; git clone git@bitbucket.org:YOUR_NAME/YOUR_REPO.git'

方法

キーペアの作成&登録

記事たくさんあるので、割愛します。

Dockerfile

あくまでも一例なので、必要に合わせて修正してください。

FROM ubuntu
# おまじない
RUN apt-get update
RUN apt-get install -y openssl git
WORKDIR /usr/src/app

# known_hostsにbitbucket.orgを登録
# 登録しなければ、キーが正しいであっても通らない
# `Permission denied (publickey).`と怒られる
RUN mkdir /root/.ssh/ && touch /root/.ssh/known_hosts
RUN ssh-keyscan -t rsa bitbucket.org >> /root/.ssh/known_hosts
# GitHubの場合は
RUN ssh-keyscan -t rsa github.com >> /root/.ssh/known_hosts

# キーをコンテナにコピー
COPY ./*.pem /usr/src/app/git-key.pem
RUN chmod 600 /usr/src/app/git-key.pem

# リポジトリのClone
RUN ssh-agent bash -c 'ssh-add /usr/src/app/git-key.pem; git clone git@bitbucket.org:YOUR_NAME/YOUR_REPO.git'

# 使い終わったキーを削除
RUN rm -rf /usr/src/app/git-key.pem

# 一応確認しておく
RUN cd YOUR_REPO && ls -la

余談

ssh-agentコマンドは踏み台サーバーでログインする時も活用出来ます。

参考

https://stackoverflow.com/a/4565746
https://stackoverflow.com/a/23411161
https://stackoverflow.com/a/29380765
https://euske.github.io/openssh-jman/ssh-keyscan.html
https://qiita.com/naoki_mochizuki/items/93ee2643a4c6ab0a20f5

5
3
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
5
3