首页 > 解决方案 > 使用 Azure Devops Pipeline 构建容器时如何将变量传递给 docker

问题描述

我正在尝试使用具有 DDBB 连接的 PHP 项目构建一个容器,并且希望通过环境变量设置 DDBB。

我已经用管道变量定义了变量。

变量

我还在变量部分中设置了变量

variables:
  imageName: 'project'
  repositoryNameDes: 'portalweb-des/project'
  repositoryNamePro: 'portalweb-pro/project'
  connectionECRpredes: 'amazon container registry w-predes'
  connectionECRpro: 'amazon container registry w-pro'
  tName: $(Build.SourceBranchName)_$(Build.SourceVersion)
  ecrRepositoryNameBaseUrl: '513537361685.dkr.ecr.eu-west-1.amazonaws.com'
  dirNameS3: 'project'
  bucketNameDes: 'cluster-drupal-des-deploy-s3'
  deployOnECS: $[or(startsWith(variables['Build.SourceBranch'], 'refs/heads/tags/'), startsWith(variables['Build.SourceBranch'], 'refs/heads/develop'), startsWith(variables['Build.SourceBranch'], 'refs/heads/feature/generardocker'))]
  ddbb_name: $(DDBB_NAME)

但是我在构建时看不到如何加载变量,我不确定是否有选项设置环境变量,如果我必须编写自定义构建以使用变量运行或如何做了。

steps:
- task: Docker@2
  displayName: Build an image
  inputs:
    repository: $(imageName)
    command: build
    Dockerfile: Dockerfile
    tags: $(tName)
- task: ECRPushImage@1
  inputs:
    ENV: '$(dev)'
    awsCredentials: '$(connectionECRpredes)'
    regionName: 'eu-west-1'
    imageSource: 'imagename'
    sourceImageName: '$(imageName)'
    sourceImageTag: '$(tName)'
    repositoryName: '$(repositoryNameDes)'
    pushTag: $(tName)

标签: dockerazure-devopsazure-pipelines

解决方案


在最常见的情况下,您设置变量并在 YAML 文件中使用它们。这使您可以跟踪版本控制系统中变量的更改。您还可以在管道设置 UI 中定义变量(请参阅经典选项卡)并在 YAML 中引用它们。

这是一个示例,展示了如何设置两个变量configurationplatform,并在稍后的步骤中使用它们。要在 YAML 语句中使用变量,请将其包装在$().

# Set variables once
variables:
  configuration: debug
  platform: x64

steps:

# Use them once
- task: MSBuild@1
  inputs:
    solution: solution1.sln
    configuration: $(configuration) # Use the variable
    platform: $(platform)

# Use them again
- task: MSBuild@1
  inputs:
    solution: solution2.sln
    configuration: $(configuration) # Use the variable
    platform: $(platform)

您可以查看以下链接以获取更多详细信息:

https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch


推荐阅读