Debian Codegraph @

azure_functions_devops_build/service_endpoint/service_endpoint_manager.py

raw
1 # --------------------------------------------------------------------------------------------
2 # Copyright (c) Microsoft Corporation. All rights reserved.
3 # Licensed under the MIT License. See License.txt in the project root for license information.
4 # --------------------------------------------------------------------------------------------
5
6 import json
7 import os
8 try:
9 from subprocess import DEVNULL
10 except ImportError:
11 DEVNULL = open(os.devnull, 'w')
12 from subprocess import check_output, CalledProcessError
13 import vsts.service_endpoint.v4_1.models as models
14 from vsts.exceptions import VstsServiceError
15 from ..base.base_manager import BaseManager
16 from ..constants import SERVICE_ENDPOINT_DOMAIN
17 from ..exceptions import RoleAssignmentException
18
19
20 class ServiceEndpointManager(BaseManager):
21 """ Manage DevOps service endpoints within projects
22
23 Attributes:
24 See BaseManager
25 """
26
27 def __init__(self, organization_name="", project_name="", creds=None):
28 """Inits ServiceEndpointManager as per BaseManager"""
29 super(ServiceEndpointManager, self).__init__(creds, organization_name=organization_name,
30 project_name=project_name)
31
32 # Get the details of a service endpoint
33 # If endpoint does not exist, return an empty list
34 def get_service_endpoints(self, repository_name):
35 service_endpoint_name = self._get_service_endpoint_name(repository_name, "pipeline")
36 try:
37 result = self._service_endpoint_client.get_service_endpoints_by_names(
38 self._project_name,
39 [service_endpoint_name]
40 )
41 except VstsServiceError:
42 return []
43 return result
44
45 # This function requires user permission of Microsoft.Authorization/roleAssignments/write
46 # i.e. only the owner of the subscription can use this function
47 def create_service_endpoint(self, repository_name):
48 """Create a new service endpoint within a project with an associated service principal"""
49 project = self._get_project_by_name(self._project_name)
50
51 command = "az account show --o json"
52 token_resp = check_output(command, shell=True).decode()
53 account = json.loads(token_resp)
54
55 data = {}
56 data["subscriptionId"] = account['id']
57 data["subscriptionName"] = account['name']
58 data["environment"] = "AzureCloud"
59 data["scopeLevel"] = "Subscription"
60
61 # The following command requires Microsoft.Authorization/roleAssignments/write permission
62 service_principle_name = self._get_service_endpoint_name(repository_name, "pipeline")
63
64 # A service principal name has to include the http/https to be valid
65 command = "az ad sp create-for-rbac --o json --name http://" + service_principle_name
66 try:
67 token_resp = check_output(command, stderr=DEVNULL, shell=True).decode()
68 except CalledProcessError:
69 raise RoleAssignmentException(command)
70
71 token_resp_dict = json.loads(token_resp)
72 auth = models.endpoint_authorization.EndpointAuthorization(
73 parameters={
74 "tenantid": token_resp_dict['tenant'],
75 "serviceprincipalid": token_resp_dict['appId'],
76 "authenticationType": "spnKey",
77 "serviceprincipalkey": token_resp_dict['password']
78 },
79 scheme="ServicePrincipal"
80 )
81
82 service_endpoint = models.service_endpoint.ServiceEndpoint(
83 administrators_group=None,
84 authorization=auth,
85 data=data,
86 name=token_resp_dict['displayName'],
87 type="azurerm"
88 )
89 return self._service_endpoint_client.create_service_endpoint(service_endpoint, project.id)
90
91 def list_service_endpoints(self):
92 """List exisiting service endpoints within a project"""
93 project = self._get_project_by_name(self._project_name)
94 return self._service_endpoint_client.get_service_endpoints(project.id)
95
96 def _get_service_endpoint_name(self, repository_name, service_name):
97 return "{domain}/{org}/{proj}/{repo}/{service}".format(
98 domain=SERVICE_ENDPOINT_DOMAIN,
99 org=self._organization_name,
100 proj=self._project_name,
101 repo=repository_name,
102 service=service_name
103 )