LoginSignup
0
0

More than 1 year has passed since last update.

Go言語でプライベートなGithubリポジトリにあるモジュールを利用し、DockerでBuildを行う方法

Last updated at Posted at 2021-11-01

経緯

  • Go 言語で開発したバックエンド API を Docker イメージにビルドしたい
  • Go モジュールに社内で共有している非公開リポジトリにあるライブラリ(非公開ライブラリ)を含んでいる
  • docker のイメージをビルドするとき、go mod download の箇所でライブラリにアクセスできないためエラーとなる

原因

  • Docker ビルド時に Gitの認証情報を含んでいないため、非公開ライブラリにアクセスできない
  • マイPCにはGitアカウントの認証情報があるため、ローカル環境では問題なく go install が行える

対応

  • 秘密鍵を生成し、非公開リポジトリに公開鍵を設定する
  • バックエンド API に、非公開ライブラリにSSH通信するための秘密鍵とSSHのconfigを配置する
  • Dockerfile で 非公開ライブラリにアクセスするための設定を行う

秘密鍵をGitリポジトリにおくことに抵抗がある人は、github の secrets を利用するなりしてください

秘密鍵を生成し、非公開リポジトリに公開鍵を設定する

  • 秘密鍵と公開鍵を生成する
ssh-keygen -t rsa

Windows でも Git をインストールすれば ssh-keygen を利用できると思います

  • 非公開なGithubリポジトリに公開鍵を登録する

Github 公式に手順が記載されています

バックエンド API に、非公開ライブラリにSSH通信するための秘密鍵とSSHのconfigを配置する

  • 秘密鍵とconfigの配置

以下のディレクトリ構成を想定します。certs以下に secrets.pem と config を配置しています

/
├ certs
│   ├ secrets.pem  # 秘密鍵
│   └ config # SSH Config
├ main.go
├ go.mod
└ dockerfile
  • config
Host github.com
  Hostname github.com
  User git
  IdentityFile /go/src/certs/readonly

Dockerfile で 非公開ライブラリにアクセスするための設定を行う

該当の部分だけ記載します

  • dockerfile
COPY ./certs/config  /root/.ssh/config
RUN chmod 600 ./certs/readonly
RUN chmod 600 /root/.ssh/config
RUN git config --global url."git@github.com:<account>/<repository>".insteadOf "https://github.com/<account>/<repository>"
RUN ssh -o StrictHostKeyChecking=no -i ./certs/readonly -T git@github.com || true
RUN export GOPRIVATE=github.com/<account>/<repository>
RUN go mod download

エラーが出なければ OK

追記

2021-11-19

  • Linux(WSL) で動作検証をしています。Windows で試すときは CRLF <=> LF などを注意してください
  • SSH 周りのエラーを確認したいときは、
RUN ssh -o StrictHostKeyChecking=no -i ./certs/readonly -T git@github.com || true

の部分を

RUN ssh -o StrictHostKeyChecking=no -i ./certs/readonly -T git@github.com

にして実行してみてください。

Hi xxxxxx/xxxxx! You've successfully authenticated, but GitHub does not provide shell access.

以外のメッセージが出ていれば成功しています。

0
0
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
0
0