I'm trying to deploy a Docker image to AWS ECR using Bitbucket Pipeline. In the requirements.txt
file, I have a Python package that originates from a private Bitbucket repo within my project.
Unfortunately, my Bitbucket pipeline builds keep failing. I think I'm missing some essential steps in authentication or pip install
but I can't seem to find the correct documentation for this use case.
Following this Bitbucket community post, I generated a SSH key in my pipeline project and added it to Access Keys in the package repo. Then I followed this post and structured my files as such:
- Dockerfile
# syntax = docker/dockerfile:1.2
FROM python:3.9-slim
WORKDIR /src
# Install git to download private repo
RUN apt-get update && apt-get install -y git
# Add Bitbucket SSH key to install private repo
ARG SSH_PRIVATE_KEY
RUN mkdir ~/.ssh/
RUN echo "${SSH_PRIVATE_KEY}" > ~.ssh/id_rsa
RUN chmod 600 ~/.ssh/id_rsa
RUN touch ~/.ssh/known_hosts
RUN ssh-keyscan bitbucket.org >> ~/.ssh/known_hosts
RUN eval $(ssh-agent -s)
RUN ssh-add ~/.ssh/id_rsa
# Install Python dependencies
RUN pip install --upgrade pip setuptools
COPY requirements.txt requirements.txt
# requirements.txt also includes private repo package
RUN pip install --no-cache-dir -r requirements.txt
# Copy code into `src` folder
COPY src/ /src
# Set up environment variables & secrets
RUN --mount=type=secret,id=keys cat /run/secrets/keys \
&& python -m configs.parser
ENTRYPOINT ["python", "main.py"]
- bitbucket-pipelines.yml
image: atlassian/default-image:2
pipelines:
branches:
master:
- step:
name: Build and AWS Setup
services:
- docker
script:
# Export repo variables to .env file
- export ENV_PATH=src/configs/.env
- echo AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID >> $ENV_PATH
- echo AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY >> $ENV_PATH
- export SSH_PRIVATE_KEY=`cat /opt/atlassian/pipelines/agent/data/id_rsa`
- export TIMESTAMP="$(date +%Y%m%d%H%M%S)"
# Build docker image with secrets mounted
- export DOCKER_BUILDKIT=1
- docker build --build-arg SSH_PRIVATE_KEY --secret id=keys,src=$ENV_PATH -t $AWS_ECR_REPO .
# use pipe to push the image to AWS ECR
- pipe: atlassian/aws-ecr-push-image:1.3.0
variables:
AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
AWS_DEFAULT_REGION: us-east-1
IMAGE_NAME: $AWS_ECR_REPO
TAGS: "latest $TIMESTAMP $BITBUCKET_BUILD_NUMBER"
My pipeline run fails at Step 5 of docker build
with the error: executor failed running [/bin/sh -c echo "${SSH_PRIVATE_KEY}" > ~.ssh/id_rsa]: exit code: 2
Any help with this would be greatly appreciated!