Passing SSH key variable from Bitbucket Pipelines to a Dockerfile.

Still need help?

The Atlassian Community is here for you.

Ask the community

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:
$ base64 -w 0 < my_ssh_key
    • macOS: 
$ base64 < my_ssh_key
  • Then, use the SSH key variable in the Dockerfile:
Dockerfile
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
docker build --build-arg "SSH_PRIVATE_KEY=$SSH_PRIVATE_KEY" .
Last modified on Jan 2, 2024

Was this helpful?

Yes
No
Provide feedback about this article
Powered by Confluence and Scroll Viewport.