如何将参数从Azure Pipeline传递给Python脚本?

0 投票
1 回答
73 浏览
提问于 2025-04-13 16:11

我想为一些Azure DevOps管道变量创建一个用户输入,并在Python脚本中获取这些变量。

下面是我的yml文件

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

这是我的Python脚本

import requests
import json
import os


Action123 = os.getenv('Action123')

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

我不太确定哪里出错了,尝试了很多次,但变量Action123的值总是为空。

奇怪的是,如果我这样做

print(os.environ) 

它会返回

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

你能告诉我哪里出错了吗?

谢谢

1 个回答

1

通过 os.getenv() 来获取DevOps变量的值在Python脚本中是正确的做法。

因为你使用的是自托管的代理池,如果变量Action123的值为空,你可以在yaml文件中明确地定义这个变量,以确保它有值。

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

我的输出:

在这里输入图片描述

撰写回答