Пример #1
0
def get_kubernetes_namespace(organization, project, cluster, subscription_id,
                             subscription_name, tenant_id, azure_env):
    choice_list = []
    existing_namespace_list = []
    choice_list.append("Create new")
    se_request_obj = get_se_kubernetes_namespace_request_obj(
        subscription_id, subscription_name, cluster['id'], cluster['name'],
        cluster['fqdn'], azure_env, tenant_id)
    se_client = get_service_endpoint_client(organization=organization)
    se_result = se_client.execute_service_endpoint_request(
        service_endpoint_request=se_request_obj,
        project=project,
        endpoint_id=cluster['name'])
    if se_result.result:
        import json
        for namespace in se_result.result:
            ns_json_obj = json.loads(namespace)
            existing_namespace_list.append(ns_json_obj['Value'])
            choice_list.append(ns_json_obj['Value'])
    choice = prompt_user_friendly_choice_list(
        "Which kubernetes namespace do you want to target?", choice_list)
    if choice == 0:
        create_namespace = True
        namespace = prompt_not_empty(
            "Enter a name for new namespace to create: ")
        print('')
    else:
        create_namespace = False
        namespace = existing_namespace_list[choice - 1]
    return create_namespace, namespace
def update_service_endpoint(
        id,
        enable_for_all=None,
        organization=None,  # pylint: disable=redefined-builtin
        project=None,
        detect=None):
    """Update a service endpoint
    :param id: ID of the service endpoint.
    :type id: str
    """
    if enable_for_all is None:
        raise CLIError('Atleast one property to be updated must be specified.')
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)
    se = client.get_service_endpoint_details(project, id)

    # set authorization if get service endpoint succeeded
    from azext_devops.dev.pipelines.pipeline_utils import set_authorize_resource, get_authorize_resource
    set_authorize_resource(authorized=enable_for_all,
                           res_id=se.id,
                           name=se.name,
                           res_type='endpoint',
                           organization=organization,
                           project=project)

    authorized = get_authorize_resource(res_id=se.id,
                                        res_type='endpoint',
                                        organization=organization,
                                        project=project)
    return ServiceEndpointAuthorized(service_endpoint_parameters=se,
                                     authorized=authorized)
