Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

azure pipelines - How to pass variables from a PowerShell task to job and stages

I'm trying to understand how to pass environment variables between Azure Pipeline tasks, jobs, and stages. I created a PowerShell task to define variable, according to the docs, but I can't seem to see them after my task completes. Here is a snippet that shows the stage that I create, with jobs and tasks. I'm trying to set the FOO variable in the 'PassVariable' task and then access it from the 'PowerShell' task.

Unfortunately, FOO is never passed. What am I doing wrong?

stages:
- stage: Test
  displayName: Test
  jobs:
  - job: SetSemVer
    displayName: 'Test Var Passing'
    steps:
    
    - task: PowerShell@2
      displayName: 'Pass Variable'
      name: PassVariable
      inputs:
        targetType: 'inline'
        script: |
          echo "##vso[task.setvariable variable=FOO;isOutput=true]Hello World)"

    - task: PowerShell@2
      displayName: 'PowerShell Script'
      name: PowerShellTask
      env:
        myVar: $FOO
      inputs:
        targetType: 'inline'
        script: |
          Write-Host "Foo: $FOO"
question from:https://stackoverflow.com/questions/65836901/how-to-pass-variables-from-a-powershell-task-to-job-and-stages

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You define the name in the power shell task, we need to print the variable via $($env:PASSVARIABLE_FOO) or $(PassVariable.FOO) instead of $FOO. Check this doc

enter image description here

In addition, we can print the variables via bash cmd printenv and check the variables defined in the script

YAML sample

trigger: none
stages:
- stage: Test
  displayName: Test
  jobs:
  - job: SetSemVer
    displayName: 'Test Var Passing'
    steps:
    - task: PowerShell@2
      displayName: 'Pass Variable'
      name: PassVariable
      inputs:
        targetType: 'inline'
        script: |
          echo "##vso[task.setvariable variable=FOO;isOutput=true]Hello World"
    
    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: 'printenv'
        
    - task: PowerShell@2
      displayName: 'PowerShell Script'
      name: PowerShellTask
      env:
        myVar: $FOO
      inputs:
        targetType: 'inline'
        script: |
          Write-Host "Foo: $($env:PASSVARIABLE_FOO)"

Result:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...