Azure 管道 - 动态获取变量

问题描述 投票:0回答:1

我在我的 azure 管道中定义了一个名为 tst-my--variable 的变量,以及另一个名为 uat-my--variable 的变量,如下所示。 enter image description here

当我运行 azure-pipelines.yml 时,我正在检查管道执行的环境并定义变量“environmentName”。

之后,我想通过将变量“environmentName”值与文本“-my--variable”连接来获得“tst-my--variable”“uat-my--variable”之一。 但没有任何效果。

steps:
- script: | 
    echo $MY_ENV
  env:
    MY_ENV: $($(environmentName)-my--variable)

我已经检查过这篇文章但没有帮助。

azure azure-pipelines azure-pipelines-yaml
1个回答
0
投票

这不是对您问题的直接回答,但请允许我建议一种不同的方法来解决您的问题。

1.为每个环境创建变量模板

根据变量重用,创建一个单独的模板来存储每个环境的变量:

测试变量:

# /pipelines/variables/tst-variables.yaml

variables:
  - name: MY_ENV
    # use another variable's value or, as an alternative, an hard-coded value
    value: $(tst-my--variable)

  # Other TEST-related variables here

UAT 变量:

# /pipelines/variables/uat-variables.yaml

variables:
  - name: MY_ENV
    # use another variable's value or, as an alternative, an hard-coded value
    value: $(uat-my--variable)

  # Other UAT-related variables here

2.根据环境引用变量模板

使用环境管道参数(而不是管道变量)的示例管道。

然后使用该参数动态引用正确的变量模板:

parameters:
  - name: environmentName
    displayName: 'Environment Name'
    type: string
    default: 'tst'
    values:
      - 'tst'
      - 'uat'

trigger: none

pool:
  vmImage: 'ubuntu-latest'

variables:
  - template: /pipelines/variables/${{ parameters.environmentName }}-variables.yaml

steps:
  - checkout: none

  - script: | 
      echo "$(MY_ENV)"
    displayName: 'Print the value of pipeline variable'
© www.soinside.com 2019 - 2024. All rights reserved.