Search code examples
pythonazure-devopsazure-pipelinesazure-pipelines-yaml

Trying to pass prompt value into the code in Azure DevOps (python)


I am trying to get userStory value from user while running build pipeline in Azure DevOps. I want to use that value as a variable into the python script that I am building. I tried below code with yaml, Also attached is the error.

trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

parameters:
  - name: UserStory
    displayName: Enter User Story ID.
    type: string
    default: ''

steps:
- task: UsePythonVersion@0
  inputs:
    versionSpec: '3.x'
    addToPath: true
  
- script: |
    echo "Running p1.py with User Story ID ${UserStory}"
    export USER_STORY_ID=${UserStory}
    python p1.py
  displayName: 'Run p1.py'

p1.py

import os

print('Hello, world!')
user_story2 = os.getenv('USER_STORY_ID')
print(user_story2)

Error:

    ========================== Starting Command Output ===========================
/usr/bin/bash --noprofile --norc /home/vsts/work/_temp/e91b2e42-ada0-4108-aa1f-8bb3b4b6d4a3.sh
Running p1.py with User Story ID 
Hello, world!

Solution

  • The right syntax to use a parameter is ${{ parameters.xxx }}:

    - script: |
        echo "Running p1.py with User Story ID ${{ parameters.UserStory }}"
        export USER_STORY_ID=${{ parameters.UserStory }}
        python p1.py
      displayName: 'Run p1.py'
    

    Also, you don't need to set the environment variable in the script body using the export command.

    Set an environment variable at the task level instead:

    - script: |
        echo "Running p1.py with User Story ID ${{ parameters.UserStory }}"
        python p1.py
      displayName: 'Run p1.py'
      env:
       USER_STORY_ID: ${{ parameters.UserStory }}