2

Currently, I am faced with the need to run a pipeline on an azure VM, I am using a python script to run a process in which I store the ID in a variable, and I need to use that variable value in the code yaml from the pipeline to use as a parameter, does anyone know how I can proceed?

1
  • Please provide enough code so others can better understand or reproduce the problem. Commented Jan 4, 2022 at 22:02

1 Answer 1

3

In your Python script, you can set an output variable with the value you want to pass so that it can be access in the subsequent steps in the pipeline.

  1. In the Python script, use the logging command 'SetVariable' to set an output variable with the value you want. And use the Python Script task to run the script.

  2. In the subsequent steps of the same pipeline job, you can use the expression '$({taskName}.{variableName})' to access the output variable.

Below is an example YAML pipeline as reference.

jobs:
- job: job1
  displayName: 'Job 1'
  pool:
    vmImage: ubuntu-latest
  steps:
  - task: PythonScript@0
    name: pythScr
    displayName: 'Set output variable'
    inputs:
      scriptSource: inline
      script: |
        import subprocess
        myID = 123
        subprocess.Popen(["echo", "##vso[task.setvariable variable=MY_ID;isoutput=true]{0}".format(myID)])
  
  - task: Bash@3
    displayName: 'Print output variable'
    inputs:
      targetType: inline
      script: echo "MY_ID = $(pythScr.MY_ID)"

Result. enter image description here

[UPDATE]

You also can put the same script into a Python script file, then call this script file on the Python Script task.

enter image description here

jobs:
- job: job1
  displayName: 'Job 1'
  pool:
    vmImage: ubuntu-latest
  steps:
  - task: PythonScript@0
    name: pythScr
    displayName: 'Set output variable'
    inputs:
      scriptSource: filePath
      scriptPath: 'PythonScript/output-variable.py'
  
  - task: Bash@3
    displayName: 'Print output variable'
    inputs:
      targetType: inline
      script: echo "MY_ID = $(pythScr.MY_ID)"

And you will get the same result like as above example.

Sign up to request clarification or add additional context in comments.

3 Comments

I am understanding what you say, but I am handling it is directly a python file (.py) and from that file pass the variable to the pipeline. It would be the same?
Hi @BrandonDuque, Sure. Putting the same script into a Python script file (.py) also can get the same result. I have updated my answer with more details, please check it.
@Bright Ran-MSFT this is beautiful! Thank you!! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.