Passing SSH key variable from Bitbucket Pipelines to a Dockerfile.
Platform Notice: Cloud Only - This article only applies to Atlassian products on the cloud platform.
Summary
In Bitbucket Pipelines, there are some scenarios where it's required to run ssh commands inside a Dockerfile.
Cause
The Dockerfile within the Pipeline by default doesn't have access to the SSH key variables configured in Bitbucket Pipelines.
Solution
The key has to be added as an environment variable and explicitly passed as an argument to the Dockerfile.
Currently, Bitbucket Pipelines do not support line breaks in environment variables, so base-64 encode the private key by running:
Linux:
1
$ base64 -w 0 < my_ssh_key
macOS:
1
$ base64 < my_ssh_key
Then, use the SSH key variable in the Dockerfile:
Dockerfile
1
2
3
4
5
6
7
FROM atlassian/default-image:3
ARG SSH_PRIVATE_KEY
RUN mkdir -p /root/.ssh/ && chmod 700 /root/.ssh
RUN (umask 077 ; echo $SSH_PRIVATE_KEY | base64 --decode > ~/.ssh/id_rsa)
RUN touch ~/.ssh/known_hosts
RUN ssh-keyscan -T 60 bitbucket.org >> ~/.ssh/known_hosts
Pass the SSH key variable using the "--build-arg" argument in the docker build command:
Bitbucket Pipelines Step
1
docker build --build-arg "SSH_PRIVATE_KEY=$SSH_PRIVATE_KEY" .
Note
This method will add the SSH key pair to the docker image which can be accessed by anyone who has access to the image. It is recommended to not use the same key pair for any other purposes.
Was this helpful?