Пример #3
0
def create_github_service_endpoint(name,
                                   github_url,
                                   organization=None,
                                   project=None,
                                   detect=None):
    """ Create a GitHub service endpoint.
    :param name: Name of service endpoint to create
    :type name: str
    :param github_url: Url for github for creating service endpoint
    :type github_url: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)
    if AZ_DEVOPS_GITHUB_PAT_ENVKEY not in os.environ:
        error_message = 'Please pass GitHub access token in ' + AZ_DEVOPS_GITHUB_PAT_ENVKEY +\
                        ' environment variable in non-interactive mode.'
        verify_is_a_tty_or_raise_error(error_message)
        github_access_token = prompt_pass('GitHub access token:', confirm=True)
    else:
        logger.debug('Picking GitHub PAT from environment variable')
        github_access_token = os.environ[AZ_DEVOPS_GITHUB_PAT_ENVKEY]

    service_endpoint_authorization = EndpointAuthorization(
        parameters={'accessToken': github_access_token},
        scheme=SERVICE_ENDPOINT_AUTHORIZATION_PERSONAL_ACCESS_TOKEN)
    service_endpoint_to_create = ServiceEndpoint(
        authorization=service_endpoint_authorization,
        name=name,
        type=SERVICE_ENDPOINT_TYPE_GITHUB,
        url=github_url)
    return client.create_service_endpoint(service_endpoint_to_create, project)
def list_service_endpoints(organization=None, project=None, detect=None):
    """List service endpoints in a project.
    :rtype: list of :class:`VssJsonCollectionWrapper <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)
    return client.get_service_endpoints(project)
def show_service_endpoint(id, organization=None, project=None, detect=None):  # pylint: disable=redefined-builtin
    """Get the details of a service endpoint.
    :param id: ID of the service endpoint.
    :type id: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)
    return client.get_service_endpoint_details(project, id)
Пример #6
0
def _get_service_endpoints(organization, project, endpoint_type=None):
    """
    Get the list of existing service connections filtered by type if mentioned
    """
    client = get_service_endpoint_client(organization)
    all_connections = client.get_service_endpoints(project)
    if endpoint_type is None:
        return all_connections
    filtered_connection = []
    for connection in all_connections:
        if connection.type.lower() == endpoint_type.lower():
            filtered_connection.append(connection)
    return filtered_connection
def poll_connection_ready(organization, project, connection_id):
    import colorama
    import humanfriendly
    import time
    colorama.init()
    with humanfriendly.Spinner(label="Checking resource readiness") as spinner:
        se_client = get_service_endpoint_client(organization)
        while True:
            spinner.step()
            time.sleep(0.5)
            service_endpoint = se_client.get_service_endpoint_details(
                project, connection_id)
            if service_endpoint.is_ready:
                break
Пример #8
0
def delete_service_endpoint(id,
                            deep=False,
                            organization=None,
                            project=None,
                            detect=None):  # pylint: disable=redefined-builtin
    """Deletes service endpoint
    :param id: Id of the service endpoint to delete.
    :type id: str
    :param deep: Specific to AzureRM endpoint created in Automatic flow. When it is specified,
    this will also delete corresponding AAD application in Azure.
    :type deep: bool
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)
    return client.delete_service_endpoint(project, id, deep)
def list_service_endpoints(organization=None, project=None, detect=None):
    """List service endpoints in a project.
    :param organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :type organization: str
    :param project: Name or ID of the project.
    :type project: str
    :param detect: Automatically detect organization. Default is "on".
    :type detect: str
    :rtype: list of :class:`VssJsonCollectionWrapper <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    try:
        organization, project = resolve_instance_and_project(
            detect=detect, organization=organization, project=project)
        client = get_service_endpoint_client(organization)
        return client.get_service_endpoints(project)

    except VstsServiceError as ex:
        raise CLIError(ex)
Пример #10
0
def get_github_service_endpoint(organization, project):
    """
    This will try to create a GitHub service connection if there is no existing one in the project
    GitHub pat token will be asked for interactively or can be provided
    by setting the Environment variable AZ_DEVOPS_GITHUB_PAT_ENVKEY.
    Service endpoint connection name is asked as input from the user
    """
    from azext_devops.dev.common.identities import get_current_identity, get_account_from_identity
    authenticated_user_unique_id = get_account_from_identity(
        get_current_identity(organization))
    se_client = get_service_endpoint_client(organization)
    existing_service_endpoints = _get_service_endpoints(
        organization, project, 'github')
    service_endpoints_choice_list = ['Create new GitHub service connection']
    github_service_endpoints = []
    choice = 0
    for endpoint in existing_service_endpoints:
        if (endpoint.authorization.scheme == 'InstallationToken'
                or authenticated_user_unique_id
                == endpoint.created_by.unique_name):
            service_endpoints_choice_list.append('{}'.format(endpoint.name))
            github_service_endpoints.append(endpoint)
    if github_service_endpoints:
        choice = prompt_user_friendly_choice_list(
            "Which service connection do you want to use to communicate with GitHub?",
            service_endpoints_choice_list)
        if choice > 0:
            logger.debug('Using service endpoint index (%s) name (%s)', choice,
                         github_service_endpoints[choice - 1].name)
            return github_service_endpoints[choice - 1].id
    logger.debug("Creating a new service endpoint.")
    github_pat = get_github_pat_token()
    se_name = prompt_not_empty('Enter a service connection name to create? ')
    print('')
    service_endpoint_authorization = EndpointAuthorization(
        parameters={'accessToken': github_pat}, scheme='PersonalAccessToken')
    service_endpoint_to_create = ServiceEndpoint(
        authorization=service_endpoint_authorization,
        name=se_name,
        type='github',
        url='https://github.com/')
    return se_client.create_service_endpoint(service_endpoint_to_create,
                                             project).id
