我想向多个Azure管道添加任务,我创建了一个脚本来安装这些任务,但我得到了状态代码:405

wvt8vs2t  于 2023-08-07  发布在  其他
关注(0)|答案(2)|浏览(97)

我的密码

我正在使用我的个人访问令牌,完全访问仍然出错,请告诉我其他可能的方法来实现这一点,以便我可以通过自动化将任务添加到多个Azure管道。

import requests
import base64

# Azure DevOps organization URL
org_url = "https://dev.azure.com/my-org"  # Replace with your organization URL

# Personal access token (PAT) with necessary permissions (Read and Write) for pipelines
pat = "my-pat" 

# Encode the PAT to Base64
credentials = base64.b64encode(f":{pat}".encode()).decode()

# Project name and pipeline ID where you want to add the tasks
project_name = "My Project"
pipeline_id = 12

# Tasks to be added
tasks = [
    {
        "taskReference": {
            "id": "mspremier.PostBuildCleanup.PostBuildCleanup-task.PostBuildCleanup@3",
            "name": "Clean Agent Directories"
        },
        "enabled": True
    },
    {
        "taskReference": {
            "id": "NodeTool@0",
            "name": "Use Node 6.x"
        },
        "enabled": True
    }
]

def update_pipeline_definition():
    url = f"{org_url}/{project_name}/_apis/pipelines/{pipeline_id}?api-version=6.0-preview.1"
    headers = {"Authorization": f"Basic {credentials}", "Content-Type": "application/json"}

    # Get the current pipeline definition
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        pipeline_data = response.json()

        # Modify the pipeline definition to include the tasks
        if "phases" in pipeline_data["configuration"]:
            for phase in pipeline_data["configuration"]["phases"]:
                if "steps" in phase:
                    for task in tasks:
                        phase["steps"].append(task)

        # Update the pipeline definition
        response = requests.put(url, headers=headers, json=pipeline_data)

        if response.status_code == 200:
            print(f"Tasks added to pipeline {pipeline_id} successfully.")
        else:
            print(f"Failed to update pipeline {pipeline_id}. Status code: {response.status_code}")
            print(response.text)
    else:
        print(f"Failed to get pipeline {pipeline_id}. Status code: {response.status_code}")
        print(response.text)

if __name__ == "__main__":
    update_pipeline_definition()

字符串
下面的错误我得到:

Failed to update pipeline 42. Status code: 405
{"count":1,"value":{"Message":"The requested resource does not support http method 'PUT'."}}


它应该更新/添加任务到多个Azure管道,告诉我其他可能的方法来自动化。

dgsult0t

dgsult0t1#

我试着对你的代码做了一些修改,并通过更新它的任务来运行管道,但是只有管道运行,任务没有被更新为步骤,作业和经典的管道阶段,Python中不支持步骤。
在现有代码中,将put替换为post,或者使用以下修改后的代码,该代码运行管道,但无法创建任务,因为它不受支持,如上所述。

我修改的编码:-

import requests
from requests.auth import HTTPBasicAuth

# Replace with your Azure DevOps organization URL
organization_url = "https://dev.azure.com/org-name"

# Replace with your Personal Access Token
personal_access_token = "xxxxxj4gskzhnjunhtxdpdfi3kaygq2a"

# Replace with your project name and pipeline ID
project_name = "devopsprojectname"
pipeline_id = 122

# Task definition for the sample task
new_task = {
    "task": {
        "id": "CmdLine",              # ID of the task type (CmdLine is a simple command line task)
        "versionSpec": "2.*",         # Task version (2.* is the latest version)
        "inputs": {
            "script": "echo Hello",   # Sample command to be executed by the task
        }
    }
}

# URL to create a new version of the pipeline
api_url = f"{organization_url}/{project_name}/_apis/pipelines/{pipeline_id}/runs?api-version=6.0-preview.1"

headers = {
    "Content-Type": "application/json",
}

auth = HTTPBasicAuth("", personal_access_token)

response = requests.post(api_url, json={}, headers=headers, auth=auth)

if response.status_code == 202:
    run_id = response.json()["id"]

    # Get the run details to modify the new pipeline
    api_url = f"{organization_url}/{project_name}/_apis/pipelines/{pipeline_id}/runs/{run_id}?api-version=6.0-preview.1"
    response = requests.get(api_url, headers=headers, auth=auth)

    if response.status_code == 200:
        pipeline_run = response.json()

        # Add the new task definition to the existing tasks in the new pipeline version
        pipeline_run["phases"][0]["steps"].append(new_task)

        # Update the pipeline run with the modified definition
        response = requests.patch(api_url, json=pipeline_run, headers=headers, auth=auth)

        if response.status_code == 200:
            print("Task added successfully to the pipeline.")
        else:
            print(f"Failed to add task to the new pipeline. Status code: {response.status_code}, Error: {response.text}")
    else:
        print(f"Failed to get pipeline run details. Status code: {response.status_code}, Error: {response.text}")
else:
    print(f"Failed to create a new version of the pipeline. Status code: {response.status_code}, Error: {response.text}")

字符串

管道运行但任务失败:-

x1c 0d1x的数据

推荐的方法是升级Azure存储库中的YAML文件内容,然后使用下面的代码触发Python管道,如下所示:-
Python代码:-

import requests
from requests.auth import HTTPBasicAuth

# Replace with your Azure DevOps organization URL
organization_url = "https://dev.azure.com/org-name"

# Replace with your Personal Access Token
personal_access_token = "xxxxixxxhtxdpdfi3kaygq2a"

# Replace with your project name and pipeline ID
project_name = "devopsprojectname"
pipeline_id = 122

# URL to trigger a new pipeline run
api_url = f"{organization_url}/{project_name}/_apis/pipelines/{pipeline_id}/runs?api-version=7.1-preview"

headers = {
    "Content-Type": "application/json",
}

auth = HTTPBasicAuth("", personal_access_token)

# Trigger a new pipeline run
response = requests.post(api_url, json={}, headers=headers, auth=auth)

if response.status_code == 200:
    print("Pipeline run triggered successfully.")
else:
    print(f"Failed to trigger the pipeline run. Status code: {response.status_code}, Error: {response.text}")

输出:-



eoxn13cs

eoxn13cs2#

你能检查端点方法是否正确吗,因为405状态码意味着“方法是允许注解的”(在这种情况下是PUT)

相关问题