コード例 #1
0
def confluent_organization_create(cmd,
                                  client,
                                  resource_group_name,
                                  organization_name,
                                  plan_id,
                                  plan_name,
                                  term_unit,
                                  tags=None,
                                  location=None,
                                  publisher_id=None,
                                  offer_id=None,
                                  no_wait=False):
    import jwt
    from azure.cli.core._profile import Profile
    from azure.cli.core.azclierror import UnauthorizedError
    from azure.cli.command_modules.role.custom import list_role_assignments

    token_info = Profile(cli_ctx=cmd.cli_ctx).get_raw_token()[0][2]
    # PyJWT < 2.0.0 is using `verify` to verify token
    # PyJWT >= 2.0.0 has moved this paramter in options
    # For compatibility, keep two options for now.
    decode = jwt.decode(token_info['accessToken'],
                        algorithms=['RS256'],
                        verify=False,
                        options={"verify_signature": False})
    body = {}
    body['user_detail'] = {}
    try:
        body['user_detail']['first_name'] = decode['given_name']
        body['user_detail']['last_name'] = decode['family_name']
        body['user_detail']['email_address'] = decode[
            'email'] if 'email' in decode else decode['unique_name']
    except KeyError as ex:
        raise UnauthorizedError(
            f'Cannot create the organization as CLI cannot get the right value for {str(ex)} from access '
            'token.') from ex

    # Check owner or contributor role of subscription
    user_object_id = decode['oid']
    role_assignments = list_role_assignments(cmd, assignee=user_object_id, role='Owner', include_inherited=True, include_groups=True) + \
        list_role_assignments(cmd, assignee=user_object_id, role='Contributor', include_inherited=True, include_groups=True)
    if not role_assignments:
        raise UnauthorizedError(
            'You must have Owner or Contributor role of the subscription to create an organization.'
        )

    body['tags'] = tags
    body['location'] = location
    body['offer_detail'] = {}
    body['offer_detail']['publisher_id'] = publisher_id
    body['offer_detail']['id'] = offer_id
    body['offer_detail']['plan_id'] = plan_id
    body['offer_detail']['plan_name'] = plan_name
    body['offer_detail']['term_unit'] = term_unit

    return sdk_no_wait(no_wait,
                       client.begin_create,
                       resource_group_name=resource_group_name,
                       organization_name=organization_name,
                       body=body)
コード例 #2
0
ファイル: _roleassignments.py プロジェクト: woakesd/azure-cli
def ensure_cluster_identity_permission_on_kubelet_identity(
        cmd, cluster_identity_object_id, scope):
    factory = get_auth_management_client(cmd.cli_ctx, scope)
    assignments_client = factory.role_assignments

    for i in assignments_client.list_for_scope(scope=scope,
                                               filter="atScope()"):
        if i.scope.lower() != scope.lower():
            continue
        if not i.role_definition_id.lower().endswith(
                CONST_MANAGED_IDENTITY_OPERATOR_ROLE_ID):
            continue
        if i.principal_id.lower() != cluster_identity_object_id.lower():
            continue
        # already assigned
        return

    if not add_role_assignment(cmd,
                               CONST_MANAGED_IDENTITY_OPERATOR_ROLE,
                               cluster_identity_object_id,
                               is_service_principal=False,
                               scope=scope):
        raise UnauthorizedError(
            "Could not grant Managed Identity Operator "
            "permission to cluster identity at scope {}".format(scope))
コード例 #3
0
def get_bearer_token(cmd, tenant_id):
    client = Profile(cli_ctx=cmd.cli_ctx)

    try:
        logger.debug("Retrieving access token for tenant %s", tenant_id)
        creds, _, _ = client.get_raw_token(tenant=tenant_id)
    except CLIError as unauthorized_error:
        raise UnauthorizedError("Can't find authorization for {0}. ".format(tenant_id) +
                                "Run \'az login -t <tenant_name> --allow-no-subscriptions\' and try again.") from \
            unauthorized_error

    return "Bearer " + creds[1]
コード例 #4
0
def map_azure_error_to_cli_error(azure_error):
    error_message = getattr(azure_error, "message", str(azure_error))
    if isinstance(azure_error, HttpResponseError):
        status_code = getattr(azure_error, "status_code", None)
        if status_code:
            status_code = int(status_code)
            if status_code == 400:
                return BadRequestError(error_message)
            if status_code == 401:
                return UnauthorizedError(error_message)
            if status_code == 403:
                return ForbiddenError(error_message)
            if status_code == 404:
                return ResourceNotFoundError(error_message)
            if 400 <= status_code < 500:
                return UnclassifiedUserFault(error_message)
            if 500 <= status_code < 600:
                return AzureInternalError(error_message)
        return ServiceError(error_message)
    if isinstance(azure_error, ServiceRequestError):
        return ClientRequestError(error_message)
    if isinstance(azure_error, ServiceResponseError):
        return AzureResponseError(error_message)
    return ServiceError(error_message)