def show_service_endpoint(id, organization=None, project=None, detect=None):  # pylint: disable=redefined-builtin
    """Get the details of a service endpoint.
    :param id: ID of the service endpoint.
    :type id: str
    :param organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :type organization: str
    :param project: Name or ID of the project.
    :type project: str
    :param detect: Automatically detect organization. Default is "on".
    :type detect: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    try:
        organization, project = resolve_instance_and_project(
            detect=detect, organization=organization, project=project)
        client = get_service_endpoint_client(organization)
        return client.get_service_endpoint_details(project, id)

    except VstsServiceError as ex:
        raise CLIError(ex)
Пример #12
0
def create_service_endpoint(service_endpoint_configuration,
                            encoding='utf-8',
                            organization=None,
                            project=None,
                            detect=None):
    """Create a service endpoint using configuration file.
    :param name: Name of service endpoint to create
    :type name: str
    :param service_endpoint_configuration: Configuration file with service endpoint request.
    :type service_endpoint_configuration: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)
    from azext_devops.dev.common.utils import read_file_content
    in_file_content = read_file_content(
        file_path=service_endpoint_configuration, encoding=encoding)
    import json
    service_endpoint_to_create = json.loads(in_file_content)
    return client.create_service_endpoint(service_endpoint_to_create, project)
Пример #13
0
def create_import_request(git_source_url, project=None, repository=None,
                          requires_authorization=False,
                          user_name=None,
                          git_service_endpoint_id=None,
                          organization=None, detect=None):
    """Create a git import request
    :param repository: Name or ID of the repository to create the import request in.
    :type repository: str
    :param git_source_url: Url of the source git repository.
    :type git_source_url: str
    :param requires_authorization: Flag to tell if source git repository is private.
    :type requires_authorization: bool
    :param user_name: User name in case source git repository is private.
    :type user_name: str
    :param git_service_endpoint_id: Service Endpoint for connection to external endpoint.
    :type git_service_endpoint_id: str
    """
    organization, project, repository = resolve_instance_project_and_repo(
        detect=detect,
        organization=organization,
        project=project,
        repo=repository,
        repo_required=True)

    delete_se_after_import = False

    password = None
    import random
    import string
    import os
    if requires_authorization and git_service_endpoint_id is None:
        delete_se_after_import = True
        if GIT_SOURCE_PASSWORD_OR_PAT in os.environ:
            password = os.environ[GIT_SOURCE_PASSWORD_OR_PAT]
        else:
            error_message = 'Please specify target git password / PAT in ' + GIT_SOURCE_PASSWORD_OR_PAT +\
                            ' environment variable in non-interactive mode.'
            verify_is_a_tty_or_raise_error(error_message)
            password = prompt_pass('Git Password / PAT:', confirm=True)

        service_endpoint_authorization = EndpointAuthorization(
            parameters={'password': password, 'username': user_name},
            scheme='UsernamePassword')
        service_endpoint_to_create = ServiceEndpoint(
            authorization=service_endpoint_authorization,
            name=''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)),
            type='git',
            url=git_source_url)
        client = get_service_endpoint_client(organization)
        se_created = client.create_service_endpoint(service_endpoint_to_create, project)
        git_service_endpoint_id = se_created.id

    client = get_git_client(organization)
    gitImportGitSource = GitImportGitSource(overwrite=False, url=git_source_url)
    gitImportRequestParameter = GitImportRequestParameters(
        delete_service_endpoint_after_import_is_done=delete_se_after_import,
        git_source=gitImportGitSource,
        service_endpoint_id=git_service_endpoint_id,
        tfvc_source=None)
    gitImportRequest = GitImportRequest(parameters=gitImportRequestParameter)
    importRequest = client.create_import_request(import_request=gitImportRequest, project=project,
                                                 repository_id=repository)
    return _wait_for_import_request(client, project, repository, importRequest.import_request_id)
