【问题标题】:Referencing yaml variables in AzurePowerShellV5 inline script在 AzurePowerShellV5 内联脚本中引用 yaml 变量
【发布时间】:2021-02-20 06:37:25
【问题描述】:
我有一个 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?
【问题讨论】:
标签:
azure
powershell
azure-devops
【解决方案1】:
我把它精简到最简单的状态,它工作得很好:
pool:
vmImage: 'windows-latest'
variables:
myVar: test value
steps:
- powershell: Write-Host "$(myVar)"
生成:
我修改了您的示例以删除未编译的env 块,并删除不正确的变量引用:
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'
得到:
它没有通过第一个,因为语法 $(variables.MyVar) 无效。语法如下:
- 编译时间(只能在声明变量的文件中使用,不能用于模板等嵌套文件):
${{ variables.MyVar }}
- 运行时(任务执行前):
$(MyVar) - 如果为空,则扩展为“$(MyVar)”
- 运行时(专为条件设计,或默认值导致问题):
$[variables.MyVar] - 如果为空则扩展为空字符串
我想知道缺少 Azure Powershell 版本是否是您的问题的一部分?
【解决方案2】:
当您指定 env 块时,它会将变量创建为环境变量。
在 PowerShell 中,您使用 $env:VariableName 引用环境变量。所以在你的情况下,$env:DoesThisWork。