Azure Data Explorer and KQL Interview Questions and Answers Part 8 - Security and Governance

Azure Data Explorer Interview Q&A · Part 8 of 10

In this post we are going to cover security and governance in Azure Data Explorer. These are 7 real Azure Data Explorer and KQL interview questions for data engineers, asked the way they come up on a real project, and the last one is a scenario: one shared cluster serves three teams with different data and different budgets.

Security in Azure Data Explorer has layers: who signs in, what each caller may do, which rows and columns they see, how the cluster is reached, and how you prove later who did what. Interviewers ask about it because a real security review checks every one of these layers.

Part 8 of the Real Time Azure Data Explorer and KQL Interview Questions and Answers series on TechBrothersIT.

The short answer

Say this first

Callers sign in with Microsoft Entra ID and get Kusto roles (cluster, database, table); Azure roles only manage the resource. Row level security replaces every query on a table with a function, and can also mask a column: there's no column-level permission. Apps use managed identities, the network uses private endpoints, and audits read .show commands-and-queries, .show journal and diagnostic logs.

Let's create some sample data

Every query below runs on the Kusto emulator, Microsoft's Azure Data Explorer engine in a local container, in a database called shop. kql is a small helper that sends a query or a .kql file to the emulator and prints the result as a table. setup.kql creates Sales, six invented orders in three regions, loaded with .ingest inline, which is for exploration and prototyping, not production. It also creates two empty lookup tables, RegionAccess and PiiReaders. teamdbs.kql creates three team databases, finance, marketing and support, and the full script puts one row in a table in each.

One thing to keep in mind for the whole post: the emulator has no sign-in. Every caller is the same <null identity>, so roles are stored but never enforced locally. What only a cluster in Azure can show, such as Entra ID sign-in, private endpoints and diagnostic logs, is shown as code.

setup.kql
.create table Sales (OrderId:long, Region:string, Customer:string, Email:string, Amount:real)

.ingest inline into table Sales <|
1001,East,lena,lena@example.com,120
1002,West,omar,omar@example.com,200
1003,East,priya,priya@example.com,80
1004,North,sam,sam@example.com,150
1005,West,kim,kim@example.com,95
1006,East,tom,tom@example.com,60

.create table RegionAccess (Principal:string, Region:string)

.create table PiiReaders (Principal:string)
teamdbs.kql
.create database finance persist (@"/kustodata/dbs/finance/md", @"/kustodata/dbs/finance/data")

.create database marketing persist (@"/kustodata/dbs/marketing/md", @"/kustodata/dbs/marketing/data")

.create database support persist (@"/kustodata/dbs/support/md", @"/kustodata/dbs/support/data")

Question 1: A security review asks how access works in Azure Data Explorer. What roles exist?

Every caller signs in with Microsoft Entra ID, and what it can do comes from Kusto roles on the cluster, a database or a table. Azure roles like Owner or Contributor manage the cluster resource, not the data.

Let's look at the roles by level:

LevelRolesWhat they allow
ClusterAllDatabasesAdmin, AllDatabasesViewer, AllDatabasesMonitorthe same, on every database
DatabaseAdmin, Usereverything / read, create tables and functions
DatabaseViewer, UnrestrictedViewerread / also tables with restricted view access
DatabaseIngestor, Monitoringest without query / metadata and .show
TableAdmin, Ingestorone table

Now let's grant four Entra groups database roles with .add database, in roles.kql. Then we list them with .show database shop principals.

roles.kql
.add database shop viewers
    ('aadgroup=sales-analysts@contoso.com') 'Sales analysts'

.add database shop ingestors
    ('aadgroup=order-loaders@contoso.com') 'Load pipelines'

.add database shop monitors
    ('aadgroup=platform-ops@contoso.com') 'Operations'

.add database shop unrestrictedviewers
    ('aadgroup=privacy-team@contoso.com') 'PII readers'
Terminal
$ kql -q -f roles.kql
> .add database shop viewers
ok: .add database shop viewers

> .add database shop ingestors
ok: .add database shop ingestors

> .add database shop monitors
ok: .add database shop monitors

> .add database shop unrestrictedviewers
ok: .add database shop unrestrictedviewers
KQL - the query behind the result table
.show database shop principals | project Role, PrincipalFQN | order by Role asc
Result table4 rows
RolePrincipalFQN
Database shop Ingestoraadgroup=order-loaders@contoso.com
Database shop Monitoraadgroup=platform-ops@contoso.com
Database shop UnrestrictedVieweraadgroup=privacy-team@contoso.com
Database shop Vieweraadgroup=sales-analysts@contoso.com

We get four rows: Database shop Ingestor for order-loaders@contoso.com, Database shop Monitor for platform-ops@contoso.com, Database shop UnrestrictedViewer for privacy-team@contoso.com, and Database shop Viewer for sales-analysts@contoso.com.

The emulator stores these roles, but it has no sign-in, so it enforces none of them. In Azure, every request is checked against them.

Real project

Grant roles to groups, never to single users. Load pipelines get Ingestor, plus Viewer only if they must read, and I review this list in every audit.

Question 2: Each region's managers must see only their own rows. How does row level security work?

Row level security is a table policy that names a function. Once it's enabled, every query on the table runs that function instead, for every user, including database admins and the person who created it.

Our function keeps the rows whose region is mapped to the caller in RegionAccess, and the caller comes from current_principal(). Let's create SalesRls(), enable the policy, and count the rows.

