Search code examples
pythonazureazure-devopsazure-pipelines

How to Pass Parameter from Azure Pipeline to Python Script?


I want to create an user Input for some Azure DevOps pipeline variable and get those variable in the Python script.

Below is my yml file

parameters:
- name: Action123
  displayName: 'Select Action'
  type: string
  default: 'enable'
  values:
  - 'enable'
  - 'disable'

trigger: none
stages:
- stage: Create
  pool: 
   name: sdasdasd
   demands:
    - agent.name -equals sdasdasd
  jobs:
  - job: BuildJob
    steps:
    - script: echo Building!
    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          export Action123=$(Action123)
          python job/job-action.py

    - task: Bash@3
      inputs:
        targetType: 'inline'
        script: |
          echo 'Action123 Taken =========>>>' + $(Action123)
      displayName: Summary for Dev Action Utility

And here is my python script

import requests
import json
import os


Action123 = os.getenv('Action123')

print("Action123 ===========>>> " + Action123) #This is not getting printed

I am not sure where I am getting it wrong, tried multiple time but the Variable Action123 Is Coming as empty.

Strange thing is if I do

print(os.environ) 

it's giving

{'otherdields & value,
 'Action123': 'enable', 
 'otherdields & value}

Can you please correct me where its getting wrong

Thanks


Solution

  • The way to get the DevOps variable value to python script by os.getenv() is correct.

    Since you are using self-hosted agent pool, and Variable Action123 gets empty, you can define it explictly in the yaml, to make sure the value is given.

    parameters:
    - name: Action123
      displayName: 'Select Action'
      type: string
      default: 'enable'
      values:
      - 'enable'
      - 'disable'
    
    variables:
      - name: Action123              # define the variable to make sure it has the value.
        value: ${{ parameters.Action123 }}
    
    trigger: none
    
    stages:
    - stage: Create
      jobs:
      - job: BuildJob
        steps:
        - script: echo Building!
        - task: Bash@3
          inputs:
            targetType: 'inline'
            script: |
              export Action123=$(Action123)
              python job/job-action.py
    
        - task: Bash@3
          inputs:
            targetType: 'inline'
            script: |
              echo 'Action123 Taken =========>>>' + $(Action123)
          displayName: Summary for Dev Action Utility
    

    My output:

    enter image description here