Ejemplo n.º 1
0
def login(cmd, username=None, password=None, service_principal=None, tenant=None, allow_no_subscriptions=False,
          identity=False, identity_port=None,
          msi=False, msi_port=None):  # will remove msi_xxx in a future release
    """Log in to access Azure subscriptions"""
    import os
    import re
    from adal.adal_error import AdalError
    import requests

    # quick argument usage check
    if (any([password, service_principal, tenant, allow_no_subscriptions]) and
            any([identity, msi])):
        raise CLIError("usage error: '--identity/--identity-port' are not applicable with other arguments")

    interactive = False

    profile = Profile(cli_ctx=cmd.cli_ctx, async_persist=False)

    # if identity or msi:
    #     if in_cloud_console():
    #         return profile.find_subscriptions_in_cloud_console()
    #     return profile.find_subscriptions_in_vm_with_msi(identity_port or msi_port or 50342, username)
    # elif in_cloud_console():  # tell users they might not need login
    #     logger.warning(_CLOUD_CONSOLE_LOGIN_WARNING)

    if in_cloud_console():
        console_tokens = os.environ.get('AZURE_CONSOLE_TOKENS', None)
        if console_tokens:
            return profile.find_subscriptions_in_cloud_console_thru_raw_token(re.split(';|,', console_tokens))
        logger.warning(_CLOUD_CONSOLE_WARNING_TEMPLATE, 'login')
        return

    if identity or msi:
        return profile.find_subscriptions_in_vm_with_msi(identity_port or msi_port or 50342, username)

    if username:
        if not password:
            try:
                password = prompt_pass('Password: '******'Please specify both username and password in non-interactive mode.')
    else:
        interactive = True

    try:
        subscriptions = profile.find_subscriptions_on_login(
            interactive,
            username,
            password,
            service_principal,
            tenant,
            allow_no_subscriptions=allow_no_subscriptions)
    except AdalError as err:
        # try polish unfriendly server errors
        if username:
            msg = str(err)
            suggestion = "For cross-check, try 'az login' to authenticate through browser."
            if ('ID3242:' in msg) or ('Server returned an unknown AccountType' in msg):
                raise CLIError("The user name might be invalid. " + suggestion)
            if 'Server returned error in RSTR - ErrorCode' in msg:
                raise CLIError("Logging in through command line is not supported. " + suggestion)
        raise CLIError(err)
    except requests.exceptions.ConnectionError as err:
        raise CLIError('Please ensure you have network connection. Error detail: ' + str(err))
    all_subscriptions = list(subscriptions)
    for sub in all_subscriptions:
        sub['cloudName'] = sub.pop('environmentName', None)
    return all_subscriptions