def create_service_endpoint(service_endpoint_type,
                            authorization_scheme,
                            name,
                            github_access_token=None,
                            github_url=None,
                            azure_rm_tenant_id=None,
                            azure_rm_service_principal_id=None,
                            azure_rm_service_principal_key=None,
                            azure_rm_subscription_id=None,
                            azure_rm_subscription_name=None,
                            organization=None,
                            project=None,
                            detect=None):
    """Create a service endpoint
    :param service_endpoint_type: Type of service endpoint
    :type service_endpoint_type: str
    :param name: Name of service endpoint to create
    :type name: str
    :param authorization_scheme: Authorization to be used in service endpoint creation
     Github service endpoint supports PersonalAccessToken
     AzureRm service endpoint supports ServicePrincipal
    :type authorization_scheme: str
    :param github_access_token: PAT token of github for creating github service endpoint
    :type github_access_token: str
    :param github_url: Url for github for creating service endpoint
    :type github_url: str
    :param azure_rm_tenant_id: tenant id for creating azure rm service endpoint
    :type azure_rm_tenant_id: str
    :param azure_rm_service_principal_id: service principal id for creating azure rm service endpoint
    :type azure_rm_service_principal_id: str
    :param azure_rm_service_principal_key: key/password for service principal used to create azure rm service endpoint
    :type azure_rm_service_principal_key: str
    :param azure_rm_subscription_id: subscription id for azure rm service endpoint
    :type azure_rm_subscription_id: str
    :param azure_rm_subscription_name: name of azure subscription for azure rm service endpoint
    :type azure_rm_subscription_name: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)

    if (service_endpoint_type == SERVICE_ENDPOINT_TYPE_GITHUB
            and authorization_scheme
            == SERVICE_ENDPOINT_AUTHORIZATION_PERSONAL_ACCESS_TOKEN):
        if not github_access_token:
            try:
                github_access_token = prompt_pass('GitHub access token:',
                                                  confirm=True)
            except NoTTYException:
                raise CLIError(
                    'Please specify --github-access-token in non-interactive mode.'
                )

        service_endpoint_authorization = EndpointAuthorization(
            parameters={'accessToken': github_access_token},
            scheme=SERVICE_ENDPOINT_AUTHORIZATION_PERSONAL_ACCESS_TOKEN)
        service_endpoint_to_create = ServiceEndpoint(
            authorization=service_endpoint_authorization,
            name=name,
            type=SERVICE_ENDPOINT_TYPE_GITHUB,
            url=github_url)
        return client.create_service_endpoint(service_endpoint_to_create,
                                              project)

    if (service_endpoint_type == SERVICE_ENDPOINT_TYPE_AZURE_RM
            and authorization_scheme
            == SERVICE_ENDPOINT_AUTHORIZATION_SERVICE_PRINCIPAL):
        if not azure_rm_service_principal_key:
            try:
                azure_rm_service_principal_key = prompt_pass(
                    'Azure RM service principal key:', confirm=True)
            except NoTTYException:
                raise CLIError(
                    'Please specify --azure-rm-service-principal-key in non-interactive mode.'
                )
        service_endpoint_authorization = EndpointAuthorization(
            parameters={
                'tenantid': azure_rm_tenant_id,
                'serviceprincipalid': azure_rm_service_principal_id,
                'authenticationType': 'spnKey',
                'serviceprincipalkey': azure_rm_service_principal_key
            },
            scheme=SERVICE_ENDPOINT_AUTHORIZATION_SERVICE_PRINCIPAL)
        service_endpoint_data = {
            'subscriptionId': azure_rm_subscription_id,
            'subscriptionName': azure_rm_subscription_name,
            'environment': 'AzureCloud',
            'creationMode': 'Manual'
        }
        service_endpoint_to_create = ServiceEndpoint(
            authorization=service_endpoint_authorization,
            data=service_endpoint_data,
            name=name,
            type=SERVICE_ENDPOINT_TYPE_AZURE_RM,
            url='https://management.azure.com/')
        return client.create_service_endpoint(service_endpoint_to_create,
                                              project)

    raise CLIError(
        'This combination of endpoint type is not supported with this authorization scheme.'
    )
def create_service_endpoint(service_endpoint_type,
                            authorization_scheme,
                            name,
                            github_access_token=None,
                            github_url=None,
                            azure_rm_tenant_id=None,
                            azure_rm_service_principal_id=None,
                            azure_rm_service_prinicipal_key=None,
                            azure_rm_subscription_id=None,
                            azure_rm_subscription_name=None,
                            organization=None,
                            project=None,
                            detect=None):
    """Create a service endpoint
    :param service_endpoint_type: Type of service endpoint
    :type service_endpoint_type: str
    :param name: Name of service endpoint to create
    :type name: str
    :param authorization_scheme: Authorization to be used in service endpoint creation
     Github service endpoint supports PersonalAccessToken
     AzureRm service endpoint supports ServicePrincipal
    :type authorization_scheme: str
    :param github_access_token: PAT token of github for creating github service endpoint
    :type github_access_token: str
    :param github_url: Url for github for creating service endpoint
    :type github_url: str
    :param azure_rm_tenant_id: tenant id for creating azure rm service endpoint
    :type azure_rm_tenant_id: str
    :param azure_rm_service_principal_id: service principal id for creating azure rm service endpoint
    :type azure_rm_service_principal_id: str
    :param azure_rm_service_prinicipal_key: key/password for service principal used to create azure rm service endpoint
    :type azure_rm_service_prinicipal_key: str
    :param azure_rm_subscription_id: subscription id for azure rm service endpoint
    :type azure_rm_subscription_id: str
    :param azure_rm_subscription_name: name of azure subscription for azure rm service endpoint
    :type azure_rm_subscription_name: str
    :param organization: Azure Devops organization URL. Example: https://dev.azure.com/MyOrganizationName/
    :type organization: str
    :param project: Name or ID of the project.
    :type project: str
    :param detect: Automatically detect organization. Default is "on".
    :type detect: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    try:
        organization, project = resolve_instance_and_project(
            detect=detect, organization=organization, project=project)
        client = get_service_endpoint_client(organization)

        if (service_endpoint_type == SERVICE_ENDPOINT_TYPE_GITHUB
                and authorization_scheme
                == SERVICE_ENDPOINT_AUTHORIZATION_PERSONAL_ACCESS_TOKEN):
            service_endpoint_authorization = EndpointAuthorization(
                parameters={'accessToken': github_access_token},
                scheme=SERVICE_ENDPOINT_AUTHORIZATION_PERSONAL_ACCESS_TOKEN)
            service_endpoint_to_create = ServiceEndpoint(
                authorization=service_endpoint_authorization,
                name=name,
                type=SERVICE_ENDPOINT_TYPE_GITHUB,
                url=github_url)
            return client.create_service_endpoint(service_endpoint_to_create,
                                                  project)

        if (service_endpoint_type == SERVICE_ENDPOINT_TYPE_AZURE_RM
                and authorization_scheme
                == SERVICE_ENDPOINT_AUTHORIZATION_SERVICE_PRINCIPAL):
            service_endpoint_authorization = EndpointAuthorization(
                parameters={
                    'tenantid': azure_rm_tenant_id,
                    'serviceprincipalid': azure_rm_service_principal_id,
                    'authenticationType': 'spnKey',
                    'serviceprincipalkey': azure_rm_service_prinicipal_key
                },
                scheme=SERVICE_ENDPOINT_AUTHORIZATION_SERVICE_PRINCIPAL)
            service_endpoint_data = {
                'subscriptionId': azure_rm_subscription_id,
                'subscriptionName': azure_rm_subscription_name,
                'environment': 'AzureCloud',
                'creationMode': 'Manual'
            }
            service_endpoint_to_create = ServiceEndpoint(
                authorization=service_endpoint_authorization,
                data=service_endpoint_data,
                name=name,
                type=SERVICE_ENDPOINT_TYPE_AZURE_RM,
                url='https://management.azure.com/')
            return client.create_service_endpoint(service_endpoint_to_create,
                                                  project)

        raise CLIError(
            'This combination of endpoint type is not supported with this authorization scheme.'
        )

    except VstsServiceError as ex:
        raise CLIError(ex)
