无法获取Azure管道中变量内部的变量值

kx5bkwkv  于 2023-01-02  发布在  其他
关注(0)|答案(2)|浏览(147)

我尝试在Azure管道中使用变量内部的变量。下面是bash脚本的一个例子:

#!/bin/bash

customer=google
environment=preprod
android_google_preprod_account_activation_url=preprod.google.com

echo "Customer is $customer"
echo "Environment is $environment"

var1=android_${customer}_${environment}_account_activation_url

echo "variable is $var1"
echo "original value is ${!var1}"

当我在Ubuntu服务器上运行上述bash脚本时,我得到了预期的输出,没有错误:

Customer is google
Environment is preprod
variable is android_google_preprod_account_activation_url
original value is preprod.google.com

Azure管道的yml代码为:

parameters:
  - name: customer
    displayName: 'select customer'
    type: string
    values:
      - google
  - name: environment
    displayName: 'select environment'
    type: string
    values:
      - preprod

variables:
  - group: android-${{ parameters.customer }}-${{ parameters.environment }}
  - name: var1
    value: android-${{ parameters.customer }}-${{ parameters.environment }}-account-activation-url

script: |
      echo "Customer is $(customer)"
      echo "Environment is $(environment)"
      echo "variable is $(var1)"
      echo "original value is $(!var1)"
    displayName: 'echo variables'

android-google-preprod-account-activation-url的值取自库中的变量组。
它给了我一个错误的第四行:

invalid indirect expansion

前3行输出符合预期。
预期输出为:

Customer is google
Environment is preprod
variable is android_google_preprod_account_activation_url
original value is preprod.google.com

在azure管道中是否需要遵循不同的语法?

pgky5nke

pgky5nke1#

我不是bashMaven)))然而...你尝试使用参数扩展What is indirect expansion? What does ${!var*} mean?
但是它引用了bash变量....当您在devops管道中定义变量时,您必须将它们作为环境变量或通过宏使用。
或者类似的东西

android_google_preprod_account_activation_url=preprod.google.com

echo "Customer is $(customer)"
echo "Environment is $(environment)"

var1=android_$(customer)_$(environment)_account_activation_url

echo "variable is $var1"
echo "original value is ${!var1}"
5jvtdoz2

5jvtdoz22#

宏语法“$(varName)”是Azure管道中用于插入变量值的专有语法。它在运行时期间进行处理,与Bash脚本中的语法“${varName}”不同。
对于您的情况,可以尝试使用编译时语法“${{ variables.varName }}”来获取管道中的值。

echo "original value is $(${{ variables.var1 }})"

根据上述更改,触发管道后:

  • 在编译时,表达式“${{ variables.var1 }}”将替换为实际值“android_google_preprod_account_activation_url"。因此,表达式“$(${{ variables.var1 }})”将更改为“$(android_google_preprod_account_activation_url)"。
  • 然后在运行时,表达式将被解析为正确的值“preprod.google.com"。

下面是我自己测试过的一个例子。

YAML
variables:
  android_google_preprod_account_activation_url: 'preprod.google.com'
  var1: 'android_google_preprod_account_activation_url'

jobs:
- job: A
  displayName: 'Job A'
  pool:
    vmImage: ubuntu-latest
  steps:
  - checkout: none
  - task: Bash@3
    displayName: 'Print variables'
    inputs:
      targetType: inline
      script: |
        echo "android_google_preprod_account_activation_url = $(android_google_preprod_account_activation_url)"
        echo "var1 = $(var1)"
        echo "original value = $(${{ variables.var1 }})"
结果

有关详细信息,请参考相关文档“了解变量语法"。

相关问题