且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将env变量注入映像的构建阶段

更新时间:2021-08-05 10:24:19

您的python manage.py collectstatic在docker容器中运行,其os.environ['SECRET_KEY]将尝试获取运行容器的环境变量.但是您在管道中设置的环境变量SECRET_KEY是用于构建代理的.

Your python manage.py collectstatic is running in the docker container, and its os.environ['SECRET_KEY] will try to get the environment variable of the container where it is running. But the environment variable SECRET_KEY you were setting in your pipeline is for build agent.

您可以尝试按照以下步骤将管道env变量传递给docker容器.

You can try following below steps to pass your pipeline env variable to the docker container.

1,我在您的dockerfile ARG SECRET; ENV SECRET_KEY $SECRET

1, I add an ARG and an ENV in your dockerfile ARG SECRET; ENV SECRET_KEY $SECRET

ENV SECRET_KEY表示ARG SECRET

FROM python:3.7-slim

ARG SECRET
ENV SECRET_KEY $SECRET

ENV PYTHONUNBUFFERED 1
WORKDIR /app
EXPOSE 5000
COPY requirements*.txt ./
RUN pip install -r requirements.txt
COPY . .
RUN python manage.py collectstatic
CMD ["gunicorn", "-b", ":5000", "--log-level", "info", "config.wsgi:application"]

2,我将docker buildandpush任务分离为停靠构建和停靠推入,因为buildandpush命令不能接受参数.

2, I separate docker buildandpush task to dock build and dock push, as buildandpush command cannot accept arguments.

在docker build 任务中.我将变量secretKey传递给 arguments 字段--build-arg SECRET=$(secretKey).这样,当docker运行build时,ARG SECRET将被secretKey替换.它将按照上面的dockerfile中的定义传递给ENV SECRET_KEY.以便将SECRET_KEY设置为Docker容器的Environment变量.

In docker build task. I passed the variable secretKey to the arguments field --build-arg SECRET=$(secretKey). So that when docker run build, ARG SECRET will be replaced by secretKey. And it will be passed to the ENV SECRET_KEY as defined in above dockerfile. So that SECRET_KEY will be set to the docker container's Environment variable.

然后,您的python代码应该可以使用os.environ['SECRET_KEY]

Then you python code should be able to get the environment variable's value using os.environ['SECRET_KEY]

stages:
- stage: Build
  displayName: Build and push stage
  jobs:  
  - job: Build
    displayName: Build
    pool:
      vmImage: $(vmImageName)
    steps:
    - task: Docker@2
      displayName: Build
      inputs:
        command: build
        repository: $(imageRepository)-api
        dockerfile: $(dockerfilePath)/api/Dockerfile
        containerRegistry: $(dockerRegistryServiceConnection)

        arguments: --build-arg SECRET=$(secretKey)

        tags: |
          $(tag)

    - task: Docker@2
      displayName: Push
      inputs:
        command: push
        repository: $(imageRepository)-api
        containerRegistry: $(dockerRegistryServiceConnection)
        tags: |
          $(tag)


- upload: manifests
  artifact: manifests