Как назначить группу в качестве пользователей на конечной точке в VSTS через API? - PullRequest
0 голосов
/ 01 июня 2018

Я пытаюсь привести в порядок VSTS и обеспечить согласованность конечных точек AzureRM с нашими более 40 проектами.Я написал скрипт Powershell для вызова остальных API и обеспечения того, чтобы одинаковые конечные точки были доступны для всех проектов.Это прекрасно работает.

Я хочу сделать одну вещь - предоставить группе «Участники» для каждого пользователя права проекта на конечные точки, не являющиеся продуктами.Это не , кажется, работает, и официальная документация ( create или update ) не дает никаких реальных указаний по этому вопросу.

Я могу получить группу и передать ее в качестве «группы читателей» в теле JSON-запроса, а затем это отражается в ответе, подразумевая, что это сработало, но, похоже, это ничего не меняет в самой конечной точке.

Кто-нибудь делал это раньше, кто может дать мне некоторое руководство относительно того, где я иду не так?

[CmdletBinding()]
Param(
    [ValidateSet("Production","NonProduction","RandD")][string]$Environment,
    [string]$SubscriptionName,
    [string]$SubscriptionDisplayName = $SubscriptionName,
    [string]$SubscriptionId,
    [string]$TenantId,
    [string]$ClientId,
    [string]$ClientKey,
    [string]$Token  #Required Scopes: Graph (read), Project and team (read), Service Endpoints (read, query and manage)
)

#Set up Endpoint data
$EndpointDisplayName = "$Environment ($SubscriptionDisplayName)"
$EndpointConfiguration = @"
{
    "data": {
        "SubscriptionId": "$SubscriptionId",
        "SubscriptionName": "$SubscriptionName",
        "creationMode" : "Manual"
    },
    "name": "$EndpointDisplayName",
    "type": "azurerm",
    "url" : "https://management.azure.com/",
    "authorization": {
        "parameters": {
            "serviceprincipalid" : "$ClientId",
            "serviceprincipalkey" : "$ClientKey",
            "tenantid" : "$TenantId"
        },
        "scheme": "ServicePrincipal"
    }
}
"@

#Set up API data
$Authentication = [Text.Encoding]::ASCII.GetBytes(":$Token")
$Authentication = [System.Convert]::ToBase64String($Authentication)
$Headers = @{
    'Authorization' = "Basic $Authentication"
    'Content-Type' = "application/json"
}
$BaseURI = "https://contoso.visualstudio.com"
$APIVersion = "?api-version=4.1-preview.1"

#get all vsts projects
$ListProjectsURI = "$BaseURI/DefaultCollection/_apis/projects$APIVersion"
$ProjectList = (Invoke-RestMethod -Method GET -Uri $ListProjectsURI -Headers $Headers).value

#Get VSTS Contributor groups for "user" role assignment
$ListGroupsURI = "https://Contoso.vssps.visualstudio.com/_apis/graph/groups$APIVersion" 
$GroupsList = (Invoke-RestMethod -Method GET -Uri $ListGroupsURI -Headers $Headers).value
$AllContributorsGroups = $GroupsList | Where-Object -Property principalName -like "*\Contributors"

foreach($Project in $ProjectList)
{
    $ProjectName = $Project.name
    $ProjectId = $Project.id
    #get all AzureRM SP endpoints
    $ListEndpointsURI = "$BaseURI/$ProjectId/_apis/serviceendpoint/endpoints$APIVersion&type=azurerm&authschemes=ServicePrincipal"
    $EndpointList = (Invoke-RestMethod -Method GET -Uri $ListEndpointsURI -Headers $Headers).value
    $Exists = $false

    #set up the endpoint settings for this project
    if($Environment -eq "Production")
    {
        $EndpointJSON = $EndpointConfiguration
    }
    else #grant devs access to use non-prod/R&D endpoints
    {
        Write-Host "Setting [$ProjectName]\Contributors as Users on $EndpointDisplayName in $ProjectName"
        $ReadersGroup = ($AllContributorsGroups | Where-Object -Property principalName -eq "[$ProjectName]\Contributors") | ConvertTo-Json
        $ReadersConfiguration = @"
    ,"readersGroup" : $ReadersGroup
}
"@
        $EndpointJSON = $EndpointConfiguration.TrimEnd('}') + $ReadersConfiguration #Append the readers role for this project to the base configuration
    }

    #Look for existing matching endpoints
    foreach($Endpoint in $EndpointList)
    {
        $EndpointName = $Endpoint.name
        $EndpointId = $Endpoint.id

        #check if it uses the subscription Id we're updating,
        if($Endpoint.data.subscriptionId -eq $SubscriptionId)
        {
            #if so, update it
            Write-Host "Updating endpoint `"$EndpointName`" in Project `"$ProjectName`" (Endpoint ID: $EndpointId)"
            $UpdateEndpointURI = "$BaseURI/$ProjectId/_apis/serviceendpoint/endpoints/$EndpointId$APIVersion"
            Invoke-RestMethod -Method PUT -Uri $UpdateEndpointURI -Headers $Headers -Body $EndpointJSON
            $Exists = $true
        }
    }
    #if no existing endpoints match, create one
    if(!$Exists)
    {
        Write-Output "No endpoint found for $SubscriptionName in `"$ProjectName`". Creating endpoint `"$EndpointDisplayName`"."
        $CreateEndpointURI = "$BaseURI/$ProjectId/_apis/serviceendpoint/endpoints$APIVersion"
        Invoke-RestMethod -Method POST -Uri $CreateEndpointURI -Headers $Headers -Body $EndpointJSON
    }
}

1 Ответ

0 голосов
/ 04 июня 2018

Используя этот API вместо:

Положите

https://{account}.visualstudio.com/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/{project id}_{endpoint id}?api-version=5.0-preview.1

Тело (application / json)

[{"roleName":"User","userId":"{group or user id (originId)"}]
...