rls.kql
.create-or-alter function with (folder='Security') SalesRls() {
    Sales
    | where Region in ((RegionAccess
        | where Principal == current_principal()
        | project Region))
}

.alter table Sales policy row_level_security enable "SalesRls"
Terminal
$ kql -q -f rls.kql
> .create-or-alter function with (folder='Security') SalesRls() {
ok: .create-or-alter function with (folder='Security') SalesRls() {

> .alter table Sales policy row_level_security enable "SalesRls"
ok: .alter table Sales policy row_level_security enable "SalesRls"
$ kql 'Sales | count'
Count
-----
0

The count is 0. Nobody is mapped yet, so the policy fails closed.

Now remember, the emulator has no sign-in, so every caller is the null identity. Row level security can only filter here because we map that identity in the table. We add it to RegionAccess with .set-or-append, for East, and query Sales again.

Terminal
$ kql -q '.set-or-append RegionAccess <| print Principal = current_principal(), Region = "East"'
ok: .set-or-append RegionAccess <| print Principal = current_principal(), Region = "East"
KQL - the query behind the result table
Sales | order by OrderId asc
Result table3 rows
OrderIdRegionCustomerEmailAmount
1001Eastlenalena@example.com120
1003Eastpriyapriya@example.com80
1006Easttomtom@example.com60

Now Sales returns only the three East orders: 1001 for lena, 1003 for priya and 1006 for tom.

In Azure, I usually check Entra groups instead of a mapping table. current_principal_is_member_of() needs a real sign-in, so this version doesn't run on the emulator:

rls_azure.kql (Azure, not run here)
// on Azure: check Entra groups instead of a mapping table
.create-or-alter function SalesRls() {
    Sales
    | where (Region == "East"
      and current_principal_is_member_of('aadgroup=east@contoso.com'))
       or (Region == "West"
      and current_principal_is_member_of('aadgroup=west@contoso.com'))
}

Things to know:

  • Keep it a simple filter: it runs on every query
  • No query results cache: for queries on the table
  • Followers too: the policy applies on follower databases
Local vs Azure

Locally, the filter works only because the null identity is in RegionAccess. In Azure, the caller is the real signed-in user or app.

Question 3: Someone asks how to hide a sensitive column from most users. What options do you have?

The honest answer: there's no column-level permission in Azure Data Explorer. Whoever can read a table reads every column. So you mask the column, or you keep it somewhere else.

Option one, the row level security function can mask. Let's replace SalesRls() with a version that sets Email to four stars unless the caller is listed in PiiReaders.

mask.kql
.create-or-alter function with (folder='Security') SalesRls() {
    let me = current_principal();
    Sales
    | where Region in ((RegionAccess
        | where Principal == me | project Region))
    | extend Email = iff(me in ((PiiReaders | project Principal)),
        Email, "****")
}
Terminal
$ kql -q -f mask.kql
> .create-or-alter function with (folder='Security') SalesRls() {
ok: .create-or-alter function with (folder='Security') SalesRls() {
KQL - the query behind the result table
Sales | order by OrderId asc
Result table3 rows
OrderIdRegionCustomerEmailAmount
1001Eastlena****120
1003Eastpriya****80
1006Easttom****60

The rows are the same three East orders, and every Email is ****. The null identity isn't listed as a PII reader, so the emails come back masked.

Option two is restricted view access: only UnrestrictedViewer can query the table, and even admins are blocked. Let's try to enable it on Sales.

Terminal (expected error)
$ kql '.alter table Sales policy restricted_view_access true'
Error: Error during execution of a policy operation: Configuring an enabled restricted_view_access
  policy failed because this table has row_level_security policy enabled

The engine refuses: Configuring an enabled restricted_view_access policy failed because this table has row_level_security policy enabled. It's one or the other.

Option three, split the data at ingestion. An update policy writes a table without the column, or with a hash, and the raw PII goes to its own restricted table or database. Here are all four options side by side:

OptionHowWatch out
Mask in the RLS functioniff(...) keeps the row, hides the valueone function for rows and columns
Restricted view accessonly UnrestrictedViewer can query the tablenot together with RLS
Split at ingestionupdate policy: a table without it, or a hashraw PII in its own table or database
A function that drops itproject-away in a stored functionno boundary: the table is still readable

A function that drops the column is no boundary while users can still read the table.

Real project

I mask with a salted hash when analysts still need to count distinct customers, and PII readers are one Entra group.

Question 4: A teammate asks how an app or a pipeline authenticates to the cluster. What do you set up?

Each app or pipeline gets its own Entra identity: a managed identity where it runs in Azure, like Data Factory, otherwise an app registration with a certificate. Then it gets the smallest Kusto role on just the databases it needs.

In code, the Python SDK takes a token credential. With a managed identity, there's no secret to store or rotate:

client.py (Azure, not run here)
from azure.identity import ManagedIdentityCredential
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder

CLUSTER = "https://shopadx.eastus2.kusto.windows.net"
kcsb = KustoConnectionStringBuilder.with_azure_token_credential(
    CLUSTER, ManagedIdentityCredential())     # no secret to store
client = KustoClient(kcsb)

The grant uses the identity's client ID with .add database:

grant.kql (Azure, not run here)
// one identity per pipeline, the smallest roles, one database
.add database shop ingestors
    ('aadapp=<identity client id>;<tenant id>') 'orders pipeline'
.add database shop viewers
    ('aadapp=<identity client id>;<tenant id>') 'orders pipeline'

The emulator has no sign-in, so our local app.py connects with no authentication over plain HTTP, for local tests only. It prints who it is and how many orders it can see.

app.py
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder

# emulator only: plain HTTP and no sign-in (never in Azure)
kcsb = KustoConnectionStringBuilder.with_no_authentication(
    "http://localhost:8080")
client = KustoClient(kcsb)

who = client.execute("shop", "print who = current_principal()")
print("principal:", who.primary_results[0][0]["who"])
seen = client.execute("shop", "Sales | summarize Orders = count()")
print("orders this app can see:", seen.primary_results[0][0]["Orders"])
Terminal
$ python app.py
principal: <null identity>
orders this app can see: 3

The principal is <null identity>, the same identity we mapped to East, so row level security gives this app 3 orders.

A few more details:

  • Azure DevOps tasks: service principal, managed identity, or workload identity federation (keyless, recommended)
  • Data Factory, system identity: Database ingestor + viewer to load
  • No shared admin secret: one identity per pipeline
Mistake I see

One shared app secret with admin rights for every pipeline. One identity per pipeline, with the smallest role.

Question 5: Security wants the cluster off the public internet. What networking options do you use?

Inbound, a private endpoint, then public network access disabled. Outbound, restrict what the cluster may call.

First, inbound. Private Link gives the cluster private IP addresses in your virtual network, and clients keep the same connection string through a private DNS zone. Plan the subnet: the private endpoint uses 13 private IP addresses, so you need at least a /28.

private_endpoint.sh (Azure, not run)
# inbound: a private endpoint (target sub-resource: cluster)
az network private-endpoint create -g rg-data -n pe-shopadx \
  --vnet-name vnet-data --subnet snet-adx \
  --private-connection-resource-id "$ADX_ID" \
  --group-id cluster --connection-name shopadx-pe
# then link the private DNS zones to it (a dns-zone-group)

Virtual network injection is retired; private endpoints replace it.

Then outbound. The cluster can call out, for external tables, SQL or web requests. Restrict it with restricted outbound access and an allowed list of host names. In Bicep, both settings sit next to the public access switch:

cluster.bicep (excerpt, Azure, not run)
resource adx 'Microsoft.Kusto/clusters@2023-05-02' = {
  name: 'shopadx'
  location: location
  sku: sku
  properties: {
    publicNetworkAccess: 'Disabled'      // private endpoint only
    restrictOutboundNetworkAccess: 'Enabled'
    allowedFqdnList: [ 'stshoplake.blob.core.windows.net' ]
  }
}

For Event Hubs and storage, Microsoft recommends managed identity over managed private endpoints.

Inside the engine, callout policies control those calls, and they run on the emulator. Let's set a cluster callout policy that denies every web API call, then try the http_request plugin.

callout.kql
.alter cluster policy callout ```[{"CalloutType": "webapi",
    "CalloutUriRegex": ".*", "CanCall": false}]```
    | project Policy

evaluate http_request('https://rates.example.com/api/fx')
Terminal (expected error)
$ kql --cell 120 -f callout.kql
> .alter cluster policy callout ```[{"CalloutType": "webapi",
Policy
------------------------------------------------------------------------------------------
[   {     "CalloutType": "webapi",     "CalloutUriRegex": ".*",     "CanCall": false   } ]

> evaluate http_request('https://rates.example.com/api/fx')
Error: Cannot invoke callout of type 'webapi' to 'https://rates.example.com/api/fx' due to callout
  policy.

The policy is stored with "CanCall": false, and the plugin fails: Cannot invoke callout of type 'webapi' to 'https://rates.example.com/api/fx' due to callout policy.

Pitfall

Someone disables public access before private DNS works, and every dashboard and pipeline breaks at once. Test from inside the network first.

Question 6: Someone asks how to audit who ran which queries and commands. Where do you look?

Inside the engine first. .show commands-and-queries keeps finished commands and queries for 30 days, and .show journal records metadata changes.

WhereWhat it keepsUse it for
.show commands-and-queriesfinished commands and queries, 30 dayswho, which app, the text, the state
.show journalmetadata changescreate, alter, drop, add principals

These logs fill in the background on the emulator, so the full script waits at this point until our rows are there. Then let's read the journal for Sales and its security function.

Terminal
$ kql '.show journal | where EntityName in ("Sales", "SalesRls") | project Event, EntityName, Command = substring(ChangeCommand, 0, 64) | order by Event asc, Command asc'
Event                                  EntityName  Command
-------------------------------------  ---------- 
  ------------------------------------------------------------
ADD-FUNCTION                           SalesRls    .create-or-alter function with (folder='Security')
  SalesR...
ALTER-FUNCTION                         SalesRls    .create-or-alter function with (folder='Security')
  SalesR...
ALTER-TABLE-ROW-LEVEL-SECURITY-POLICY  Sales       .alter table Sales policy row_level_security enable
  "Sale...
CREATE-TABLE                           Sales       .create table Sales (OrderId:long, Region:string,
  Custome...
Result table4 rows
EventEntityNameCommand
ADD-FUNCTIONSalesRls.create-or-alter function with (folder='Security') SalesRls() {
ALTER-FUNCTIONSalesRls.create-or-alter function with (folder='Security') SalesRls() {
ALTER-TABLE-ROW-LEVEL-SECURITY-POLICYSales.alter table Sales policy row_level_security enable "SalesRls"
CREATE-TABLESales.create table Sales (OrderId:long, Region:string, Customer:strin

Four events, all from this post: CREATE-TABLE for Sales, ADD-FUNCTION and ALTER-FUNCTION for SalesRls, and ALTER-TABLE-ROW-LEVEL-SECURITY-POLICY for Sales.

Now everything app.py ran, with its principal:

Terminal
$ kql '.show commands-and-queries | where Application == "app.py" | project Application, Text, State, Principal | order by Text asc'
Application  Text                                State      Principal
-----------  ----------------------------------  ---------  ---------------
app.py       Sales | summarize Orders = count()  Completed  <null identity>
app.py       print who = current_principal()     Completed  <null identity>
Result table2 rows
ApplicationTextStatePrincipal
app.pySales | summarize Orders = count()Completed<null identity>
app.pyprint who = current_principal()Completed<null identity>

Two queries, both Completed: print who = current_principal() and Sales | summarize Orders = count(), each with the principal <null identity>. In Azure, that column holds the real Entra identity.

For long-term audit and alerts, turn on diagnostic settings, which are off by default:

diagnostic_settings.sh (Azure, not run)
# diagnostic logs are off by default: send them to Log Analytics
az monitor diagnostic-settings create -n adx-audit \
  --resource "$ADX_ID" --workspace "$LAW_ID" \
  --export-to-resource-specific true \
  --logs '[{"category": "Command", "enabled": true},
           {"category": "Query", "enabled": true},
           {"category": "Journal", "enabled": true}]'

The categories land in these Log Analytics tables:

CategoryLog Analytics table
CommandADXCommand
QueryADXQuery
JournalADXJournal

Changes to the cluster resource itself, like network, SKU or keys, are in the Azure activity log, not in the engine.

Tip

Query text is stored and visible to admins and monitors, so keep secrets and personal data out of it, and send the logs to a workspace your security team owns.

Scenario 7: A shared cluster serves three teams with different data and different budgets. How do you secure and isolate them?

One database per team for the data, workload groups for compute, and a follower database on its own cluster for a team with heavy dashboards.

First, data. finance, marketing and support each get their own Entra groups and roles, so no team reads another team's tables.

Then compute. Workload groups cap what each team can use. In teams.kql, finance gets a two-minute execution limit and 10 concurrent requests, and marketing gets 5. A request classification policy sends each request to a group, here by database. Then we run one query per database.

teams.kql
.add database finance viewers ('aadgroup=finance-team@contoso.com')

.add database marketing viewers ('aadgroup=mkt-team@contoso.com')

.create-or-alter workload_group Finance ```{
  "RequestLimitsPolicy": {"MaxExecutionTime":
    {"IsRelaxable": false, "Value": "00:02:00"}},
  "RequestRateLimitPolicies": [{"IsEnabled": true,
    "Scope": "WorkloadGroup", "LimitKind": "ConcurrentRequests",
    "Properties": {"MaxConcurrentRequests": 10}}]}```

.create-or-alter workload_group Marketing ```{
  "RequestRateLimitPolicies": [{"IsEnabled": true,
    "Scope": "WorkloadGroup", "LimitKind": "ConcurrentRequests",
    "Properties": {"MaxConcurrentRequests": 5}}]}```

.alter cluster policy request_classification '{"IsEnabled":true}' <|
    case(request_properties.current_database == "finance", "Finance",
      request_properties.current_database == "marketing", "Marketing",
      "default")
Terminal
$ kql -q -f teams.kql
> .add database finance viewers ('aadgroup=finance-team@contoso.com')
ok: .add database finance viewers ('aadgroup=finance-team@contoso.com')

> .add database marketing viewers ('aadgroup=mkt-team@contoso.com')
ok: .add database marketing viewers ('aadgroup=mkt-team@contoso.com')

> .create-or-alter workload_group Finance ```{
ok: .create-or-alter workload_group Finance ```{

> .create-or-alter workload_group Marketing ```{
ok: .create-or-alter workload_group Marketing ```{

> .alter cluster policy request_classification '{"IsEnabled":true}' <|
ok: .alter cluster policy request_classification '{"IsEnabled":true}' <|
$ kql -d finance 'Ledger | count'
Count
-----
1
$ kql -d marketing 'Campaigns | count'
Count
-----
1
$ kql -d support 'Tickets | count'
Count
-----
1

Each team table returns 1 row. The emulator ignores the roles, but it does classify requests. .show queries fills in the background too, so the full script waits until all three queries are listed. Then let's see where each one ran.

Terminal
$ kql '.show queries | where Database in ("finance", "marketing", "support") | project Database, Text, WorkloadGroup | order by Database asc'
Database   Text               WorkloadGroup
---------  -----------------  -------------
finance    Ledger | count     Finance
marketing  Campaigns | count  Marketing
support    Tickets | count    default
Result table3 rows
DatabaseTextWorkloadGroup
financeLedger | countFinance
marketingCampaigns | countMarketing
supportTickets | countdefault

finance ran in Finance, marketing in Marketing, and support in default, because we gave it no group.

Budgets: a team with heavy dashboards gets a follower database on its own cluster, with the same data, separate compute, and the team pays. .show commands-and-queries records each request's workload group and total CPU, for chargeback.

Two more rules:

  • Shared data: one database + RLS
  • Scripts and Bicep: a new team = a pull request

Key points to remember

  • Entra ID sign-in + Kusto roles (cluster, database, table), granted to groups
  • Row level security: a function replaces every query on the table, for every user
  • No column-level permission: mask in the RLS function, restricted view access, or split the data
  • Apps: managed identities; network: private endpoints, public access off, outbound restricted
  • Audit: .show commands-and-queries, .show journal, diagnostic logs to Log Analytics

The full script

Here is a Python script that writes every file and runs every query in order on the Kusto emulator; start the emulator container first, as the comments at the top of the script show.

Show the full script that writes the files and runs every step
Full script - writes the files and runs every step on the Kusto emulator (start the emulator container first, see the comments at the top), run it with Python
# ========================================================================
# Azure Data Explorer Interview Q&A #8 - Security and governance
# TechBrothersIT. Names and sample data are invented for teaching.
# Every step below was run on the Kusto emulator (Kustainer, the Azure Data Explorer engine in a Linux container,
# build 2026.11.02); the outputs in the video and the blog post are the real outputs.
# To run it yourself (Docker on Linux, macOS or Windows with WSL), in an EMPTY folder:
#   1. Start the emulator with this folder mounted at /kustodata (the steps ingest files from there):
#      docker run -d --name kustainer -e ACCEPT_EULA=Y -m 4G -p 8080:8080 -v "$PWD":/kustodata \
#          mcr.microsoft.com/azuredataexplorer/kustainer-linux:latest
#      Wait until `docker logs kustainer` says the database "is answering queries".
#   2. python KQL_Interview_QA_08_Code.py   (Python 3.10 or later; kql.py itself needs no packages: it uses the REST API)
#      The python scripts in some steps use the Kusto Python SDK: pip install azure-kusto-data azure-kusto-ingest
# "kql" in the commands is a small helper written by Step 0 (kql.py): it sends a query or a management command
# to http://localhost:8080 and prints the result as a text table (no sign-in: the emulator has no authentication).
# The emulator is for development and testing only; an Azure Data Explorer cluster needs Microsoft Entra ID sign-in
# (use the Kusto SDK or the web UI there).
# Steps that restart the emulator say so in a comment: run "docker restart kustainer" at that point.
# ========================================================================

import os, subprocess, sys, time

def write(path, text):
    if text is None:
        if os.path.exists(path): os.remove(path)
        return
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text.strip("\n") + "\n")

def run(cmd, expect_error=False, allow_error=False, env=None):
    print("\n$ " + cmd, flush=True)
    rc = subprocess.run(cmd, shell=True, env=dict(os.environ, **(env or {}))).returncode
    if rc != 0 and not (expect_error or allow_error):
        raise SystemExit("stopped: this command was expected to succeed")

# Environment used by every step (the database the steps use)
os.environ.update({'KQL_DB': 'shop'})

# Step 0: the kql helper, the database and the starting files
write("kql.py", '"""kql: run KQL queries and management commands on the local Kusto emulator (Kustainer), print the results as text tables.\n  kql \'StormEvents | take 3\'              run one query or one management command (starts with \'.\')\n  kql -f script.kql                      run every statement in the file (statements are separated by blank lines;\n                                         // comment lines are skipped); each result is printed under its first line\n  options: -d DB (default $KQL_DB or NetDefaultDB)  --max N rows to print (default 30)  --cell N max chars per cell (default 60)\n           -q  for management commands: print one line ("ok: <command>") instead of the result table\n           --stats  after a query, print the rows / extents the query scanned (from the engine\'s own query statistics)\n           --props \'{"Options": {...}}\'  client request properties (e.g. truncationmaxrecords)\n           -e  keep going after an error (the error is printed and the exit code is 1 at the end)\n           --json  print the last statement\'s first result as JSON {"cols": [...], "rows": [...]} (used by the video generator)\nEmpty cells: a null value in a non-string column prints as "null"; an empty or null string prints as nothing.\nA query that fails after returning some rows (for example a result over the truncation limit) prints the rows it got, then\n"Error (partial result): <engine message>", and exits 1.\nThe engine answers at http://localhost:8080 (no authentication: the emulator has none)."""\nimport json, os, re, sys, urllib.request, urllib.error\n\nURL = os.environ.get(\'KQL_URL\', \'http://localhost:8080\')\n\n\ndef post(path, db, csl, props=None):\n    body = {\'db\': db, \'csl\': csl, \'properties\': json.dumps(props or {\'Options\': {}})}\n    req = urllib.request.Request(URL + path, data=json.dumps(body).encode(), method=\'POST\',\n                                 headers={\'Content-Type\': \'application/json; charset=utf-8\', \'Accept\': \'application/json\',\n                                          \'x-ms-app\': \'kql-cli\', \'x-ms-client-request-id\': \'kql-cli\'})\n    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))\n    try:\n        with opener.open(req, timeout=600) as r: return json.loads(r.read().decode(\'utf-8\'))\n    except urllib.error.HTTPError as e:\n        txt = e.read().decode(\'utf-8\', \'replace\')\n        try:\n            er = json.loads(txt)[\'error\']\n            msg = er.get(\'@message\') or er.get(\'message\')\n        except Exception:\n            msg = txt.strip().split(\'\\n\')[0]\n        msg = re.sub(r\'^Request is invalid and cannot be processed: \', \'\', msg)\n        msg = re.sub(r\'\\s*\\(Activity stack:.*\', \'\', msg, flags=re.S)\n        raise KqlError(msg.strip())\n\n\nclass KqlError(Exception): pass\n\n\ndef cell(v, width, typ=\'\'):\n    if v is None: s = \'\' if typ in (\'string\', \'\') else \'null\'\n    elif isinstance(v, bool): s = \'true\' if v else \'false\'\n    elif isinstance(v, (dict, list)): s = json.dumps(v, separators=(\',\', \':\'), ensure_ascii=False)\n    elif isinstance(v, float):\n        s = repr(v)\n        if s.endswith(\'.0\'): s = s[:-2]\n    else: s = str(v)\n    s = s.replace(\'\\r\', \' \').replace(\'\\n\', \' \')\n    if len(s) > width: s = s[:width - 3] + \'...\'\n    return s\n\n\ndef table(cols, rows, mx, width, types=None):\n    rows = rows if isinstance(rows, list) else []\n    types = types or [\'\'] * len(cols)\n    shown = [[cell(v, width, types[i]) for i, v in enumerate(r)] for r in rows[:mx]]\n    w = [max([len(c)] + [len(r[i]) for r in shown]) for i, c in enumerate(cols)]\n    out = [\'  \'.join(c.ljust(w[i]) for i, c in enumerate(cols)).rstrip(),\n           \'  \'.join(\'-\' * w[i] for i in range(len(cols)))]\n    for r in shown:\n        out.append(\'  \'.join(v.ljust(w[i]) for i, v in enumerate(r)).rstrip())\n    n = len(rows)\n    if n > mx: out.append(\'... %d more rows (%d rows in total)\' % (n - mx, n))\n    elif n == 0: out.append(\'(no rows)\')\n    return \'\\n\'.join(out)\n\n\nLAST = {}\n\n\ndef one_api_msg(errs):\n    msgs = []\n    for e in errs or []:\n        er = e.get(\'error\', e) if isinstance(e, dict) else {}\n        m = er.get(\'@message\') or er.get(\'message\') or str(e)\n        m = re.sub(r\'\\s*\\(Activity stack:.*\', \'\', m, flags=re.S).strip()\n        if m not in msgs: msgs.append(m)\n    return \' | \'.join(msgs) or \'unknown error\'\n\n\ndef run_query(db, csl, a):\n    frames = post(\'/v2/rest/query\', db, csl, a.props)\n    outs, stats, partial = [], None, None\n    for f in frames:\n        if f.get(\'FrameType\') == \'DataSetCompletion\' and f.get(\'HasErrors\') and partial is None:\n            partial = one_api_msg(f.get(\'OneApiErrors\'))\n        if f.get(\'FrameType\') != \'DataTable\': continue\n        if f.get(\'TableKind\') == \'PrimaryResult\':\n            rows = [r for r in f[\'Rows\'] if isinstance(r, list)]\n            for r in f[\'Rows\']:\n                if isinstance(r, dict) and r.get(\'OneApiErrors\'): partial = one_api_msg(r[\'OneApiErrors\'])\n            cols = [c[\'ColumnName\'] for c in f[\'Columns\']]\n            if \'cols\' not in LAST: LAST.update(cols=cols, rows=rows)\n            outs.append(table(cols, rows, a.max, a.cell, [str(c.get(\'ColumnType\', \'\')).lower() for c in f[\'Columns\']]))\n        if f.get(\'TableKind\') == \'QueryCompletionInformation\':\n            cols = [c[\'ColumnName\'] for c in f[\'Columns\']]\n            for r in f[\'Rows\']:\n                d = dict(zip(cols, r))\n                if d.get(\'EventTypeName\') == \'QueryResourceConsumption\':\n                    try: stats = json.loads(d[\'Payload\'])\n                    except Exception: pass\n                if d.get(\'Level\') in (2, 3) and d.get(\'EventTypeName\') not in (\'QueryResourceConsumption\',):\n                    txt = d.get(\'Payload\') or \'\'\n                    try: txt = json.loads(txt).get(\'Text\', txt)\n                    except Exception: pass\n                    outs.append(\'%s: %s\' % (\'Warning\' if d.get(\'Level\') == 3 else \'Error\', txt))\n    if a.stats and stats:\n        sh = (stats.get(\'resource_usage\') or {}).get(\'cache\', {}).get(\'shards\', {})\n        ix = stats.get(\'input_dataset_statistics\') or {}\n        ex, rw = ix.get(\'extents\') or {}, ix.get(\'rows\') or {}\n        outs.append(\'scanned: %s of %s extents, %s of %s rows\' % (ex.get(\'scanned\'), ex.get(\'total\'), rw.get(\'scanned\'), rw.get(\'total\')))\n    if partial:\n        outs.append(\'Error (partial result): \' + partial)\n        raise PartialError(\'\\n\\n\'.join(outs))\n    return \'\\n\\n\'.join(outs)\n\n\nclass PartialError(Exception): pass\n\n\ndef run_mgmt(db, csl, a):\n    d = post(\'/v1/rest/mgmt\', db, csl, a.props)\n    if a.q and not a.json: return \'ok: \' + first_line(csl)\n    t = (d.get(\'Tables\') or [{}])[0]\n    LAST.update(cols=[c[\'ColumnName\'] for c in t.get(\'Columns\', [])], rows=t.get(\'Rows\', []))\n    return table([c[\'ColumnName\'] for c in t.get(\'Columns\', [])], t.get(\'Rows\', []), a.max, a.cell,\n                 [str(c.get(\'DataType\', c.get(\'ColumnType\', \'\'))).lower().replace(\'system.\', \'\') for c in t.get(\'Columns\', [])])\n\n\ndef first_line(s):\n    l = s.strip().split(\'\\n\')[0].strip()\n    return l if len(l) <= 90 else l[:87] + \'...\'\n\n\ndef statements(text):\n    blocks, cur = [], []\n    for l in text.split(\'\\n\'):\n        if not l.strip():\n            if cur: blocks.append(\'\\n\'.join(cur)); cur = []\n            continue\n        if l.strip().startswith(\'//\') and not cur: continue\n        cur.append(l)\n    if cur: blocks.append(\'\\n\'.join(cur))\n    return blocks\n\n\ndef main():\n    import argparse\n    p = argparse.ArgumentParser(add_help=False)\n    p.add_argument(\'-d\', default=os.environ.get(\'KQL_DB\', \'NetDefaultDB\'))\n    p.add_argument(\'-f\'); p.add_argument(\'-q\', action=\'store_true\'); p.add_argument(\'-e\', action=\'store_true\')\n    p.add_argument(\'--stats\', action=\'store_true\'); p.add_argument(\'--max\', type=int, default=30)\n    p.add_argument(\'--cell\', type=int, default=60); p.add_argument(\'--props\'); p.add_argument(\'-h\', \'--help\', action=\'store_true\')\n    p.add_argument(\'--json\', action=\'store_true\')\n    p.add_argument(\'text\', nargs=\'?\')\n    a = p.parse_args()\n    if a.help or (not a.f and not a.text): print(__doc__); return 0\n    a.props = json.loads(a.props) if a.props else None\n    stmts = statements(open(a.f).read()) if a.f else [a.text]\n    rc, first = 0, True\n    if a.json:\n        for s in stmts:\n            LAST.clear()\n            try:\n                run_mgmt(a.d, s, a) if s.lstrip().startswith(\'.\') else run_query(a.d, s, a)\n            except (KqlError, PartialError) as e:\n                print(\'Error: \' + str(e)); return 1\n        print(json.dumps(dict(cols=LAST.get(\'cols\', []), rows=LAST.get(\'rows\', [])), ensure_ascii=False))\n        return 0\n    for s in stmts:\n        if a.f:\n            if not first: print()\n            print(\'> \' + first_line(s))\n        first = False\n        try:\n            out = run_mgmt(a.d, s, a) if s.lstrip().startswith(\'.\') else run_query(a.d, s, a)\n            if out: print(out)\n        except PartialError as e:\n            print(str(e)); rc = 1\n            if not a.e: return 1\n        except KqlError as e:\n            print(\'Error: \' + str(e)); rc = 1\n            if not a.e: return 1\n    return rc\n\n\nif __name__ == \'__main__\':\n    sys.exit(main())\n')
KQL = '"%s" "%s"' % (sys.executable, os.path.abspath("kql.py"))   # commands below run it as: python kql.py ...
run(KQL + ' -d NetDefaultDB -q \'.create database shop persist (@"/kustodata/dbs/shop/md", @"/kustodata/dbs/shop/data")\'')
write('setup.kql', """\
.create table Sales (OrderId:long, Region:string, Customer:string, Email:string, Amount:real)

.ingest inline into table Sales <|
1001,East,lena,lena@example.com,120
1002,West,omar,omar@example.com,200
1003,East,priya,priya@example.com,80
1004,North,sam,sam@example.com,150
1005,West,kim,kim@example.com,95
1006,East,tom,tom@example.com,60

.create table RegionAccess (Principal:string, Region:string)

.create table PiiReaders (Principal:string)
""")
write('teamdbs.kql', """\
.create database finance persist (@"/kustodata/dbs/finance/md", @"/kustodata/dbs/finance/data")

.create database marketing persist (@"/kustodata/dbs/marketing/md", @"/kustodata/dbs/marketing/data")

.create database support persist (@"/kustodata/dbs/support/md", @"/kustodata/dbs/support/data")
""")
run(KQL + ' -q -f setup.kql')
run(KQL + ' -d NetDefaultDB -q -f teamdbs.kql')
run(KQL + ' -d finance -q \'.set-or-append Ledger <| print Account = "4000", Amount = 120.0\'')
run(KQL + ' -d marketing -q \'.set-or-append Campaigns <| print Campaign = "fall-sale", Clicks = 900\'')
run(KQL + ' -d support -q \'.set-or-append Tickets <| print TicketId = 1, Status = "open"\'')

# Step 1: Grant four Entra groups database roles, then list the principals
write('roles.kql', """\
.add database shop viewers
    ('aadgroup=sales-analysts@contoso.com') 'Sales analysts'

.add database shop ingestors
    ('aadgroup=order-loaders@contoso.com') 'Load pipelines'

.add database shop monitors
    ('aadgroup=platform-ops@contoso.com') 'Operations'

.add database shop unrestrictedviewers
    ('aadgroup=privacy-team@contoso.com') 'PII readers'
""")
run(KQL + ' -q -f roles.kql')

# Step 2: Row level security: a function plus the table policy; no mapping yet = no rows
write('rls.kql', """\
.create-or-alter function with (folder='Security') SalesRls() {
    Sales
    | where Region in ((RegionAccess
        | where Principal == current_principal()
        | project Region))
}

.alter table Sales policy row_level_security enable "SalesRls"
""")
run(KQL + ' -q -f rls.kql')
run(KQL + " 'Sales | count'")

# Step 3: Map the emulator identity (null identity) to East: only East rows come back
run(KQL + ' -q \'.set-or-append RegionAccess <| print Principal = current_principal(), Region = "East"\'')

# Step 4: The same RLS function masks the Email column for everyone who is not a PII reader
write('mask.kql', """\
.create-or-alter function with (folder='Security') SalesRls() {
    let me = current_principal();
    Sales
    | where Region in ((RegionAccess
        | where Principal == me | project Region))
    | extend Email = iff(me in ((PiiReaders | project Principal)),
        Email, "****")
}
""")
run(KQL + ' -q -f mask.kql')

# Step 5: Restricted view access cannot be enabled on a table that has row level security
run(KQL + " '.alter table Sales policy restricted_view_access true'", expect_error=True)   # EXPECTED TO FAIL: the video shows this error

# Step 6: An app connects with the Python SDK (emulator: no authentication) and RLS applies to it too
write('app.py', """\
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder

# emulator only: plain HTTP and no sign-in (never in Azure)
kcsb = KustoConnectionStringBuilder.with_no_authentication(
    "http://localhost:8080")
client = KustoClient(kcsb)

who = client.execute("shop", "print who = current_principal()")
print("principal:", who.primary_results[0][0]["who"])
seen = client.execute("shop", "Sales | summarize Orders = count()")
print("orders this app can see:", seen.primary_results[0][0]["Orders"])
""")
run('python app.py')

# Step 7: A callout policy that denies every web API call blocks the http_request plugin
write('callout.kql', """\
.alter cluster policy callout ```[{"CalloutType": "webapi",
    "CalloutUriRegex": ".*", "CanCall": false}]```
    | project Policy

evaluate http_request('https://rates.example.com/api/fx')
""")
run(KQL + ' --cell 120 -f callout.kql', expect_error=True)   # EXPECTED TO FAIL: the video shows this error

# Step 8: (wait until the engine has flushed its journal and query log)
run('for i in $(seq 1 60); do a=$(kql \'.show commands-and-queries | where Application == "app.py" | count\' | tail -1); j=$(kql \'.show journal | where EntityName == "SalesRls" | count\' | tail -1); [ "$a" -ge 2 ] && [ "$j" -ge 2 ] && break; sleep 5; done; echo audit logs flushed')

# Step 9: The journal: metadata changes on Sales and SalesRls
run(KQL + ' \'.show journal | where EntityName in ("Sales", "SalesRls") | project Event, EntityName, Command = substring(ChangeCommand, 0, 64) | order by Event asc, Command asc\'')

# Step 10: Commands and queries: what app.py ran, and as whom
run(KQL + ' \'.show commands-and-queries | where Application == "app.py" | project Application, Text, State, Principal | order by Text asc\'')

# Step 11: Three team databases: roles, workload groups, a request classification policy; one query per team
write('teams.kql', """\
.add database finance viewers ('aadgroup=finance-team@contoso.com')

.add database marketing viewers ('aadgroup=mkt-team@contoso.com')

.create-or-alter workload_group Finance ```{
  "RequestLimitsPolicy": {"MaxExecutionTime":
    {"IsRelaxable": false, "Value": "00:02:00"}},
  "RequestRateLimitPolicies": [{"IsEnabled": true,
    "Scope": "WorkloadGroup", "LimitKind": "ConcurrentRequests",
    "Properties": {"MaxConcurrentRequests": 10}}]}```

.create-or-alter workload_group Marketing ```{
  "RequestRateLimitPolicies": [{"IsEnabled": true,
    "Scope": "WorkloadGroup", "LimitKind": "ConcurrentRequests",
    "Properties": {"MaxConcurrentRequests": 5}}]}```

.alter cluster policy request_classification '{"IsEnabled":true}' <|
    case(request_properties.current_database == "finance", "Finance",
      request_properties.current_database == "marketing", "Marketing",
      "default")
""")
run(KQL + ' -q -f teams.kql')
run(KQL + " -d finance 'Ledger | count'")
run(KQL + " -d marketing 'Campaigns | count'")
run(KQL + " -d support 'Tickets | count'")

# Step 12: (wait until the queries show up in .show queries)
run('for i in $(seq 1 60); do n=$(kql \'.show queries | where Database in ("finance", "marketing", "support") | count\' | tail -1); [ "$n" -ge 3 ] && break; sleep 5; done; echo queries flushed')

# Step 13: Where each team query ran: its workload group
run(KQL + ' \'.show queries | where Database in ("finance", "marketing", "support") | project Database, Text, WorkloadGroup | order by Database asc\'')
Next in this series

Part 9: Operations, Monitoring and Integration

The sample data on this page is invented for teaching. Every terminal output is the real output of the command above it, run on the Kusto emulator (Kustainer, the Azure Data Explorer engine in a Linux container, build 2026.11.02). Features the emulator cannot show truthfully are shown as code. Part of the Real Time Azure Data Explorer and KQL Interview Questions and Answers series on TechBrothersIT. Features, limits and their status (GA or preview) are current as of November 2026; check the official Azure Data Explorer and Kusto documentation (learn.microsoft.com/azure/data-explorer and learn.microsoft.com/kusto) for anything you quote in an interview.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.