Azure DevOps管道中如何引用根目录下的其他文件夹?
问题描述
在Azure DevOps中,我需要运行.ci/build.yml管道来构建python/version/flavor文件夹中的镜像。每个版本对应一个Dockerfile和包含镜像标签等变量的version.yml,且所有构建必须使用项目根目录作为构建上下文。
当前管道配置中,引用version.yml和Dockerfile时,系统会从.ci目录开始查找路径,报错:
/.ci/build.yml: File /.ci/python/3.10/bookworm/version.yml not found in repository
尝试使用Azure DevOps变量未解决问题,求最优解决方案。
文件夹结构
project-root/ ├── .ci/ │ └── build.yml │ ├── README.md ├── certs.crt ├── config.json │ └── python/ ├── 3.10/ │ └── bookworm/ │ ├── Dockerfile │ └── version.yml │ ├── 3.11/ │ └── bookworm/ │ ├── Dockerfile │ └── version.yml │ └── 3.12/ └── bookworm/ ├── Dockerfile └── version.yml
version.yml示例
variables: TAG1: python-3.10-bookworm TAG2: python-3.10-slim-bookworm
当前管道配置(存在问题)
trigger: none parameters: - name: imageList type: object default: ["3.10/bookworm", "3.11/bookworm", "3.12/bookworm", ] stages: - stage: build pool: MyLinuxPool jobs: - ${{ each image in parameters.imageList }}: - job: image_${{ replace(replace(replace(image, '-', '_'), '.', '_'), '/', '_') }} variables: - template: 'python/${{ image }}/version.yml' # 问题所在 - name: dockerfile value: 'python/${{ image }}/Dockerfile' # 同样问题 steps: - task: Docker@2 displayName: Login to ACR inputs: containerRegistry: SOME-ACR command: login - task: Docker@2 displayName: Build & Push image inputs: command: buildAndPush repository: foo/bar dockerfile: $(dockerfile) buildContext: '.' arguments: '--no-cache' tags: | ${{ variables.TAG1 }} ${{ variables.TAG2 }}
解决方案
问题根源是Azure DevOps管道中引用模板文件时,路径是相对于当前管道文件所在目录的。你的build.yml在.ci目录下,直接写python/${{ image }}/version.yml会被解析为.ci/python/...,自然找不到文件。
最优解决方式是在路径前加上../,回到项目根目录后再定位目标文件:
修改后的管道配置
trigger: none parameters: - name: imageList type: object default: ["3.10/bookworm", "3.11/bookworm", "3.12/bookworm", ] stages: - stage: build pool: MyLinuxPool jobs: - ${{ each image in parameters.imageList }}: - job: image_${{ replace(replace(replace(image, '-', '_'), '.', '_'), '/', '_') }} variables: # 用../回到项目根目录,再指向python下的version.yml - template: '../python/${{ image }}/version.yml' - name: dockerfile # Dockerfile路径同样需要调整 value: '../python/${{ image }}/Dockerfile' steps: - task: Docker@2 displayName: Login to ACR inputs: containerRegistry: SOME-ACR command: login - task: Docker@2 displayName: Build & Push image inputs: command: buildAndPush repository: foo/bar dockerfile: $(dockerfile) buildContext: '.' arguments: '--no-cache' tags: | ${{ variables.TAG1 }} ${{ variables.TAG2 }}
补充说明
- Docker任务的
buildContext设置为.是正确的,确保以项目根目录作为构建上下文,这样Dockerfile中引用根目录下的certs.crt、config.json等文件不会出错。 - 模板文件和普通文件的路径解析逻辑一致,都需要相对于当前管道文件的位置调整路径层级。
内容的提问来源于stack exchange,提问作者Vitamin C
相关产品推荐
相关产品推荐

