首页 > 解决方案 > 如何使用它的 python 客户端 API 将用户添加到 Azure DevOps?

问题描述

我正在编写一个 python 脚本来将用户(来自 AAD 支持的提供程序的现有用户)添加到 Azure DevOps。为此,我正在使用 Azure DevOps 的 python 客户端库。身份验证后,我可以从 azure devops 获取用户:

# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)

# Get a client (the "graph" client provides access to list,get and create user)
graph_client = connection.clients_v5_0.get_graph_client()
resp = graph_client.list_users()

# Access the properties of object as object.property
users = resp.graph_users

# Show details about each user in the console
for user in users:
    pprint.pprint(user.__dict__)
    print("\n")

如何使用此 GraphClient 连接添加用户?

这里有一个 create_user 函数(用作graph_client.create_user())来执行此操作:https://github.com/microsoft/azure-devops-python-api/blob/dev/azure-devops/azure/devops/v5_0/graph/graph_client。 py

它说请求应该包含一个 GraphUserCreationContext 作为输入参数。

但是我怎样才能为 AAD 用户获取 GraphUserCreationContext 呢?我只有关于 AAD 用户的 UPN 的信息作为输入。

笔记:

我在这里找到了 .NET 示例:https ://github.com/microsoft/azure-devops-dotnet-samples/blob/master/ClientLibrary/Samples/Graph/UsersSample.cs

它使用 GraphUserPrincipalNameCreationContext 扩展 GraphUserCreationContext。

但是我在 python 客户端库中找不到这样的类。我使用这样的代码:

addAADUserContext = GraphUserCreationContext('anaya.john@domain.com')
print(addAADUserContext)
resp = graph_client.create_user(addAADUserContext)
print(resp) 

但出现错误:

azure.devops.exceptions.AzureDevOpsServiceError: VS860015: Must have exactly one of originId or principalName set.

标签: pythonapiazure-devopsclientazure-devops-rest-api

解决方案


GraphUserCreationContext来自用于 azure devops REST API 的 python 客户端的类仅接受一个输入参数,即StorageKey. 因此,无论您提供什么作为该函数的输入参数,无论是 UPN 还是 ID,它都会被设置为存储密钥。

如果打印addAADUserContext对象,您将获得:

{'additional_properties': {}, 'storage_key': 'anaya.john@domain.com'}

但是 Graph 客户端的功能恰好需要它作为输入参数create_user()设置的 originId 或 principalName 之一。GraphUserCreationContext

作为 azure devops REST API 的微软文档(https://docs.microsoft.com/en-us/rest/api/azure/devops/graph/users/create?view=azure-devops-rest-4.1):

请求的主体必须是 GraphUserCreationContext 的派生类型:

  • GraphUserMailAddressCreationContext
  • GraphUserOriginIdCreationContext
  • GraphUserPrincipalNameCreationContext

我们不应该GraphUserCreationContext直接使用该对象。但是像 GraphUserPrincipalNameCreationContext 这样的类目前在 python 客户端 API 中不可用。他们正在努力。您可以在 GitHub 存储库中跟踪问题:https ://github.com/microsoft/azure-devops-python-api/issues/176

您可以使用 User Entitlements - Add REST API for azure devops 而不是它的 Graph API。为此,您可以使用以下 python 客户端:

https://github.com/microsoft/azure-devops-python-api/tree/dev/azure-devops/azure/devops/v5_0/member_entitlement_management

您可以参考以下问题中给出的示例以了解如何使用上述 python 客户端:

无法反序列化为对象:类型,KeyError:'键:int;值:str'


推荐阅读