如何使用python脚本、API向Azure管道传递参数

mpbci0fu  于 2023-03-03  发布在  Python
关注(0)|答案(1)|浏览(165)

我在Python中有一个脚本,它使用API触发管道构建。我需要弄清楚如何将参数传递给此管道。
以下脚本运行id为3023的pipeline,并返回状态200:

def run_pipeline(PAT):
    url="[organization_url]_apis/pipelines/[pipeline_id]/runs?api-version=6.0-preview.1"
    headers = {"Content-Type": "application/json; charset=utf-8"}
    data={
        'id': '3023'
        }
    request_run_pipeline = requests.post(url, headers=headers, json=data, auth = ('',PAT),verify = False)

    return(print(request_run_pipeline.status_code))

现在,我的测试管道与参数如下所示:

parameters:
  - name: text
    type: string
    default: test pipeline

trigger:
      branches:
        include:
        - main

steps:
  - script: echo ${{ parameters.text }}
    displayName: 'run one-line script - write text'

我需要用我的python脚本传递这个“text”参数,不知道怎么做。

u5rb5r59

u5rb5r591#

我用你的yaml脚本创建了一个Azure DevOps管道,如下所示:-

- main

  

pool:

vmImage: ubuntu-latest

  

parameters:

- name: text

type: string

default: test pipeline

  

steps:

- script: echo Hello, world!

displayName: 'Run a one-line script'

  

- script: |

echo Add other tasks to build, test, and deploy your project.

echo See https://aka.ms/yaml

displayName: 'Run a multi-line script'

- script: echo ${{ parameters.text }}

displayName:'run one-line script - write text'
    • 输出:-**

我尝试了下面的python代码,通过传递如下文本参数来触发管道:-

import  json

import  requests

  

def  run_pipeline(PAT, project_name, pipeline_id, parameter_value):

url = f"https://dev.azure.com/organization-name/{project_name}/_apis/pipelines/{pipeline_id}/runs?api-version=6.0-preview.1"

headers = {"Content-Type": "application/json; charset=utf-8"}

data = {

"templateParameters": json.dumps({"text": parameter_value}),

"pipelineId": pipeline_id

}

request_run_pipeline = requests.post(url, headers=headers, json=data, auth=('', PAT), verify=False)

return  request_run_pipeline.status_code

  

# Example usage

PAT = "<pat-token>"

project_name = "<project-name>"

pipeline_id = "22"

parameter_value = "test pipeline"

  

run_pipeline(PAT, project_name, pipeline_id, parameter_value)

代码成功运行,管道触发如下:-

    • 输出:-**

相关问题