Inject private ssh key securely into a Docker container
How use your private ssh key in a secure way into container without duplicate files or use risky configurations
Sometimes it can happen that your project has a private dependency and to install the latter it is necessary to perform an authentication on a private repository.
The authentication that can be more easily automated is the one using the SSH private key, but at the same time it is the one to which we must pay more attention to avoid sharing it and making it easily accessible.
Docker secret were used to make this information available in a docker container; for more information, see the official docker documentation:
- https://docs.docker.com/engine/swarm/secrets/
- https://docs.docker.com/compose/compose-file/#secrets-configuration-reference
Now explain how.
We'll use this docker-compose.yml as example.
1) Definition of a secret inside docker-compose.yml
secrets:
id_rsa:
file: # path to your private ssh key
We must declare the absolute path of our ssh private key
2) Inject the secret into a service
version: '3.1'
app:
secrets:
- id_rsa
3) Build container though Dockerfile and run an init script to setup ssh key into the container
services:
app:
build:
context: .
working_dir: /usr/app
volumes:
- ./init.sh:/init.sh
command: sh init.sh
At the end, the resulting file will be:
version: '3.1'
services:
db:
build:
context: .
working_dir: /usr/app
volumes:
- ./init.sh:/init.sh
command: sh init.sh
secrets:
- id_rsasecrets:
id_rsa:
file: # path to your private ssh key
4) Write Dockerfile
Into the Dockerfile we'll install git, ssh-agent and a ssh client
FROM ubuntu
RUN apt-get update
RUN apt-get install -y git-core
RUN apt-get install -y openssh-client
5) Write init script
Into the init script, we'll add private ssh to ssh-agent and dependency host to know_host list (to prevent user prompt request)
#!/bin/bash
eval "$(ssh-agent -s)"
if [ ! -d "/root/.ssh/" ]; then
ssh-add -k /run/secrets/id_rsa
mkdir /root/.ssh
ssh-keyscan github.com > /root/.ssh/known_hosts
# now execute command which require authentication via ssh (example, git clone from a private repo)
fi
We can use this script to install the private dependency or use the project's package manager.
Now we can install any dependencies we are authorized to!