build-push-action
build-push-action copied to clipboard
A documentation for using ssh key from github secret to `--ssh` variable
It'd be incredibly helpful to have an example of how to use the --ssh
option when one has a private key stored as a secret on the repository.
Here's an example to load a SSH key in your workflow and use it in your Dockerfile to fetch Go modules from private repos:
-
name: Checkout
uses: actions/checkout@v3
-
name: Set up SSH
uses: MrSquaare/ssh-setup-action@c86f64bc308405a10f3c9f2ef6124fdf4370e677 # v2.0.0
with:
host: github.com
private-key: ${{ secrets.SSH_GITHUB_PPK }}
private-key-name: github-ppk
-
name: Build and push
uses: docker/build-push-action@v4
with:
context: .
ssh: default
push: true
tags: user/app:latest
# syntax=docker/dockerfile:1
ARG GO_VERSION="1.20"
FROM golang:${GO_VERSION}-alpine AS base
ENV CGO_ENABLED=0
ENV GOPRIVATE="github.com/foo/*"
RUN apk add --no-cache file git rsync openssh-client
RUN mkdir -p -m 0700 ~/.ssh && ssh-keyscan github.com >> ~/.ssh/known_hosts
WORKDIR /src
FROM base AS vendor
# this step configure git and checks the ssh key is loaded
RUN --mount=type=ssh <<EOT
set -e
echo "Setting Git SSH protocol"
git config --global url."[email protected]:".insteadOf "https://github.com/"
(
set +e
ssh -T [email protected]
if [ ! "$?" = "1" ]; then
echo "No GitHub SSH key loaded exiting..."
exit 1
fi
)
EOT
# this one download go modules
RUN --mount=type=bind,target=. \
--mount=type=cache,target=/go/pkg/mod \
--mount=type=ssh \
go mod download -x
FROM vendor AS build
RUN --mount=type=bind,target=. \
--mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache \
go build ...
I found that you need to specify ssh default equals the agent socket:
- name: Build and push
uses: docker/build-push-action@v5
with:
ssh: |
default=${{ env.SSH_AUTH_SOCK }}
context: .
push: true
tags: |
myimage:latest
This should be enough:
with:
ssh: default
@dvdksn Maybe we could make some docs for ssh using https://github.com/docker/build-push-action/issues/714#issuecomment-1600537437
This works for me: just save ssh private key to a temporary file and use it in ssh variable.
# .github/workflows/image-build.yaml
jobs:
build-image:
steps:
- name: Save ssh private key file
run: echo "${{ secrets.DEPLOY_SSH_PRIVATE_KEY }}" > deploy-ssh-key
- name: Build and push app image
uses: docker/build-push-action@v5
with:
context: .
push: true
file: Dockerfile
ssh: |
default=deploy-ssh-key
# Dockerfile
...
RUN --mount=type=ssh conda env create -f environment.yml
...