git pull a private repository on docker build by mounting 1Password SSH agent

dockergolang

When building a docker image, it may need to pull a private repository. Mounting a secret key as a secret works, but someone may be using an SSH agent such as 1Password’s one. Specifying the SSH agent’s socket or the key as –ssh, Dockerfile doesn’t need to care about the difference.

Buildkitとは - sambaiz-net

SSH_AUTH_SOCK is referred by default.

$ export SSH_AUTH_SOCK="${HOME}/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock"
$ docker build --ssh default .

Then, by –mount=type=ssh, you can clone a private repository as the host do.

FROM ubuntu

RUN apt-get update && apt-get install -y git

RUN mkdir -p /root/.ssh && echo "StrictHostKeyChecking no" > /root/.ssh/config
RUN --mount=type=ssh git clone [email protected]:sambaiz/privaterepo.git

Similarly, go get also works.

FROM golang:1.21

ENV GOPRIVATE github.com/sambaiz/privaterepo

RUN mkdir -p /root/.ssh && echo "StrictHostKeyChecking no" > /root/.ssh/config && \
    echo "[url \"[email protected]:\"]\n\tinsteadOf = https://github.com/" > /root/.gitconfig

COPY . app
WORKDIR app

RUN --mount=type=ssh go mod init app && go get github.com/sambaiz/privaterepo