如何使用 AWS CodeArtifact *within* AWSCodeBuild 中的 Dockerfile

问题描述

我正在尝试从 aws codebuild 中的 dockerbuild 中的 codeartifact 执行 pip 安装。

这篇文章并没有完全解决我的问题:https://docs.aws.amazon.com/codeartifact/latest/ug/using-python-packages-in-codebuild.html

AWS CodeArtifct 的登录在预构建中; Docker 上下文之外。

但我的 pip install 我的 Dockerfile(我们从私有 pypi 注册表中提取)。

在预构建中运行登录命令后,我如何做到这一点,而不是做一些可怕的事情,例如将环境变量设置为从读取 ~/.config/pip.conf/ 派生的密码?

解决方法

所以,这就是我现在解决这个问题的方法。看起来有点 hacky,但它有效:

  1. 在预构建中,我运行命令并将 ~/.config/pip/pip.conf 复制到当前构建目录:
pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      ...
      - echo Fetching pip.conf for PYPI
      - aws codeartifact --region us-east-1 login --tool pip --repository ....
      - cp ~/.config/pip/pip.conf .
  build:
    commands:
      - docker build -t $IMAGE_REPO_NAME:$IMAGE_TAG .
      - docker tag $IMAGE_REPO_NAME:$IMAGE_TAG $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME:$IMAGE_TAG

然后在 Dockerfile 中,我在 COPY 该文件中执行 pip install(您可以设置 PIP_CONFIG_FILE https://pip.pypa.io/en/stable/user_guide/),然后 rm it

,

可以使用的环境 变量:PIP_INDEX_URL[1].

下面是一个 AWS CodeBuild buildspec.yml 文件,我们在其中构建了 PIP_INDEX_URL 用于 CodeArtifact,使用 this example from the AWS documentation

buildspec.yml

  pre_build:
    commands:
      - echo Getting CodeArtifact authorization...
      - export CODEARTIFACT_AUTH_TOKEN=$(aws codeartifact get-authorization-token --domain "${CODEARTIFACT_DOMAIN}" --domain-owner "${AWS_ACCOUNT_ID}" --query authorizationToken --output text)
      - export PIP_INDEX_URL="https://aws:${CODEARTIFACT_AUTH_TOKEN}@${CODEARTIFACT_DOMAIN}-${AWS_ACCOUNT_ID}.d.codeartifact.${AWS_DEFAULT_REGION}.amazonaws.com/pypi/${CODEARTIFACT_REPO}/simple/"

在您的 Dockerfile 中,在正上方添加 ARG PIP_INDEX_URL 行 您的 RUN pip install -r requirements.txt 这样它就可以成为一个环境 构建过程中的变量:

Dockerfile

# this needs to be added before your pip install line!
ARG PIP_INDEX_URL

RUN pip install -r requirements.txt

最后,我们使用 PIP_INDEX_URL build-arg 构建映像。

buildspec.yml

  build:
    commands:
      - echo Building the Docker image...
      - docker build -t "${IMAGE_REPO_NAME}" --build-arg PIP_INDEX_URL .

顺便说一句,将 ARG PIP_INDEX_URL 添加到您的 Dockerfile 不应破坏任何 现有 CI 或工作流。如果省略 --build-arg PIP_INDEX_URL 时 构建图像时,pip 仍将使用默认的 PyPI 索引。

指定 --build-arg PIP_INDEX_URL=${PIP_INDEX_URL} 是有效的,但 不必要。指定没有值的参数名称将使 Docker 采取 它的值来自相同的环境变量 名称[2].

安全说明:如果有人运行 docker history ${IMAGE_REPO_NAME},他们可以 看价值 ${PIP_INDEX_URL}[3] .令牌最多只能使用 12 小时,您可以缩短 使用 --duration-seconds 参数缩短到 15 分钟 aws codeartifact get-authorization-token[4], 所以也许这是可以接受的。如果您的 Dockerfile 是多阶段构建,那么它 如果您没有在目标中使用 ARG PIP_INDEX_URL,这应该不是问题 阶段。 CodeBuild 目前似乎不支持 docker build --secret