Access variables from Variable Groups inside Python script task in Azure DevOps Yaml pipeline

10k Views Asked by At

I'm using a Python script task of type 'file' in my Azure DevOps Yaml pipeline. I need to use the variables that I defined in my Variable Group in the Python file. The following is my task on Azure devops yaml pipeline.

  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptPath: 'pythonTest.py'

Any advise on how I can achieve this?

Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

You need to pass the variables to the script, using arguments, and you of course need to reference the variable group:

variables:
- group: variableGroup

steps:
  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptPath: 'pythonTest.py'
      arguments: --variableInScript $(variableInVariableGroup)

And then use 'argparse' in the script.

https://learn.microsoft.com/en-us/azure/devops/pipelines/ecosystems/python?view=azure-devops#run-python-scripts

If you were using an inline script you could have done it like this:

- task: PythonScript@0
  inputs:
    scriptSource: 'inline'
    script: |
      print('variableInVariableGroup: $(variableInVariableGroup)')
0
On

According to the Azure DevOps official documentation:

System and user-defined variables also get injected as environment variables for your platform. When variables are turned into environment variables, variable names become uppercase, and periods turn into underscores. For example, the variable name any.variable becomes the variable name $ANY_VARIABLE.

So you just have to access the corresponding environment variable from your script. In Python, this can be done using the os.environ dictionary:

import os

my_var = os.environ["MY_VAR"]