azure - 在 AzurePowerShellV5 内联脚本中引用 yaml 变量

标签 azure powershell azure-devops

我有一个 Azure DevOps yaml 管道,看起来(有点像)像这样:

variables:
  MyVar: Test

Steps:
  - task: AzurePowerShell@5
    displayName: 'Test variables from yml file'
    inputs:
      azureSubscription: MyServiceConnection
      ScriptType: InLineScript
      InLine: |
        Write-Host "I really want to see the values from the variables in the yml file here"
        Write-Host "parameters from the yml file would be great too"
        Write-Host "But what would I write to do that?"
        Write-Host "$(MyVar) <- Nothing here"
        Write-Host "$(variables.MyVar) <- Nothing here"
        Write-Host "$DoesThisWork <- Nothing here"
        Write-Host "$OrThis <- Nothing here"
      env:
        DoesThisWork: $(MyVar)
        OrThis: $(variables.MyVar)

如何在 InLine 脚本中使用 MyVar?

最佳答案

我将其精简为最简单的,它工作得很好:

pool: 
  vmImage: 'windows-latest'

variables: 
  myVar: test value

steps:
  - powershell: Write-Host "$(myVar)"

生成:

Run result

我修改了您的示例以删除未编译的 env block ,并删除了不正确的变量引用:

pool: 
  vmImage: 'windows-latest'

variables: 
  myVar: test value

steps:
- task: AzurePowerShell@5
  inputs:
    azureSubscription: 'My Service Connection Name'
    ScriptType: 'InlineScript'
    Inline: |
      Write-Host "I really want to see the values from the variables in the yml file here"
            Write-Host "parameters from the yml file would be great too"
            Write-Host "But what would I write to do that?"
            Write-Host "$(MyVar) <- Nothing here"
    azurePowerShellVersion: 'LatestVersion'

得到:

Corrected result

它没有通过第一个,因为语法 $(variables.MyVar) 无效。语法的工作原理如下:

  • 编译时(仅在声明变量的文件中可用,不能用于模板等嵌套文件):${{variables.MyVar }}
  • 运行时(任务执行之前):$(MyVar) - 如果为空,则扩展为“$(MyVar)”
  • 运行时(针对特定条件或默认值导致问题的情况而设计):$[variables.MyVar] - 如果为空,则扩展为空字符串

我想知道缺少 Azure Powershell 版本是否是您的问题的一部分?

关于azure - 在 AzurePowerShellV5 内联脚本中引用 yaml 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66288762/

相关文章:

Azure 服务总线 - 结合 SQL 和相关过滤器

azure - 如何诊断和纠正 Azure 公共(public) blob 中的奇怪下载行为?

azure - 以调试或 Release模式发布到 Windows Azure

c# - 如何在没有管理员权限的情况下在 Azure Web 应用程序上安装 PowerShell 模块?

visual-studio - 如何为 Visual Studio Team Services 设置符号服务器

node.js - 在 Node.js 中映射 Azure 表存储数据模型的最简单方法

Powershell:打开 cmd.exe,然后在 cmd 上运行命令

powershell - 在 PowerShell 中的静态类上设置静态属性

Azure 发布管道 - 如果阶段 A 失败,阶段 B 应该运行所有作业,但会跳过

.net - 在 Azure CI 构建期间找不到任何程序集