Пример #16
0
def create_service_endpoint(service_endpoint_type,
                            authorization_scheme,
                            name,
                            github_url=None,
                            azure_rm_tenant_id=None,
                            azure_rm_service_principal_id=None,
                            azure_rm_subscription_id=None,
                            azure_rm_subscription_name=None,
                            organization=None,
                            project=None,
                            detect=None):
    """ (PREVIEW) Create a service endpoint
    :param service_endpoint_type: Type of service endpoint
    :type service_endpoint_type: str
    :param name: Name of service endpoint to create
    :type name: str
    :param authorization_scheme: Authorization to be used in service endpoint creation
     Github service endpoint supports PersonalAccessToken
     AzureRm service endpoint supports ServicePrincipal
    :type authorization_scheme: str
    :param github_url: Url for github for creating service endpoint
    :type github_url: str
    :param azure_rm_tenant_id: tenant id for creating azure rm service endpoint
    :type azure_rm_tenant_id: str
    :param azure_rm_service_principal_id: service principal id for creating azure rm service endpoint
    :type azure_rm_service_principal_id: str
    :param azure_rm_subscription_id: subscription id for azure rm service endpoint
    :type azure_rm_subscription_id: str
    :param azure_rm_subscription_name: name of azure subscription for azure rm service endpoint
    :type azure_rm_subscription_name: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)
    if (service_endpoint_type == SERVICE_ENDPOINT_TYPE_GITHUB
            and authorization_scheme
            == SERVICE_ENDPOINT_AUTHORIZATION_PERSONAL_ACCESS_TOKEN):

        if AZ_DEVOPS_GITHUB_PAT_ENVKEY not in os.environ:
            error_message = 'Please pass GitHub access token in ' + AZ_DEVOPS_GITHUB_PAT_ENVKEY +\
                            ' environment variable in non-interactive mode.'
            verify_is_a_tty_or_raise_error(error_message)
            github_access_token = prompt_pass('GitHub access token:',
                                              confirm=True)
        else:
            github_access_token = os.environ[AZ_DEVOPS_GITHUB_PAT_ENVKEY]

        service_endpoint_authorization = EndpointAuthorization(
            parameters={'accessToken': github_access_token},
            scheme=SERVICE_ENDPOINT_AUTHORIZATION_PERSONAL_ACCESS_TOKEN)
        service_endpoint_to_create = ServiceEndpoint(
            authorization=service_endpoint_authorization,
            name=name,
            type=SERVICE_ENDPOINT_TYPE_GITHUB,
            url=github_url)
        return client.create_service_endpoint(service_endpoint_to_create,
                                              project)

    if (service_endpoint_type == SERVICE_ENDPOINT_TYPE_AZURE_RM
            and authorization_scheme
            == SERVICE_ENDPOINT_AUTHORIZATION_SERVICE_PRINCIPAL):

        AZURE_RM_SP_KEY_END_VARIABLE_NAME = CLI_ENV_VARIABLE_PREFIX + 'AZURE_RM_SERVICE_PRINCIPAL_KEY'
        if AZURE_RM_SP_KEY_END_VARIABLE_NAME not in os.environ:
            error_message = 'Please specify azure service principal key in ' + AZURE_RM_SP_KEY_END_VARIABLE_NAME +\
                            ' environment variable in non-interactive mode.'
            verify_is_a_tty_or_raise_error(error_message)
            azure_rm_service_principal_key = prompt_pass(
                'Azure RM service principal key:', confirm=True)
        else:
            azure_rm_service_principal_key = os.environ[
                AZURE_RM_SP_KEY_END_VARIABLE_NAME]

        service_endpoint_authorization = EndpointAuthorization(
            parameters={
                'tenantid': azure_rm_tenant_id,
                'serviceprincipalid': azure_rm_service_principal_id,
                'authenticationType': 'spnKey',
                'serviceprincipalkey': azure_rm_service_principal_key
            },
            scheme=SERVICE_ENDPOINT_AUTHORIZATION_SERVICE_PRINCIPAL)
        service_endpoint_data = {
            'subscriptionId': azure_rm_subscription_id,
            'subscriptionName': azure_rm_subscription_name,
            'environment': 'AzureCloud',
            'creationMode': 'Manual'
        }
        service_endpoint_to_create = ServiceEndpoint(
            authorization=service_endpoint_authorization,
            data=service_endpoint_data,
            name=name,
            type=SERVICE_ENDPOINT_TYPE_AZURE_RM,
            url='https://management.azure.com/')
        return client.create_service_endpoint(service_endpoint_to_create,
                                              project)

    raise CLIError(
        'This combination of endpoint type is not supported with this authorization scheme.'
    )
Пример #17
0
def create_azurerm_service_endpoint(
        name,
        azure_rm_tenant_id,
        azure_rm_service_principal_id,
        azure_rm_subscription_id,
        azure_rm_subscription_name,
        azure_rm_service_principal_certificate_path=None,
        organization=None,
        project=None,
        detect=None):
    """ Create an Azure RM type service endpoint.
    :param name: Name of service endpoint to create
    :type name: str
    :param azure_rm_tenant_id: tenant id for creating azure rm service endpoint
    :type azure_rm_tenant_id: str
    :param azure_rm_service_principal_id: service principal id for creating azure rm service endpoint
    :type azure_rm_service_principal_id: str
    :param azure_rm_subscription_id: subscription id for azure rm service endpoint
    :type azure_rm_subscription_id: str
    :param azure_rm_service_principal_certificate_path: Path to (.pem) which is certificate.
     Create using command "openssl pkcs12 -in file.pfx -out file.pem -nodes -password pass:<password_here>".
     More details : https://aka.ms/azure-devops-cli-service-endpoint
    :type azure_rm_service_principal_certificate_path: str
    :param azure_rm_subscription_name: name of azure subscription for azure rm service endpoint
    :type azure_rm_subscription_name: str
    :rtype: :class:`ServiceEndpoint <service_endpoint.v4_1.models.ServiceEndpoint>`
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    client = get_service_endpoint_client(organization)

    service_endpoint_authorization = EndpointAuthorization(
        parameters={
            'tenantid': azure_rm_tenant_id,
            'serviceprincipalid': azure_rm_service_principal_id
        },
        scheme=SERVICE_ENDPOINT_AUTHORIZATION_SERVICE_PRINCIPAL)

    if azure_rm_service_principal_certificate_path is None:
        AZURE_RM_SP_KEY_END_VARIABLE_NAME = CLI_ENV_VARIABLE_PREFIX + 'AZURE_RM_SERVICE_PRINCIPAL_KEY'
        if AZURE_RM_SP_KEY_END_VARIABLE_NAME not in os.environ:
            error_message = 'Please specify azure service principal key in ' + AZURE_RM_SP_KEY_END_VARIABLE_NAME +\
                            ' environment variable in non-interactive mode or use ' +\
                            '--azure-rm-service-principal-certificate-path.'
            verify_is_a_tty_or_raise_error(error_message)
            azure_rm_service_principal_key = prompt_pass(
                'Azure RM service principal key:', confirm=True)
        else:
            logger.debug(
                'Picking Azure RM principal key from environment variable')
            azure_rm_service_principal_key = os.environ[
                AZURE_RM_SP_KEY_END_VARIABLE_NAME]

        service_endpoint_authorization.parameters[
            'authenticationType'] = 'spnKey'
        service_endpoint_authorization.parameters[
            'serviceprincipalkey'] = azure_rm_service_principal_key
    else:
        with open(azure_rm_service_principal_certificate_path, "r") as f:
            service_endpoint_authorization.parameters[
                'authenticationType'] = 'spnCertificate'
            service_endpoint_authorization.parameters[
                'servicePrincipalCertificate'] = f.read()

    service_endpoint_data = {
        'subscriptionId': azure_rm_subscription_id,
        'subscriptionName': azure_rm_subscription_name,
        'environment': 'AzureCloud',
        'creationMode': 'Manual'
    }
    service_endpoint_to_create = ServiceEndpoint(
        authorization=service_endpoint_authorization,
        data=service_endpoint_data,
        name=name,
        type=SERVICE_ENDPOINT_TYPE_AZURE_RM,
        url='https://management.azure.com/')
    return client.create_service_endpoint(service_endpoint_to_create, project)