コード例 #5
0
ファイル: custom.py プロジェクト: nilsanderselde/ARO-RP
def aro_create(cmd,  # pylint: disable=too-many-locals
               client,
               resource_group_name,
               resource_name,
               master_subnet,
               worker_subnet,
               vnet=None,  # pylint: disable=unused-argument
               vnet_resource_group_name=None,  # pylint: disable=unused-argument
               location=None,
               pull_secret=None,
               domain=None,
               cluster_resource_group=None,
               client_id=None,
               client_secret=None,
               pod_cidr=None,
               service_cidr=None,
               software_defined_network=None,
               disk_encryption_set=None,
               master_encryption_at_host=False,
               master_vm_size=None,
               worker_encryption_at_host=False,
               worker_vm_size=None,
               worker_vm_disk_size_gb=None,
               worker_count=None,
               apiserver_visibility=None,
               ingress_visibility=None,
               tags=None,
               no_wait=False):
    if not rp_mode_development():
        resource_client = get_mgmt_service_client(
            cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES)
        provider = resource_client.providers.get('Microsoft.RedHatOpenShift')
        if provider.registration_state != 'Registered':
            raise UnauthorizedError('Microsoft.RedHatOpenShift provider is not registered.',
                                    'Run `az provider register -n Microsoft.RedHatOpenShift --wait`.')

    validate_subnets(master_subnet, worker_subnet)

    subscription_id = get_subscription_id(cmd.cli_ctx)

    random_id = generate_random_id()

    aad = AADManager(cmd.cli_ctx)
    if client_id is None:
        app, client_secret = aad.create_application(cluster_resource_group or 'aro-' + random_id)
        client_id = app.app_id

    client_sp = aad.get_service_principal(client_id)
    if not client_sp:
        client_sp = aad.create_service_principal(client_id)

    rp_client_sp = aad.get_service_principal(resolve_rp_client_id())
    if not rp_client_sp:
        raise ResourceNotFoundError("RP service principal not found.")

    if rp_mode_development():
        worker_vm_size = worker_vm_size or 'Standard_D2s_v3'
    else:
        worker_vm_size = worker_vm_size or 'Standard_D4s_v3'

    if apiserver_visibility is not None:
        apiserver_visibility = apiserver_visibility.capitalize()

    if ingress_visibility is not None:
        ingress_visibility = ingress_visibility.capitalize()

    oc = openshiftcluster.OpenShiftCluster(
        location=location,
        tags=tags,
        cluster_profile=openshiftcluster.ClusterProfile(
            pull_secret=pull_secret or "",
            domain=domain or random_id,
            resource_group_id='/subscriptions/%s/resourceGroups/%s' %
            (subscription_id, cluster_resource_group or "aro-" + random_id),
        ),
        service_principal_profile=openshiftcluster.ServicePrincipalProfile(
            client_id=client_id,
            client_secret=client_secret,
        ),
        network_profile=openshiftcluster.NetworkProfile(
            pod_cidr=pod_cidr or '10.128.0.0/14',
            service_cidr=service_cidr or '172.30.0.0/16',
            software_defined_network=software_defined_network or 'OpenShiftSDN'
        ),
        master_profile=openshiftcluster.MasterProfile(
            vm_size=master_vm_size or 'Standard_D8s_v3',
            subnet_id=master_subnet,
            encryption_at_host='Enabled' if master_encryption_at_host else 'Disabled',
            disk_encryption_set_id=disk_encryption_set,
        ),
        worker_profiles=[
            openshiftcluster.WorkerProfile(
                name='worker',  # TODO: 'worker' should not be hard-coded
                vm_size=worker_vm_size,
                disk_size_gb=worker_vm_disk_size_gb or 128,
                subnet_id=worker_subnet,
                count=worker_count or 3,
                encryption_at_host='Enabled' if worker_encryption_at_host else 'Disabled',
                disk_encryption_set_id=disk_encryption_set,
            )
        ],
        apiserver_profile=openshiftcluster.APIServerProfile(
            visibility=apiserver_visibility or 'Public',
        ),
        ingress_profiles=[
            openshiftcluster.IngressProfile(
                name='default',  # TODO: 'default' should not be hard-coded
                visibility=ingress_visibility or 'Public',
            )
        ],
    )

    sp_obj_ids = [client_sp.object_id, rp_client_sp.object_id]
    ensure_resource_permissions(cmd.cli_ctx, oc, True, sp_obj_ids)

    return sdk_no_wait(no_wait, client.begin_create_or_update,
                       resource_group_name=resource_group_name,
                       resource_name=resource_name,
                       parameters=oc)