<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Judy Yang on Medium]]></title>
        <description><![CDATA[Stories by Judy Yang on Medium]]></description>
        <link>https://medium.com/@judy3.yang?source=rss-e8af258846a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hGpS5pGf4X-BVKkD</url>
            <title>Stories by Judy Yang on Medium</title>
            <link>https://medium.com/@judy3.yang?source=rss-e8af258846a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:47:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@judy3.yang/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What Makes a Data Platform AI-Ready?]]></title>
            <link>https://medium.com/@judy3.yang/what-makes-a-data-platform-ai-ready-f031a3bee4f2?source=rss-e8af258846a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f031a3bee4f2</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[semantic-layer]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Judy Yang]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 08:37:24 GMT</pubDate>
            <atom:updated>2026-11-23T08:37:24.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why I started thinking about this</h3><p>I’ve built a data discovery agent that works on metadata from a few thousand tables. Recently I’ve also been testing Metric Views and Genie on Databricks. Along the way, I realized that finding the right table and getting a metric right are two different problems.</p><p>Here is a simple example. In an order line table, each row is one item. Order A has two items, $80 and $20. Order B has one item, $140. Both orders come from the same customer. If the business asks “What is our average spend?”, you can get at least three numbers:</p><ul><li>Average of the three rows: $80. This is really the average price per item. The denominator is at the wrong level.</li><li>Per order: $240 ÷ 2 orders = $120.</li><li>Per customer: $240 ÷ 1 customer = $240.</li></ul><p>The first one is simply wrong. The other two both make sense, depending on how your company defines average spend. All three queries run fine, and the table schema won’t tell you which one to use.</p><p>These numbers are made up to show the point. My agent can narrow thousands of tables down to a few candidates. But finding the table or reading the column names won’t tell you what one row means, or whether the denominator should be orders or customers. If you let an LLM write SQL directly against the tables, it will likely pick one of these and give you an answer that looks reasonable but doesn’t match how the business defines the metric.</p><p>That made me rethink what <strong>AI-ready data</strong> actually means.</p><h3>AI-ready depends on the use case</h3><p>Gartner’s definition is narrower than many people think: the data has to fit a specific use case, you need to be able to show that it meets the use case’s requirements, and it has to be governed. [1] So there is <strong>no single company-wide standard</strong>, and AI-ready doesn’t mean “clean.” An anomaly detection model, for example, needs the outliers.</p><p>Instead of asking “Is our data AI-ready?”, ask “<strong>AI-ready for what?</strong>” This post focuses on one of the most common use cases: letting business users analyze structured data in plain language.</p><h3>Four concepts</h3><ul><li><strong>Metadata:</strong> What is this data? Descriptions, tags, owners, lineage.</li><li><strong>Semantic layer:</strong> How does the business calculate it? Dimensions, metric formulas, joins, synonyms.</li><li><strong>Ontology:</strong> How do business objects relate to each other? Often across systems; add it only when needed.</li><li><strong>Context layer:</strong> All of the above, plus live trust signals such as data quality, freshness, and access rules.</li></ul><p><strong>Metadata describes the data. A semantic layer models how the business uses it.</strong> Writing “item sale amount, in USD” on the amount column is metadata. Once the business decides that average spend is per order, locking in average spend = SUM(amount) / COUNT(DISTINCT order_id) is the semantic layer. In the example above, the point isn&#39;t whether the SQL runs. The business has to choose the denominator first, orders or customers, and then that definition is fixed so every question uses the same formula.</p><p>The core idea of a semantic layer: <strong>the metric formula is fixed, and the dimensions are chosen at query time.</strong> Whether you look at average spend by region, channel, month, or any mix of them, it uses the same definition.</p><p>“Context layer” is a term you hear more and more. The argument is that a semantic layer is necessary but not enough: AI also needs to know whether the data can be trusted right now and who is allowed to see it. [2] There’s no standard definition yet, so it helps to say what you mean when you use the term.</p><h3>Capability map</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*27k0QsXXIV4F2lsaNLwJqg.png" /><figcaption>AI-ready data platform capability map</figcaption></figure><p>The colors show priority for this use case, not build progress. Many of these capabilities also aren’t new for AI. Data ingestion, layered modeling, metadata, and data quality are core work that data platforms did long before AI, and many teams already have them. In practice, start by checking what you already have. Then ask whether it’s good enough for AI: Are the business descriptions complete? Is it clear what one row in each table represents? Are the definitions of core metrics locked in? Then fill the gaps.</p><p>Reading from the top down: questions come in through the AI entry points at the top. The context layer in the middle brings together the semantics, metadata, and trust signals that AI needs to understand and use the data. The data foundation at the bottom provides the raw material. Security, compliance, and evaluation apply to every layer.</p><p>I split AI entry points into two kinds of questions: <strong>finding data</strong> and <strong>asking for a metric</strong>. Finding data relies mostly on metadata, such as table and column descriptions, owners, lineage, query logs, and usage stats, with sample data when needed. It answers “Where is the data, what is it, and who owns it?” Asking for a metric works best on a semantic layer that the business has signed off on. It answers “What is this number?” The first covers a lot of ground but doesn’t promise that the business definition is right. The second covers only core metrics at first, but the definitions are clear and managed in one place. They can be two separate tools, or one chat box where the system figures out which kind of question it is and says what the answer is based on. The two aren’t fully separate, either: when answering a metric question, AI often still uses metadata to understand columns, check permissions, and see how fresh the data is. The split is just about being clear whose definition counts when you give someone a number.</p><p>A sensible flow looks like this: use data discovery to find candidate data, have someone who knows the business validate it and turn it into a semantic model, and then let business users run official metric analysis on that model. For questions the semantic model doesn’t cover, don’t present ad hoc SQL as the official number. If you allow queries on detail tables within the user’s permissions, clearly label the result as “exploratory.”</p><h3>A semantic layer needs ongoing upkeep. Now what?</h3><p>You can’t avoid the maintenance cost, but you can change how you approach it:</p><ol><li><strong>Start with core metrics.</strong> Only include metrics that must be consistent and get asked about often.</li><li><strong>Add plenty of dimensions, but keep metrics few and well defined.</strong> Define base metrics first, then build ratios from them.</li><li><strong>Be careful with fallbacks.</strong> If the semantic layer can’t answer a question, don’t pass off the result as official. Only answer from detail tables when permissions allow and the user is fine with an exploratory answer, and label it clearly.</li><li><strong>Grow based on real questions.</strong> If the same ad hoc query keeps coming up, agree on the definition and make it an official metric.</li><li><strong>Let AI draft; let people confirm the definitions.</strong> The SQL behind existing reports is a ready-made source of definitions.</li><li><strong>Treat semantics as code, owned by business domain.</strong> Manage it in YAML and Git, with the people who know each domain best in charge.</li></ol><p>The industry is moving the same way. Open Semantic Interchange, backed by Snowflake, Databricks, and other vendors, defines a vendor-neutral YAML format for semantic models. [3] The project was later renamed Apache Ossie and is now incubating at Apache. [4]</p><h3>How to get started</h3><p><strong>If you’re starting with a new business domain, first turn the P0 items in the map into a loop you can test:</strong></p><ol><li>A Gold table where it’s clear what one row represents</li><li>Column descriptions and sensitive-data tags</li><li>A semantic model with a few core metrics</li><li>A natural language analytics entry point that answers official metric questions from that model first</li><li>Data accessed as the user, plus clear rules on what data can be sent to the LLM</li><li>A set of test questions with agreed correct answers</li></ol><p>If this setup answers real business questions correctly, expand to more capabilities and other domains. <strong>Build in permissions and evaluation from day one.</strong> The later these problems show up, the harder they are to deal with.</p><h3>Closing thoughts</h3><p>Most of this isn’t new. Data quality, metadata, semantic models, governance: data teams have worked on these for years. What’s changed is that <strong>they used to be mainly for people, and now AI uses them too.</strong> When a person sees a vague column, they ask a colleague. AI doesn’t ask. It just gives you an answer that looks reasonable.</p><p>So being AI-ready really comes down to this: <strong>turn the business knowledge that lives in people’s heads and scattered reports into something machines can read, and that can be governed and checked.</strong> Get that right, and AI isn’t the only one that benefits.</p><h3>References</h3><ol><li>Gartner, <a href="https://www.gartner.com/en/articles/ai-ready-data"><em>What Is AI-Ready Data?</em></a></li><li>Atlan, <a href="https://atlan.com/know/ai-agent/semantic-layer-for-ai-agents/"><em>Semantic Layer for AI Agents</em></a></li><li>Snowflake, <a href="https://www.snowflake.com/en/blog/open-semantic-interchanges-specs-finalized/"><em>Open Semantic Interchange (OSI) Updates</em></a></li><li><a href="https://ossie.apache.org/">Apache Ossie (incubating)</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f031a3bee4f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Zero-to-One Guide to Automated Column Masking in Databricks Unity Catalog]]></title>
            <link>https://medium.com/@judy3.yang/a-zero-to-one-guide-to-automated-column-masking-in-databricks-unity-catalog-a56d0a6e24ec?source=rss-e8af258846a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a56d0a6e24ec</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-security]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[unity-catalog]]></category>
            <category><![CDATA[data-governance]]></category>
            <dc:creator><![CDATA[Judy Yang]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 05:46:23 GMT</pubDate>
            <atom:updated>2025-11-20T05:46:23.152Z</atom:updated>
            <content:encoded><![CDATA[<p>In data governance, we often face a dilemma: we need to give analysts access to data to generate value, but we must simultaneously prevent sensitive information (like Social Security Numbers, VINs, or GPS coordinates) from being exposed to unauthorized eyes.</p><p>Databricks Unity Catalog offers a powerful feature called <strong>Column Masking</strong>. However, if you are managing hundreds of tables, manually writing SQL commands (ALTER TABLE … SET MASK …) for every single column is a nightmare. It’s hard to maintain, error-prone, and makes auditing a headache.</p><p>In this article, I will share a <strong>Tag-Based Automated Workflow</strong>. Whether you have 10 tables or 10,000, this solution scales effortlessly.</p><h3>The Architecture: How It Works</h3><p>Instead of hard-coding masking rules directly onto columns one by one, we decouple the process into four logical layers:</p><ul><li><strong>Security Layer (Who?):</strong> Who has the right to see raw data? (Using <strong>Account Groups</strong>)</li><li><strong>Logic Layer (How?):</strong> How is the data masked? (Using <strong>SQL UDFs</strong>)</li><li><strong>Metadata Layer (What?):</strong> Which data needs protection? (Using <strong>Tags</strong>)</li><li><strong>Execution Layer (Automation):</strong> Automatically applying logic to tagged data. (Using <strong>Python</strong>)</li></ul><h4>Step 1: The Security Layer (Who sees what?)</h4><p>In Databricks, <strong>Account Groups</strong> are the cornerstone of secure permission control.</p><ul><li><strong>Why Account Groups?</strong> They are global. Even if a user is a Workspace Admin, they cannot modify the membership of an Account Group (unless explicitly authorized as a Group Manager). This prevents privilege escalation.</li></ul><p><strong>Action:</strong><br>Contact your Account Admin to create groups in the Databricks Account Console. For example:</p><ul><li>g_pii_unmask: Members can see raw PII (Personally Identifiable Information).</li><li>g_geo_unmask: Members can see raw GPS/Location data.</li></ul><h4>Step 2: The Logic Layer (Defining the Rules)</h4><p>We need to create <strong>User Defined Functions (UDFs)</strong> to define the masking logic. Think of this as a “filter” — only users in the specific groups can see through the filter to the original image.</p><p><strong>Action:</strong><br>Run the following code in your Databricks SQL Editor (I recommend creating a dedicated schema like main.governance for this):</p><pre>-- Scenario A: For ID-like info (VIN, SSN, Email) -&gt; Return SHA256 Hash<br>CREATE OR REPLACE FUNCTION main.governance.mask_id_sha256(val STRING)<br>  RETURNS STRING<br>  COMMENT &#39;Masks ID columns using SHA256 for unauthorized users.&#39;<br>  RETURN CASE<br>    WHEN is_account_group_member(&#39;g_pii_unmask&#39;) THEN val<br>    ELSE SHA2(val, 256)<br>  END;<br>-- Scenario B: For Coordinates/Descriptions (GPS) -&gt; Return NULL<br>CREATE OR REPLACE FUNCTION main.governance.mask_as_null(val STRING)<br>  RETURNS STRING<br>  COMMENT &#39;Returns NULL for unauthorized users.&#39;<br>  RETURN CASE<br>    WHEN is_account_group_member(&#39;g_geo_unmask&#39;) THEN val<br>    ELSE CAST(NULL AS STRING)<br>  END;</pre><blockquote><strong><em>Note:</em></strong><em> The return type of the UDF must match the data type of the column. If the column is STRING, the function must return STRING.</em></blockquote><h4>Step 3: The Metadata Layer (Tagging the Assets)</h4><p>Now, you don’t need to write complex ALTER TABLE statements. As a Data Steward, you simply identify which columns are sensitive and “tag” them.</p><p>We will use a Python helper function <em>tag_columns_by_name </em>(code provided in the Appendix) to do this in bulk.</p><pre># Define the assets to protect<br>tables_to_protect = [<br>    &#39;main.iot.vehicle_telemetry&#39;,<br>    &#39;main.sales.customer_profiles&#39;<br>]<br># Define the sensitive column names<br>sensitive_cols = [&#39;vin&#39;, &#39;gps_latitude&#39;, &#39;email&#39;, &#39;phone_number&#39;]<br># Apply the tag &quot;apply_masking=True&quot; in bulk<br>tag_columns_by_name(<br>    table_list=tables_to_protect,<br>    columns_to_tag=sensitive_cols,<br>    tag_key=&#39;apply_masking&#39;,<br>    tag_value=&#39;True&#39;<br>)</pre><h4>Step 4: The Execution Layer (Automation)</h4><p>This is where the magic happens. We run an automation script that reads a simple, human-readable <strong>Policy Configuration</strong>, finds all tagged columns, and applies the correct masking function automatically.</p><p><strong>Action:</strong></p><ul><li><strong>Define the Policy:</strong><br>Map tables and columns to their specific masking functions in a simple text block.</li></ul><pre># Format: Table Name | Column Name | Masking Function Name<br>policy_config = &quot;&quot;&quot;<br>main.iot.vehicle_telemetry   | vin           | main.governance.mask_id_sha256<br>main.iot.vehicle_telemetry   | gps_latitude  | main.governance.mask_as_null<br>main.sales.customer_profiles | email         | main.governance.mask_id_sha256<br>&quot;&quot;&quot;</pre><ul><li><strong>Run the Engine:</strong><br>Call the <em>apply_masking_policies_granular</em> function (code in Appendix).</li></ul><pre># Parse the config string<br>policy_map = parse_policy_string(policy_config)<br><br># Execute the automation<br>apply_masking_policies_granular(<br>    catalog_name=&#39;main&#39;,<br>    policy_map=policy_map,<br>    tag_name=&#39;apply_masking&#39;<br>)</pre><p><strong>Result:</strong> The script scans the system, identifies columns that are tagged but not yet protected, and executes the necessary ALTER TABLE … SET MASK commands.</p><h4>Step 5: Verification (Audit)</h4><p>“Trust, but verify.” Finally, we run a query to prove that all sensitive data is securely masked. We do this by joining the Unity Catalog system tables (information_schema).</p><p><strong>SQL Query:</strong></p><pre>SELECT<br>  ct.table_name,<br>  ct.column_name,<br>  -- Verification Status<br>  CASE<br>    WHEN cm.mask_name IS NOT NULL THEN &#39;✅ MASK APPLIED&#39;<br>    ELSE &#39;❌ NOT APPLIED - CHECK SCRIPT&#39;<br>  END AS status,<br>  cm.mask_name AS applied_function<br>FROM<br>  system.information_schema.column_tags ct<br>LEFT JOIN<br>  system.information_schema.column_masks cm<br>  ON ct.table_name = cm.table_name AND ct.column_name = cm.column_name<br>WHERE<br>  ct.tag_name = &#39;apply_masking&#39;;</pre><h3>FAQ &amp; Security Deep Dive</h3><p><strong>Q: If I am a Workspace Admin, can I add myself to the permission group and bypass the mask?</strong><br><strong>A: No.</strong> The is_account_group_member function checks membership at the <strong>Account Level</strong>. Even if you add the group to your workspace and add yourself to it locally, the function ignores these local workspace changes. This ensures separation of duties and high security.</p><p><strong>Q: I added a user to the group, but they still see masked data. Why?</strong><br><strong>A:</strong> Databricks caches permission data on clusters for performance. Changes typically take <strong>2–10 minutes</strong> to propagate. If you are testing and need immediate results, <strong>restart your Cluster or SQL Warehouse</strong> to force a cache refresh.</p><p>By adopting this workflow, we turn complex data security governance into a simple process: <strong>Tag -&gt; Configure -&gt; Run</strong>. Whether managing 10 tables or 1000, the complexity remains low, and the security remains high. Happy coding!</p><h3>Appendix: The Python Helper Functions</h3><p>Here are the reusable Python functions referenced above. Copy these into your Databricks notebook.</p><pre>from pyspark.sql.functions import col<br><br>def tag_columns_by_name(table_list: list,<br>                        columns_to_tag: list,<br>                        tag_key: str = &quot;apply_masking&quot;,<br>                        tag_value: str = &quot;True&quot;):<br>    &quot;&quot;&quot;<br>    Applies a specific tag to a list of columns across a list of tables.<br>    <br>    Args:<br>        table_list (list): List of fully qualified table names (e.g., [&#39;cat.schema.tbl1&#39;]).<br>        columns_to_tag (list): List of column names to tag (e.g., [&#39;vin&#39;, &#39;ssn&#39;]).<br>        tag_key (str): The key of the tag. Defaults to &quot;apply_masking&quot;.<br>        tag_value (str): The value of the tag. Defaults to &quot;True&quot;.<br>    &quot;&quot;&quot;<br>    print(f&quot;--- Starting tagging process for columns: {columns_to_tag} ---&quot;)<br>    <br>    if not table_list or not columns_to_tag:<br>        print(&quot;[WARN] Table list or column list is empty. Exiting.&quot;)<br>        return<br><br>    # Extract catalog name from the first table (assuming all tables are in the same catalog)<br>    try:<br>        catalog_name = table_list[0].split(&#39;.&#39;)[0]<br>    except IndexError:<br>        print(f&quot;[ERROR] Invalid table format: &#39;{table_list[0]}&#39;. Expected &#39;catalog.schema.table&#39;.&quot;)<br>        return<br><br>    # Format lists for SQL IN clause<br>    formatted_tables = &quot;, &quot;.join([f&quot;&#39;{t.split(&#39;.&#39;)[2]}&#39;&quot; for t in table_list])<br>    formatted_schemas = &quot;, &quot;.join(list(set([f&quot;&#39;{t.split(&#39;.&#39;)[1]}&#39;&quot; for t in table_list])))<br>    formatted_columns = &quot;, &quot;.join([f&quot;&#39;{c}&#39;&quot; for c in columns_to_tag])<br><br>    print(&quot;Querying information_schema to find matching columns...&quot;)<br>    <br>    try:<br>        # Find columns that actually exist in the target tables<br>        found_columns_df = spark.sql(f&quot;&quot;&quot;<br>            SELECT table_catalog, table_schema, table_name, column_name<br>            FROM system.information_schema.columns<br>            WHERE table_schema IN ({formatted_schemas})<br>              AND table_name IN ({formatted_tables})<br>              AND column_name IN ({formatted_columns})<br>        &quot;&quot;&quot;)<br>        columns_to_process = found_columns_df.collect()<br>    except Exception as e:<br>        print(f&quot;[ERROR] Failed to query information_schema. Error: {e}&quot;)<br>        return<br>        <br>    if not columns_to_process:<br>        print(&quot;No matching columns found in the specified tables.&quot;)<br>        return<br>        <br>    print(f&quot;Found {len(columns_to_process)} column(s) to tag. Applying tags...&quot;)<br>    <br>    for row in columns_to_process:<br>        full_table_name = f&quot;{row.table_catalog}.{row.table_schema}.{row.table_name}&quot;<br>        column = row.column_name<br>        try:<br>            spark.sql(f&quot;ALTER TABLE {full_table_name} ALTER COLUMN {column} SET TAGS (&#39;{tag_key}&#39; = &#39;{tag_value}&#39;)&quot;)<br>            print(f&quot;  [SUCCESS] Tag applied to: {full_table_name}.{column}&quot;)<br>        except Exception as e:<br>            print(f&quot;  [ERROR] Failed to tag {full_table_name}.{column}. Error: {e}&quot;)<br>            <br>    print(&quot;--- Tagging process finished ---&quot;)<br><br><br>def parse_policy_string(policy_string: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Parses a pipe-delimited multi-line string into a nested policy dictionary.<br>    <br>    Expected format per line:<br>    &#39;catalog.schema.table | column_name | catalog.schema.masking_function&#39;<br>    <br>    Args:<br>        policy_string (str): The raw configuration string.<br>        <br>    Returns:<br>        dict: A nested dictionary {table_name: {column_name: function_name}}<br>    &quot;&quot;&quot;<br>    policy_map = {}<br>    lines = policy_string.strip().splitlines()<br><br>    for i, line in enumerate(lines):<br>        cleaned_line = line.strip()<br>        # Skip empty lines or comments<br>        if not cleaned_line or cleaned_line.startswith(&#39;#&#39;):<br>            continue<br><br>        parts = [part.strip() for part in cleaned_line.split(&#39;|&#39;)]<br><br>        if len(parts) != 3:<br>            print(f&quot;[WARN] Skipping invalid line {i+1}: &#39;{line}&#39;&quot;)<br>            continue<br><br>        table_name, column_name, function_name = parts<br><br>        if table_name not in policy_map:<br>            policy_map[table_name] = {}<br>        <br>        policy_map[table_name][column_name] = function_name<br>        <br>    return policy_map<br><br>def apply_masking_policies_granular(catalog_name: str, <br>                                    policy_map: dict, <br>                                    tag_name: str = &#39;apply_masking&#39;):<br>    &quot;&quot;&quot;<br>    Applies masking functions to tagged columns based on a granular policy map.<br>    It is idempotent: it only applies masks to columns that are tagged but not yet masked.<br><br>    Args:<br>        catalog_name (str): The catalog name to operate in.<br>        policy_map (dict): Nested dict {table: {column: mask_function}}.<br>        tag_name (str): The tag key to look for. Defaults to &#39;apply_masking&#39;.<br>    &quot;&quot;&quot;<br>    print(&quot;--- Starting Automated Masking Process ---&quot;)<br><br>    if not policy_map:<br>        print(&quot;[ERROR] Policy map is empty.&quot;)<br>        return<br><br>    target_tables = list(policy_map.keys())<br>    formatted_tables = &quot;, &quot;.join([f&quot;&#39;{t}&#39;&quot; for t in target_tables])<br><br>    # Step 1: Find columns that are TAGGED but NOT YET MASKED<br>    # We join column_tags with column_masks to filter out already protected columns<br>    print(f&quot;\n[Phase 1] Identifying unprotected columns in {len(target_tables)} target tables...&quot;)<br>    try:<br>        tagged_columns_df = spark.sql(f&quot;&quot;&quot;<br>            SELECT<br>              ct.catalog_name, ct.schema_name, ct.table_name, ct.column_name<br>            FROM<br>              system.information_schema.column_tags AS ct<br>            LEFT JOIN<br>              system.information_schema.column_masks AS cm<br>              ON ct.catalog_name = cm.catalog_name<br>              AND ct.schema_name = cm.schema_name<br>              AND ct.table_name = cm.table_name<br>              AND ct.column_name = cm.column_name<br>            WHERE<br>              ct.tag_name = &#39;{tag_name}&#39; AND ct.tag_value = &#39;True&#39;<br>              AND CONCAT(ct.catalog_name, &#39;.&#39;, ct.schema_name, &#39;.&#39;, ct.table_name) IN ({formatted_tables})<br>              AND cm.mask_name IS NULL -- Only pick columns without an existing mask<br>        &quot;&quot;&quot;)<br>        columns_to_mask = tagged_columns_df.collect()<br>    except Exception as e:<br>        print(f&quot;[ERROR] Failed to query information_schema. Error: {e}&quot;)<br>        return<br>        <br>    if not columns_to_mask:<br>        print(&quot;  - No new unprotected columns found. System is secure.&quot;)<br>        print(&quot;--- Process Finished ---&quot;)<br>        return<br><br>    print(f&quot;  - Found {len(columns_to_mask)} new column(s) to mask.&quot;)<br><br>    # Step 2: Apply the masks<br>    print(&quot;\n[Phase 2] Applying masking functions...&quot;)<br>    applied_count = 0<br>    for row in columns_to_mask:<br>        full_table_name = f&quot;{row.catalog_name}.{row.schema_name}.{row.table_name}&quot;<br>        column = row.column_name<br>        <br>        # Lookup the specific function for this table and column<br>        if full_table_name in policy_map and column in policy_map[full_table_name]:<br>            mask_function = policy_map[full_table_name][column]<br>            <br>            print(f&quot;  - Applying mask &#39;{mask_function}&#39; to {full_table_name}.{column}&quot;)<br>            try:<br>                spark.sql(f&quot;ALTER TABLE {full_table_name} ALTER COLUMN {column} SET MASK {mask_function}&quot;)<br>                print(&quot;    [SUCCESS] Mask applied.&quot;)<br>                applied_count += 1<br>            except Exception as e:<br>                print(f&quot;    [ERROR] Failed to apply mask. Error: {e}&quot;)<br>        else:<br>            print(f&quot;  - [WARN] Column &#39;{column}&#39; is tagged but not defined in the policy map. Skipping.&quot;)<br><br>    print(f&quot;\nSummary: Successfully masked {applied_count} out of {len(columns_to_mask)} identified columns.&quot;)<br>    print(&quot;--- Process Finished ---&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a56d0a6e24ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running SQL Server Stored Procedures on Databricks Shared Clusters: The Ultimate Guide]]></title>
            <link>https://medium.com/@judy3.yang/running-sql-server-stored-procedures-on-databricks-shared-clusters-the-ultimate-guide-7cd273084f85?source=rss-e8af258846a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cd273084f85</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[pyspark]]></category>
            <dc:creator><![CDATA[Judy Yang]]></dc:creator>
            <pubDate>Wed, 19 Nov 2025 06:37:08 GMT</pubDate>
            <atom:updated>2025-11-19T06:37:08.283Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>How to bypass Py4JSecurityException errors without installing ODBC drivers.</strong></h4><p>If you are working within a Databricks <strong>Shared</strong> cluster or an environment with <strong>Unity Catalog</strong> enabled, and you’ve tried connecting to SQL Server to execute a Stored Procedure, you have likely hit this wall:</p><blockquote>Py4JSecurityException: Method public static java.sql.Connection java.sql.DriverManager.getConnection(…) is not whitelisted on class class java.sql.DriverManager</blockquote><p>Or, if you tried the standard JDBC approach, you might have encountered:</p><blockquote><strong><em>SQLServerException:</em></strong><em> Incorrect syntax near the keyword ‘SET’.</em></blockquote><p>This article explains why this happens and provides a universal PySpark code snippet to solve it perfectly.</p><h3>Why did your original code fail?</h3><p>In older Databricks versions or <strong>Single User</strong> mode, many developers were accustomed to using sc._gateway.jvm to directly call the Java java.sql.DriverManager to get a database connection.</p><p>However, in <strong>Shared Access Mode</strong> (which is the default and recommended mode for Unity Catalog), Databricks enforces a strict process isolation security policy:</p><ul><li><strong>Py4J Restrictions:</strong> To prevent users from escaping the sandbox, direct calls to underlying JVM methods (like java.sql.*) are blocked unless the method is explicitly whitelisted.</li><li><strong>Root Access Restrictions:</strong> You cannot use sudo apt-get install to install ODBC drivers. This means Python’s native pyodbc library usually cannot be used (unless an administrator configures complex Init Scripts).</li></ul><p><strong>Conclusion:</strong> You need a method that complies with the Databricks security whitelist while still being able to execute complex SQL (like EXEC, UPDATE). The answer is the native Spark <strong>JDBC API</strong>.</p><h3>The Challenges: Two “Traps” in Spark JDBC</h3><p>When we switch to using spark.read.jdbc, we encounter two tricky issues:</p><h4>1. The Syntax Trap</h4><p>If you try to execute a stored procedure like this:</p><pre># Wrong Approach<br>spark.read.format(&quot;jdbc&quot;).option(&quot;query&quot;, &quot;EXEC dbo.MyProc&quot;).load()</pre><p>You will get an error: Incorrect syntax near the keyword ‘EXEC’.<br>This is because Spark defaults to wrapping your SQL in a subquery: SELECT * FROM (EXEC dbo.MyProc) AS q. In T-SQL, EXEC statements are not allowed inside a FROM clause.</p><h4>2. The Lazy Evaluation Trap</h4><p>Even if you bypass the syntax error, Spark is <strong>lazy</strong>. If your stored procedure only updates data (Update/Insert) and returns no results, Spark might skip your execution logic entirely when it tries to infer the schema (often by adding WHERE 1=0). The code might run without errors, but nothing changes in the database.</p><h3>The Ultimate Solution: sessionInitStatement</h3><p>To solve the problems above, we need to utilize a lesser-known parameter in Spark JDBC: sessionInitStatement.</p><p>This parameter allows us to send a standalone SQL command <em>after</em> the JDBC session is established but <em>before</em> the main query is executed. This command is <strong>not</strong> wrapped in a subquery, making it perfect for SET, EXEC, and UPDATE.</p><h4>The Universal Code Wrapper</h4><p>Copy the function below into your Notebook. It handles both “Data Querying” and “Command Execution” scenarios.</p><pre>def run_sql_server_cmd(query, is_exec_only=False):<br>    &quot;&quot;&quot;<br>    Executes SQL Server statements compatible with Databricks Shared Clusters.<br>    <br>    :param query: Your SQL statement (SELECT, EXEC, UPDATE, etc.)<br>    :param is_exec_only: <br>           False (Default) -&gt; For queries (SELECT), returns a Spark DataFrame.<br>           True            -&gt; For operations with no return (EXEC/UPDATE/INSERT), returns Boolean.<br>    &quot;&quot;&quot;<br>    <br>    # Recommended: Store these sensitive values in Databricks Secrets<br>    jdbc_url = &quot;jdbc:sqlserver://&lt;YOUR_SERVER&gt;;databaseName=&lt;YOUR_DB&gt;&quot;<br>    user = &quot;&lt;YOUR_USER&gt;&quot;<br>    password = &quot;&lt;YOUR_PASSWORD&gt;&quot;<br>    <br>    # Basic Configuration<br>    options = {<br>        &quot;url&quot;: jdbc_url,<br>        &quot;user&quot;: user,<br>        &quot;password&quot;: password,<br>        &quot;driver&quot;: &quot;com.microsoft.sqlserver.jdbc.SQLServerDriver&quot;<br>    }<br><br>    try:<br>        # --- Mode A: Execute Action (Stored Procedure / Update / Insert) ---<br>        if is_exec_only:<br>            # Key Trick:<br>            # 1. Put the command in &#39;sessionInitStatement&#39; to bypass the subquery restriction.<br>            # 2. The main &#39;query&#39; is just a dummy SELECT 1 to satisfy Spark&#39;s read requirement.<br>            # 3. Add SET NOCOUNT ON to prevent the JDBC driver from getting confused by &#39;rows affected&#39;.<br>            exec_cmd = f&quot;SET NOCOUNT ON; {query}&quot;<br>            <br>            df = spark.read.format(&quot;jdbc&quot;) \<br>                .options(**options) \<br>                .option(&quot;sessionInitStatement&quot;, exec_cmd) \<br>                .option(&quot;query&quot;, &quot;SELECT 1 AS status&quot;) \<br>                .load()<br>            <br>            # CRITICAL: Force trigger the Action!<br>            # Without .head(), Spark&#39;s Lazy Evaluation might result in the SQL never being sent to the DB.<br>            df.head()<br>            <br>            print(f&quot;✅ Command executed successfully: {query[:50]}...&quot;)<br>            return True<br><br>        # --- Mode B: Fetch Data (SELECT) ---<br>        else:<br>            # Normal queries can be passed directly to the query parameter<br>            df = spark.read.format(&quot;jdbc&quot;) \<br>                .options(**options) \<br>                .option(&quot;query&quot;, query) \<br>                .load()<br>            return df<br><br>    except Exception as e:<br>        # Error Cleaning: Make the error message human-readable<br>        error_msg = str(e)<br>        if &quot;com.microsoft.sqlserver.jdbc.SQLServerException&quot; in error_msg:<br>            # Extract the real SQL error from the Java stack trace<br>            try:<br>                clean_error = error_msg.split(&quot;com.microsoft.sqlserver.jdbc.SQLServerException:&quot;)[1].split(&quot;\n&quot;)[0]<br>                print(f&quot;❌ SQL Server Execution Failed: {clean_error}&quot;)<br>            except:<br>                print(f&quot;❌ SQL Server Execution Failed: {error_msg}&quot;)<br>        else:<br>            print(f&quot;❌ Spark/Network Error: {e}&quot;)<br>        <br>        # Must raise the exception to stop the Notebook execution<br>        raise e</pre><h3>How to Use</h3><h4>Scenario 1: Querying Data (SELECT)</h4><p>Use it just like you normally use Spark. This returns a DataFrame.</p><pre>sql = &quot;SELECT * FROM Sales.Orders WHERE OrderDate &gt; &#39;2023-01-01&#39;&quot;<br>df = run_sql_server_cmd(sql, is_exec_only=False)<br><br>display(df)</pre><h4>Scenario 2: Executing Stored Procedures (EXEC)</h4><p>This is the critical part. Set the second parameter to True.</p><pre># Execute a Stored Procedure with parameters<br>proc_sql = &quot;EXEC dbo.UpdateDailyInventory @Date=&#39;2023-11-19&#39;&quot;<br># is_exec_only=True ensures it runs via sessionInitStatement and forces execution<br>run_sql_server_cmd(proc_sql, is_exec_only=True)</pre><h4>Scenario 3: Executing Update/Insert</h4><p>Similarly, set the parameter to True.</p><pre>update_sql = &quot;UPDATE Config SET IsActive = 1 WHERE ServiceName = &#39;ETL&#39;&quot;<br>run_sql_server_cmd(update_sql, is_exec_only=True)</pre><h3>Summary</h3><p>In Databricks Shared clusters, don’t try to “fight” the security mechanisms (like attempting to install drivers or hacking the JVM). Adapting to Spark’s design by utilizing the JDBC <strong>sessionInitStatement</strong> parameter is currently the most stable and compliant solution.</p><p>The advantages of this approach are:</p><ul><li><strong>No Admin Rights Needed:</strong> No need to configure Init Scripts or install pyodbc.</li><li><strong>Security Compliant:</strong> Uses the official Spark Whitelisted API.</li><li><strong>Universally Robust:</strong> Solves both the syntax errors and the “Lazy Evaluation” false-success issues.</li></ul><p>Happy Coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cd273084f85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Solutions for the WIZ Cloud Security CTF 2025]]></title>
            <link>https://medium.com/@judy3.yang/my-solutions-for-the-wiz-cloud-security-ctf-2025-df286430ee73?source=rss-e8af258846a------2</link>
            <guid isPermaLink="false">https://medium.com/p/df286430ee73</guid>
            <category><![CDATA[wiz]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[s3]]></category>
            <dc:creator><![CDATA[Judy Yang]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 03:36:54 GMT</pubDate>
            <atom:updated>2025-06-30T03:41:39.988Z</atom:updated>
            <content:encoded><![CDATA[<p>I just competed in the <a href="https://www.cloudsecuritychampionship.com/">WIZ Cloud Security Championship</a>, and it was a great experience! The challenges were really fun and gave me a much deeper appreciation for the attacker and defender perspectives in the cloud. I thought I’d recap my solution process for some challenges to share what I learned.</p><h3>June Challenge: Perimeter Leak</h3><blockquote><em>After weeks of exploits and privilege escalation you’ve gained access to what you hope is the final server that you can then use to extract out the secret flag from an S3 bucket.</em></blockquote><blockquote><em>It won’t be easy though. The target uses an AWS data perimeter to restrict access to the bucket contents.</em></blockquote><blockquote>chanllenge link: <a href="https://www.cloudsecuritychampionship.com/challenge/1">here</a></blockquote><ol><li>Upon gaining access to the server, the first logical step was to look for AWS credentials and assess my capabilities.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q4y64cR9tq_wV7wZ7VUImw.png" /></figure><p>2. No credentials. A classic start. The next step was to check the EC2 Instance Metadata Service (IMDS), the standard way for an EC2 instance to discover its own identity and IAM Role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTVyGktMhgsE6pqMJkQcbg.png" /></figure><p>3. Another dead end. This meant I couldn’t easily assume the instance’s IAM Role. Frustrated, I decided to check the environment variables for any clues. And there it was — the first breadcrumb.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNie-lNEiAEqG8yeEYqP3Q.png" /></figure><p>This single line of text opened up the entire attack surface.</p><p>4. The INFO_MSG gave me two critical pieces of information: a. <em>A Spring Boot application with Actuator endpoints was running. b. I had credentials to access it at a public URL.</em></p><p>I immediately accessed the <em>/actuator/env</em> endpoint, which dumps all environment and configuration properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9L0ovGR2biTK5hw4O65-DQ.png" /></figure><p>The massive JSON output contained a gem:</p><pre>”systemEnvironment”:{ “properties”:{ “BUCKET”:{ “value”:”challenge01–470f711&quot; } } }`</pre><p>I had the S3 bucket name: <em>challenge01–470f711</em>.</p><p>To understand my options, I then queried the /actuator/mappings endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vgjJZ7-7c-jkHzdKnQOdQ.png" /></figure><p>Buried in the standard Spring mappings was a custom, non-standard endpoint:</p><pre>{<br>    &quot;predicate&quot;: &quot;{ [/proxy], params [url]}&quot;,<br>    &quot;handler&quot;: &quot;challenge.Application#proxy(String)&quot;<br>}</pre><p>A proxy endpoint that takes a url parameter? This screamed <strong>Server-Side Request Forgery (SSRF)</strong>.</p><p>5. I now had a tool to make the server issue web requests on my behalf. After numerous failed attempts to use it, a hilarious but informative error message gave me the final clue:</p><pre>{<br>  &quot;status&quot;: 418,<br>  &quot;error&quot;: &quot;I&#39;m a teapot&quot;,<br>  &quot;message&quot;: &quot;This proxy can only be used to contact host names that match IP addresses or include amazonaws.com&quot;<br>}</pre><p>The rules of the game were clear. The /proxy endpoint had a whitelist: it would only make requests to <strong>IP addresses</strong> or URLs containing <strong>amazonaws.com</strong>.</p><p>6. The journey to gain credentials was a multi-step dance with IMDSv2, all performed through the /proxy SSRF. IMDSv2 requires a session token, obtained via a PUT request. Below is the encoded “url=http://169.254.169.25/lastested/api/token”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nyB_zrNaWg7N8DYY5M7tA.png" /></figure><p>6. Using the token, I could now query the instance’s IAM role and full <strong>AWS Credentials</strong>.</p><p>First, I queried for the IAM role name: …/iam/security-credentials/.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HZH2jwd_9v2cOtYlN2hdwg.png" /></figure><p>Then, I used the role name to query for the full temporary credentials: …/iam/security-credentials/&lt;role-name&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSgPc1KOQYXf-UzeV2dfCQ.png" /></figure><p>The result was a JSON object containing the AccessKeyId, SecretAccessKey, and SessionToken. I finally had an identity!</p><p>7. With my newly acquired credentials exported as environment variables, I felt unstoppable. I ran the command to download the targeted file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blCL16Lrcocw8y6j9l1OPA.png" /></figure><p>This was the “data perimeter.” The S3 bucket had a policy that explicitly denied access <strong>unless the request originated from a specific network path</strong>, almost certainly a VPC Endpoint.</p><p>My aws-cli requests, coming from the EC2 instance’s general internet path, were being blocked. I had the right “identity” but was walking through the wrong “door.”</p><p>What can I do now? The answer is S3 presigned url.</p><p>8. Using the credentials I’d stolen, I acted as an “officer” and generated a presigned URL for the flag.txt file. This URL is a self-contained, temporary “pass” that includes all necessary authorization information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzfqnUlYlbp7pr_CgXJG2g.png" /></figure><p>9. I then handed this “pass” to my “messenger,” the /proxy endpoint. The presigned URL’s hostname (…s3.us-east-1.amazonaws.com…) conveniently satisfied the SSRF’s amazonaws.com whitelist rule. I took the long presigned URL and URL-encoded it and I fed it into the /proxy endpoint.</p><pre># &lt;ENCODED_URL&gt; is the URL-encoded version of the presigned URL<br>curl &quot;https://ctf:88sPVWyC2P3p@challenge01.cloud-champions.com/proxy?url=&lt;ENCODED_URL&gt;&quot;</pre><p>Finally Success!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axROUBTkl15a336vMynpOw.png" /></figure><p>This challenge wasn’t about a single vulnerability, but about understanding and chaining together multiple cloud-native mechanisms:</p><ul><li><strong>Spring Boot Actuator</strong> for information disclosure.</li><li><strong>Server-Side Request Forgery (SSRF)</strong> as a pivot tool.</li><li><strong>IMDSv2</strong> as a security control that can be programmatically bypassed.</li><li><strong>S3 Bucket Policies</strong> and <strong>VPC Endpoints</strong> creating a robust data perimeter.</li><li><strong>S3 Presigned URLs</strong> as a way to separate authorization from the request’s origin.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df286430ee73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run sql procedure in databricks notebook]]></title>
            <link>https://medium.com/@judy3.yang/how-to-run-sql-procedure-in-databricks-notebook-e28023555565?source=rss-e8af258846a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28023555565</guid>
            <category><![CDATA[azure-sql-database]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[sql-procedure]]></category>
            <dc:creator><![CDATA[Judy Yang]]></dc:creator>
            <pubDate>Thu, 30 May 2024 08:17:58 GMT</pubDate>
            <atom:updated>2024-05-30T08:29:25.734Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m using Azure SQL database created some stored procedures and it need to be called in some situations. Here’s the code to run sql procedure or other sql query in the databricks notebook.</p><pre>def runSqlDBQuery(jdbc_url, query):<br>    # get the gateway/connection to py4j<br>    gateway = sc._gateway<br>    jvm = gateway.jvm<br><br>    # connection to the server<br>    con = jvm.java.sql.DriverManager.getConnection(jdbc_url)<br>    statement = con.prepareCall(query)<br>    statement.execute()<br>    metadata = statement.getMetaData()<br>    resultset = statement.getResultSet()<br><br>    # extract column names from metadata<br>    if metadata:<br>        columns = [metadata.getColumnName(i+1) for i in range(metadata.getColumnCount())]<br><br>        # loop through the result set and make into a list of lists<br>        rows = []<br>        while resultset.next():<br>            row = []<br>            for i in range(len(columns)):<br>                row.append(resultset.getObject(i+1))<br>            rows.append(row)<br><br>        con.close()<br>        df = spark.createDataFrame(rows, schema=columns)<br><br>        return df<br>    else:<br>        return resultset<br><br><br>if __name__ == &quot;__main__&quot;:<br>  query = &quot;EXECUTE dbo.PROCEDURE_NAME @Month = NULL, @Year = NULL, @RunDate = &#39;2024-05-30&#39;;&quot;<br>  db_jdbc_url = &quot;jdbc:sqlserver://{db_server_name}.database.chinacloudapi.cn:1433;database={database_name};user={your_user_name};password={your_password_here};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.chinacloudapi.cn;loginTimeout=30;&quot;<br>  result_df =  runSqlDBQuery(jdbc_url=db_jdbc_url, query=query)<br>  display(result_df)</pre><p>Above code will return the output of the query if there’s any.</p><p>Note: Above code can only be run in the single user access mode, otherwise it will give an error like below:</p><pre>py4j.security.Py4JSecurityException: Method public static java.sql.Connection java.sql.DriverManager.getConnection(java.lang.String) throws java.sql.SQLException is not whitelisted on class class java.sql.DriverManager</pre><p>The error reason is because the Unity Catalog limitation, more details can be find here: <a href="https://stackoverflow.com/questions/77658969/java-sql-driver-manager-not-working-in-unit-catalog">https://stackoverflow.com/questions/77658969/java-sql-driver-manager-not-working-in-unit-catalog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28023555565" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to configure external Hive meta store for Databricks SQL Warehouse Cluster on Azure Cloud?]]></title>
            <link>https://medium.com/@judy3.yang/how-to-configure-external-hive-meta-store-for-databricks-sql-warehouse-cluster-on-azure-cloud-4f1f9405a079?source=rss-e8af258846a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f1f9405a079</guid>
            <category><![CDATA[hive-metastore]]></category>
            <category><![CDATA[adls-gen2]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[sqlwarehouse]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Judy Yang]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 06:11:37 GMT</pubDate>
            <atom:updated>2023-08-24T06:23:36.697Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re going to migrate our data analysis tasks from Azure Hdinsight clusters to Azure databricks, in which the hdinsight cluster was using an external database(Azure sql server) as the hive metadata store and Azure datalake storage gen2(Adls gen2) as the HDFS. It would be necessary to reuse those resource under Databricks, including the hive meta store and adls gen2. (This is the situation that you’re not going to enable the Unity Catalog, Unity Catalog supports SQL warehouses by default.)</p><p>Below is the steps to configure Azure Databricks SQL warehouse cluster with the existing external hive meta store using UI.</p><h4>Step 1: Configure a service principal</h4><p>To configure access for your SQL warehouses to an Azure Data Lake Storage Gen2 storage account using service principals, follow these steps:</p><ol><li>Register an <a href="https://learn.microsoft.com/en-us/azure/databricks/storage/aad-storage-service-principal"><em>Azure AD application</em></a> and record the following properties:</li></ol><ul><li>Application (client) ID: An ID that uniquely identifies the Azure Active Directory application.</li><li>Directory (tenant) ID: An ID that uniquely identifies the Azure Active Directory instance (called directory (tenant) ID in Azure Databricks).</li><li>Client secret: The value of a client secret created for this application registration. The application will use this secret string to prove its identity.</li></ul><p>2. On your storage account, add a role assignment for the application registered at the previous step to give it access to the storage account. Here I’ve granted the contributor role to the new created Azure AD application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWHUWQ56w4LfDVywJOm0WA.jpeg" /></figure><p>3. Create an <a href="https://learn.microsoft.com/en-us/azure/databricks/security/secrets/secret-scopes#akv-ss">Azure Key Vault-backed secret scope</a> or a <a href="https://learn.microsoft.com/en-us/azure/databricks/security/secrets/secret-scopes#create-a-databricks-backed-secret-scope">Databricks-scoped secret scope</a>, and record the value of the scope name property:</p><ul><li>Scope name: The name of the created secret scope.</li></ul><p>4. If using the Azure Key Vault, go to the Secrets section and <a href="https://learn.microsoft.com/en-us/azure/databricks/security/secrets/secrets#key-vault-secret">create a new secret</a> with a name of your choice. Use the “client secret” that you have obtained in Step 1 to populate the “value” field of this secret. Keep a record of the secret name that you just chose.</p><ul><li>Secret name: The name of the created Azure Key Vault secret.</li></ul><p>5. If using a Databricks-backed scope, <a href="https://learn.microsoft.com/en-us/azure/databricks/security/secrets/secrets#create-a-secret-in-a-databricks-backed-scope">create a new secret</a> using the Databricks CLI and use it to store the client secret that you have obtained in Step 1. Keep a record of the secret key that you entered at this step.</p><ul><li>Secret key: The key of the created Databricks-backed secret.</li></ul><p>6. Click your username in the top bar of the databricks workspace and select Admin Settings from the drop down.</p><p>7. Click the SQL Warehouse settings tab.</p><p>8. In the Data Access Configuration field, click the Add Service Principal button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkCEbNOR4E7E5BlwoZdSvQ.jpeg" /></figure><p>9. Configure the properties for your Azure Data Lake Storage Gen2 storage account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mOIMGhTVQn8SdC_f.png" /></figure><p>10. Click Add. After it, you will find the configurations you made in the previous will shown text box as below:</p><pre>spark.hadoop.fs.azure.account.auth.type.YOUR_STORAGE_ACCOUNT_NAME.dfs.core.windows.net OAuth<br>spark.hadoop.fs.azure.account.oauth.provider.type.YOUR_STORAGE_ACCOUNT_NAME.dfs.core.windows.net org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider<br>spark.hadoop.fs.azure.account.oauth2.client.id.YOUR_STORAGE_ACCOUNT_NAME.dfs.core.windows.net YOUR_APP_APPLICATION_CLIENT_ID<br>spark.hadoop.fs.azure.account.oauth2.client.secret.YOUR_STORAGE_ACCOUNT_NAME.dfs.core.windows.net {{secrets/YOUR_SECRET_SCOPE_NAME/SECRET_NAME}}<br>spark.hadoop.fs.azure.account.oauth2.client.endpoint.YOUR_STORAGE_ACCOUNT_NAME.dfs.core.windows.net https://login.microsoftonline.com/YOUR_TENANT_ID/oauth2/token</pre><p><strong>NOTE: </strong>If you’re using regional azure service, you need to replace the auto generated url to your own region, otherwise, you will meet the error like this:</p><pre>Failure to initialize configuration for storage account YOUR_STORAGE_ACCOUNT_NAME.dfs.core.chinacloudapi.cn: Invalid configuration value detected for fs.azure.account.key</pre><p>for example if you’re using 21vnet Azure services, you need to replace below url to China recognized url:</p><pre>*.dfs.core.windows.net -&gt; *.dfs.core.chinacloudapi.cn<br>https://login.microsoftonline.com -&gt; https://login.partner.microsoftonline.cn</pre><h4>Step 2: Configure data access properties for SQL warehouses to integrate the existing Hive meta data store(Azure sql server).</h4><ol><li>Below is the example I used to connect to the hive meta store.</li></ol><pre>spark.hadoop.javax.jdo.option.ConnectionDriverName com.microsoft.sqlserver.jdbc.SQLServerDriver<br>spark.hadoop.javax.jdo.option.ConnectionURL {{secrets/YOUR_SECRET_SCOPE_NAME/HIVE_CONNECTION_STRING_SECRET}}<br>spark.hadoop.javax.jdo.option.ConnectionUserName {{secrets/YOUR_SECRET_SCOPE_NAME/HIVE_USERNAME_SECRET}}<br>spark.hadoop.javax.jdo.option.ConnectionPassword {{secrets/YOUR_SECRET_SCOPE_NAME/HIVE_USER_PASSWORD_SECRET}}<br>spark.sql.hive.metastore.jars /dbfs/FileStore/apache-hive-3.1.2-bin/lib/*<br>spark.sql.hive.metastore.version 3.1.2</pre><p>Note: please replace the value to your actual hive configurations. The hive connection string format is like below:</p><pre>jdbc:sqlserver://YOUR_SERVER_NAME.database.chinacloudapi.cn:1433;database=HIVEDATABASE;encrypt=true;create=false;trustServerCertificate=false;loginTimeout=30</pre><p>2. Click “Save changes”. Your SQL warehouse cluster will restart, and now you will find the metadata catalog will be availble when you run the queries.</p><p>Thanks for watching and leave your comments if you like and welcome to follow me!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f1f9405a079" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>