How to pass Json variable to command line task in Azure DevOps pipeline?

僤鯓⒐⒋嵵緔 提交于 2021-02-11 15:18:13

问题


I am populating a pipeline variable in Powershell task and it is getting populated successfully:

    $env:RESULTJSON=$json
Write-host "##vso[task.setvariable variable=testJSON]$json"

However, when I try to use it to pass the value in a command line task I am not able to do so:

    task: CmdLine@2 
    env:     
      InputJSON: $(testJSON)    
    inputs:      
    script:
        echo %INPUTJSON%        
        'jsonProcessor.exe $(Build.BuildID),%INPUTJSON%'    
    workingDirectory: './jsonProcExe/'

I am getting just "{" in testJSON instead of the whole JSON value.


回答1:


I am not able to get the value of resultJson.

1.If the resultJson is the pipeline variable, you should use InputJSON: $(resultJSON) instead of InputJSON: $($resultJSON).

Assuming the value of pipeline variable resultJSON is 100, then all the tasks within the pipeline can get its value 100. You can modify its value in Task scope using $env:RESULTJSON=$json, then the value of this variable would be the value of $json in that PS task.

But note: Other tasks would get 100 instead of value of $json. (Distinguish the difference between Pipeline Scope and Task Scope)

2.If the resultJson is a variable defined in PS task, then other tasks can't access its value cause the variable is only valid in current session. (You can add second PS task to test it)

To define a variable across multiple tasks/steps, you can use logging command in PS task, check Set variables in scripts .

Update 1

The logging command doesn't support Json format variable directly. So we need to convert it into one line before defining the variable:

$json=$json| ConvertTo-Json -Compress
Write-host "##vso[task.setvariable variable=testJSON]$json"

Update 2

Another direction is to pass the json data via a file. For example first PS task uses $JSON | Out-File Test.json to output the content into Test.json file. And the next PS task uses $Input = Get-Content Test.json and Write-Host $Input to display the value. Also, the second task could be cmd task, their(PS task, CMD task) default working directories are the same one.



来源:https://stackoverflow.com/questions/62533368/how-to-pass-json-variable-to-command-line-task-in-azure-devops-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!