Brandon Duque
Brandon Duque

Reputation: 11

how to get the value of a variable stored in a python script from azure pipeline

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?

Upvotes: 1

Views: 1910

Answers (1)

Bright Ran-MSFT
Bright Ran-MSFT

Reputation: 13479

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.

Upvotes: 2

Related Questions