<?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 Tibor Vekony on Medium]]></title>
        <description><![CDATA[Stories by Tibor Vekony on Medium]]></description>
        <link>https://medium.com/@tiborvekony?source=rss-3ed469f03ece------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IXbAZHzu4fllHVf4eW8Lbg.jpeg</url>
            <title>Stories by Tibor Vekony on Medium</title>
            <link>https://medium.com/@tiborvekony?source=rss-3ed469f03ece------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:18:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tiborvekony/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[Azure Data Factory: A Simple Way to Reduce Costs]]></title>
            <link>https://tiborvekony.medium.com/azure-data-factory-a-simple-way-to-reduce-costs-1bc80c547e62?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bc80c547e62</guid>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[azure-cost-optimization]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 13:32:03 GMT</pubDate>
            <atom:updated>2024-10-25T09:16:40.573Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Data Factory: Best Practices to Reduce Costs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*6fY087nyOSCm96Kt.png" /></figure><h4>My Azure Data Factory Costs are too high!</h4><p>Many organizations using Azure Data Factory (ADF) have encountered a familiar scenario: what started as a cost-effective solution for process orchestration &amp; ETL workloads has unexpectedly turned into one of the most expensive resource in the Azure Cost Analysis report. At first, the consumption-based pricing model seems ideal. However, seemingly from nowhere, the costs can skyrocket, leaving teams scrambling to understand why.</p><p>There can be multiple reasons for rising costs, but one of the more obscure ones, that I’ve encountered quite a few times in my career (and after the most recent encounter, I’ve decided to write an article about it to raise awareness) can happen when ADF is used for monitoring some service, API or long running process by polling.</p><h4>What the Problem Looks Like?</h4><p>In many cases, developers have to interact with external services via ADF as part of a data pipeline. For example, an external process is started that has to finish before the pipeline can continue with the next steps. In these cases, usually a monitoring URL is returned in the response of the starting request, that can be used to monitor the process’ execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEvQWyiIIpYbt6Z1DOWUCA.png" /><figcaption>ADF Pipeline for Async Service</figcaption></figure><p>Seems simple enough, but the above pipeline would absolutely skyrocket Azure costs.</p><h4>But Why?</h4><p>Let’s take a look at <a href="https://azure.microsoft.com/en-us/pricing/details/data-factory/data-pipeline/">Microsoft’s documents to see how usage is billed</a> in ADF:</p><blockquote>Pipelines are control flows of discrete steps referred to as activities. You pay for data pipeline orchestration <strong>by activity run and activity execution by integration runtime hours</strong>. The integration runtime, which is serverless in Azure and self-hosted in hybrid scenarios, provides the compute resources used to execute the activities in a pipeline. <strong>Integration runtime charges are prorated by the minute and rounded up.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dI88mGlKZL16IWDsHb16gg.png" /><figcaption>Azure Data Factory Data Pipeline Pricing as of 2024–09–06.</figcaption></figure><p>The last sentence of the above quote is the key: Integration Runtime charges are rounded up by the minute. This means, that even if a Pipeline Activity is running for 59 seconds, 30 seconds or 1 second, Azure will still bill the user for a minute all the same. It’s important to understand, that <strong>the ADF bill depends on the number &amp; duration of activity runs, not on the runtime of a pipeline</strong>.</p><p>With this knowledge, let’s take another look at the same pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEvQWyiIIpYbt6Z1DOWUCA.png" /><figcaption>ADF Pipeline for Async Service</figcaption></figure><p>In the <strong>Until </strong>loop, every second a <strong>Web Activity </strong>would be executed. With each execution of the Web Activity, Azure would bill 1 minute of runtime, even if the activity only runs for a few seconds. At the theoretical 60 executions a minute (<em>theoretical, because in practice there is a bit of overhead when starting activities, which would reduce this</em>), that means 60 minutes of runtime billed for every 1 minute of monitoring, costs are incurred 60x faster.</p><h4>So What’s the Solution?</h4><p>There are a couple best practices to keep in mind when designing ADF Pipelines to keep costs to the minimum:</p><ul><li>When setting up polling for a monitoring scenario in a loop, ensure that the wait time is above 60 seconds. Try to check the metrics of previous runs &amp; set the Wait Activity’s wait time a bit above the average runtime of the monitored process.</li><li>Try to trim down the number of activities in pipelines &amp; in loops. That 1$/1000 Orchestration events (<em>Activity, Trigger &amp; Debug runs</em>) can add up quickly with a large number of complex, nested pipelines or if a pipeline is called repeatedly thousands of times.</li><li>If the runtime of the monitored process varies greatly from a few seconds to minutes or hours, use <a href="https://en.wikipedia.org/wiki/Exponential_backoff">exponential backoff</a>. Use a Variable in the Wait Activity’s wait time instead of hard-coding it to determine to number of seconds to wait &amp; in each cycle of the loop update that Variable.</li></ul><p>In general, ADF isn’t the best solution for sub-minute monitoring use cases, due to the billing model adopted by Azure. It can be done, just be ready to pay the bill.</p><p><strong><em>Thanks for reading my article! If you’d like to learn more interesting things, tricks &amp; tips about Microsoft Azure’s resources in the data space, please consider following me!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bc80c547e62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks: Merge Structured Stream Into SQL Server Table]]></title>
            <link>https://tiborvekony.medium.com/databricks-merge-structured-stream-into-sql-server-table-746b88cb8479?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/746b88cb8479</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 13:03:16 GMT</pubDate>
            <atom:updated>2023-09-15T13:03:16.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*yFZ_0wVJ-3aIZW7O.png" /></figure><h3>Summary</h3><p>While in the Databricks ecosystem it’s a lot easier to merge data from a Spark Structured Stream into a Delta Lake table &amp; really easy to connect to and use, sometimes I’m still coming across projects, where the business users don’t want to abandon their Relational Database (such as SQL Server) just yet, so they want the data streamed to the database — or sometimes both to the DB and a new Delta Lake table.</p><p>When I encountered this requirement for the first time, I couldn’t find an end-to-end description / demo of how to do it, so here is an example implementation that can be used as a starting point!</p><h3>Supported Outputs</h3><p>In the <a href="https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html">Spark Structured Streaming Documentation</a> (<em>link points to the latest — 3.5.0 as of writing this article</em>), there are 5 supported output sinks:</p><ul><li>File (<em>e.g.: writing the data to a parquet, orc, json, csv, etc. file</em>)</li><li>Apache Kafka</li><li>Console (<em>for debugging</em>)</li><li>Memory (<em>for debugging</em>)</li><li>ForEach</li></ul><p>Now, there isn’t a specific SQL Server — or even generic JDBC — output sink there, but there is the “ForEach” output sink. This Sink type can run arbitrary computation on the records in each microbatchs of the Structured Stream. Which means, we can do whatever we want, even run a <strong>MERGE</strong> SQL Statement on each microbatch, which as the name implies, merges the data into the SQL Server table.</p><p>By the way, the ForEach output type could be used to merge the data into an Oracle DB, send to a REST API, or really whatever is required.</p><h3>Step 1: Setup the Connection to the Database</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a87d2c49d7b7ec6b076be6b2c3800704/href">https://medium.com/media/a87d2c49d7b7ec6b076be6b2c3800704/href</a></iframe><p>Change the code accordingly, replacing the placeholders with the name of the SQL Server, the Database &amp; the credentials. The database connection will be established &amp; usable via the <strong>db_connection</strong> variable.</p><p>Via this approach, on Databricks no additional drivers need to be installed on the cluster or during the session.</p><h3>Step 2: Mappings / Configuration</h3><p>Instead of repeating code, I prefer to create generic, parameterized functions. In this case, a generic function which merges a microbatch to a SQL Server table.</p><p>The configuration below is just an example that I’ve used. Feel free to change it: add new things that you might need or remove things that you don’t. For merging, we’ll surely need a few things, like the target table, primary keys &amp; mappings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0b73e30df98236e3a61e0624be81f12/href">https://medium.com/media/d0b73e30df98236e3a61e0624be81f12/href</a></iframe><p><strong>Description of the Attributes:</strong></p><ul><li><strong>isActive</strong>: Boolean. If True, the configuration will be processed, if False, it’ll be skipped.</li><li><strong>sourceTable: </strong>Name of the source Delta Lake table. The contents of this table will be streamed &amp; merged into the <strong>targetTable</strong>.</li><li><strong>targetTable: </strong>Name of the target table in the SQL Server Database. The contents of the <strong>sourceTable</strong> will be merged into this table.</li><li><strong>primaryKeys: </strong>List of the columns in the microbatch &amp; the target table. Their names must be identical, so in the <strong>mapping </strong>make sure that the Delta Lake table’s primary keys columns are renamed to have the same names as the PKs of the <strong>targetTable</strong>.</li><li><strong>mapping: </strong>List of Spark expressions to be applied when the Delta Lake table’s contents are read. Essentially, transformations can be defined here to ensure that the microbatches that are passed into the merging function are in the correct format (schema).</li></ul><h3>Step 3: Merging Function</h3><p>Next, the function is defined, which will be executed for each microbatch of the Structured Stream. In this case, this is a function that merges the microbatch into the target table in the SQL Server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e238e70b7f6889db7bae191347efcdfa/href">https://medium.com/media/e238e70b7f6889db7bae191347efcdfa/href</a></iframe><p>The function has 3 main steps:</p><ol><li>Writes the microbatch’s contents to a newly created table on the SQL Server Database.</li><li>Executes the MERGE statement.</li><li>Drops the microbatch’s table.</li></ol><p>Some characteristics of the function, that you might want to fine-tune or change based on your needs:</p><ul><li>The microbatch tables are created with the epoch ID, which is a strictly monotonically increasing number, to ensure that each microbatch table’s name is unique.</li><li>The function expects a sequence column (<em>by default named as “__START_AT”</em>) which is used in the MERGE statement to filter out duplications from the microbatch. For example: if what we’re merging is a CDC feed and in the same microbatch there are 2 states for a given Customer, then only the latest state (<em>based on the sequence column</em>) will be merged.</li><li>The records in the target table are only updated, if the Epoch ID stored in the “UpdatedBy” column is lesser, than the microbatch’s Epoch ID that’s being merged. <em>See the WHEN MATCHED condition!</em></li><li>In the <strong>mapping</strong> configuration, leave the “UpdatedBy” as a static “&lt;epochId&gt;” string, if you plan on using the above described WHEN MATCHED condition, because in the insert that static string value is replaced by the current microbatch’s Epoch ID.</li></ul><h3>Step 4: Starting the Structured Streams</h3><p>Start a Structured Stream in parallel for each entry in the <strong>mapping</strong> variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5a40926f233a69837a501df4ef898ad/href">https://medium.com/media/c5a40926f233a69837a501df4ef898ad/href</a></iframe><p>At the very beginning, there is a test on the <strong>isActive</strong> attribute. If it’s False, then a stream won’t be started for that entry.</p><p>Next, a stream is started the entry — given that the <strong>isActive</strong> equals <strong>True</strong> — from the source Delta Lake table, selecting the data from it by executing the expressions defined in the <strong>mapping</strong> part of the configuration. This is the <strong>readStream()</strong> part.</p><p>Now that we have the data read as a stream, it can be written. In the <strong>writeStream() </strong>part we give it a user-friendly name, so it’s a lot easier to find in the Spark UI, if it needs to be monitored, define a checkpoint location so it becomes fault tolerant (<em>make sure to update the placeholder value!</em>) &amp; execute the <strong>mergeToSqlServer()</strong> function we defined in <strong>Step 3</strong>.</p><p>I’ve set the processing time to 30 seconds, but feel free to change that to one that suits your requirements!</p><p>After the stream is initialized, the loop waits for 45 seconds to make sure it’s fully initialized before it tries to start another one.</p><h3>Conlusion</h3><p>This is a pretty simple straightforward use case, but the foreachBatch / ForEach output sink type can be used to execute any arbitrary logic that’s needed: call APIs, merge to multiple sources, etc.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=746b88cb8479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Data Factory: Quick & Easy Releases with CI/CD]]></title>
            <link>https://medium.com/plumbersofdatascience/azure-data-factory-quick-easy-releases-with-ci-cd-bfbb15469108?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfbb15469108</guid>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 06:43:02 GMT</pubDate>
            <atom:updated>2022-09-06T06:43:02.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*kqWDgofDH1iFB4v8.png" /></figure><p><strong>What is a CI/CD Pipeline?<br>CI</strong> stands for <strong>C</strong>ontiunous <strong>I</strong>ntegration, which is the practice of automatically testing any change made to the codebase as early as possible, to get feedback ASAP, if something breaks, due to the changes.</p><p><strong>CI</strong> is followed by <strong>CD</strong>,<strong> </strong>which stands for <strong>C</strong>ontinuous <strong>D</strong>elivery: pushing the actual changes to the various environments one might have, such as Test, Pre-Production &amp; Production.</p><p>A <strong>CI/CD Pipeline </strong>is a series of steps that must be performed in order to deliver a new version of software, a practice focused on improving software delivery throughout the software development life cycle via automation.</p><p>It allows organizations to develop higher quality code, faster, by reducing the manual labour of testing &amp; deployment of changes.</p><p><strong>Release Time!<br></strong>Most companies do releases on a schedule: daily, weekly, monthly or something custom, after a period of developing new features is over, the changes have to be neatly packaged &amp; released to the various environments. First, to the Test environment, to thoroughly test the software, then, if everything checks out, to the (Pre-)Production environment.</p><p>In the past, making sure that each new feature and change, with every component &amp; dependency would make its way to the various environments took significant time, effort &amp; planning, if done manually.</p><p>In this article, I’ll showcase the <strong>CD</strong> part of a CI/CD Pipeline built for Azure Data Factory. <em>The CI part will be in the next article, so make sure to stick around, if you’re curious about automating the testing of ADF pipelines!</em></p><p><strong>Quick &amp; Easy Release<br></strong>Sure, the setup of the CI/CD Pipeline might take 30–60 minutes, but it’ll save a lot of time &amp; effort down the line! With it, the deployment of code changes in ADF won’t take more than a few clicks &amp; a few minutes of waiting for the deployment to finish: simply add a version tag to a branch, the rest will be handled by the pipelines!</p><p>There are 3 steps to take:</p><ul><li><em>Setting up the Build Pipeline</em></li><li><em>Setting up the Scripts &amp; Environment Variables</em></li><li><em>Setting up the Release (CD) Pipeline</em></li></ul><p><strong>Step 1)<br>Setting up the Build Pipeline<br></strong>I’ll use Azure Pipelines to build the ARM templates that’ll be used during Deployment, from the ADF’s Repo (which, in my case, is an Azure DevOps Repo):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*wjntbKjvnXdq-7gtDIQVFA.png" /><figcaption>ADF Repo Structure: the object definitions of ADF are under the “ADF” folder, and there is a new “Build” folder, that contains resources related to the CI/CD Pipeline.</figcaption></figure><p><em>The Repo could be a GitHub Repo, and the Build Pipeline uses NPM to generate the ARM Templates, so anything that can use that can be used instead of Azure Build Pipelines.</em></p><p>The Build Pipeline’s definition is the file with the .yml extension. It can be kept anywhere in the repo, but I like to have a “Build” folder dedicated to resources used in the CI/CD Pipeline, such as environment-specific values (“EnvironmentParameters”) and small PowerShell scripts to automate certain tasks during Deployment (“Scripts”).</p><p>There is also that “package.json” file, it’s important that it’s kept in the same directory as the .yml file. Its name &amp; content isn’t optional either, it must be “package.json”, with the content below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bca80d02a5e38dce172b32f5c3d7c0b/href">https://medium.com/media/9bca80d02a5e38dce172b32f5c3d7c0b/href</a></iframe><p>The “adf-build-pipeline.yml” contains the definition of the Build Pipeline, that’ll build the ARM templates from the object definitions, located in the “ADF” folder. It’s a variation of the <a href="https://docs.microsoft.com/en-us/azure/data-factory/continuous-integration-delivery-improvements?source=recommendations#create-an-azure-pipeline">Azure Build Pipeline from MS Docs</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9aa39e5986fffa05857eb80a8e4d39b/href">https://medium.com/media/e9aa39e5986fffa05857eb80a8e4d39b/href</a></iframe><p>I’ve added some comments to the original by Microsoft, and changed a few parts of it:</p><ul><li>The Build Pipeline is triggered, when a branch is tagged with a version tag (e.g.: v1.0.0), instead of pushes to the Main branch. This enables to Build any branch’s contents or even a historic state, by tagging it, instead of just the Main branch.</li><li>Instead of defining PowerShell Scripts inline in the CD (Release) Pipeline later on, I have the scripts stored in the Repo &amp; I’m including them in the Artifact, so I can access them later in the CD Pipeline. Same goes for the environment-specific parameters.</li><li>Instead of hard-coding the Resource ID to the ADF that’s linked to our Git Repo — in most cases this is the DEV ADF — I’m using a variable “$(adfResourceId)” in the NPM steps.</li></ul><p>If you’re happy with this behaviour, copy-paste the “adf-build-pipeline.yml” file to the Build folder &amp; commit it to the Repo!</p><p>Next, go to Azure Devops → Pipelines → Build, and create a new pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*R4-uJ57hy5SmK9EYzbP2vw.png" /><figcaption>Azure DevOps Build Pipelines -&gt; New Pipeline.</figcaption></figure><p>Select the Repo, where the ADF code* is stored, then on the “Configure” step, make sure to select the “Existing Azure Pipelines YAML file” option. Previously, the “adf-build-pipeline.yml” file was added to the Repo, so it should show up.</p><p>*<em>I know it’s not really code, but a bunch of json files, still I’ll refer to them occasionally as code, because it’s easier than writing “ADF object definitions in json format” each time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*kRTHLtoPTurc0kPf7-YaRg.png" /><figcaption>“Configure” step of Creating a New Build Pipeline. This option was towards the bottom of options for me, scroll down a bit if you can’t find it!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*Mub2F55IijqnOO3sSlmTmQ.png" /><figcaption>Select the “adf-build-pipeline.yml” file that you’ve added to the Build folder!</figcaption></figure><p>Before the new pipeline is saved, make sure to add the “adfResourceId” variable to it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*LcpklTM5FP_ywTy-8Dt5LQ.png" /><figcaption>Set Variables for the Build Pipeline.</figcaption></figure><p>This variable is the Resource ID of the ADF linked to the Repo:<br><em>“/subscriptions/&lt;SubscriptionId&gt;/resourceGroups/&lt;ResourceGroupName&gt;/providers/Microsoft.DataFactory/factories/&lt;NameOfADF&gt;”</em></p><p>After the variable was set, the pipeline can be saved by clicking on the arrow on the right-side of the Run button. It can be tested if everything was setup correctly, by running the pipeline, using the Run button, or by tagging a branch in the ADF Report with a version tag, if the trigger condition was kept as it was in the .yml file.</p><p><strong>Step 2)<br>Setting up the Scripts &amp; Environment Variables</strong></p><p>In the Repo, PowerShell scripts &amp; environment-specific parameters can be stored, that’ll be included alongside the ARM Templates generated from the ADF code.</p><p><strong>Scripts:<br></strong>Fortunately for us, <a href="https://github.com/oramoss">Jeff Moss</a> has a public GitHub Repo with <a href="https://github.com/oramoss/code-library/tree/master/powershell">a bunch of great PowerShell scripts</a> (<em>among other things, such as IaC, Databricks, SQL, Bicep, etc. — I highly recommend to check it out!</em>)</p><p>For the CI/CD Pipeline, 2 of his PowerShell scripts will be needed:</p><ul><li>SetADFTriggersState.ps1</li><li>RemoveOrphanedADFResources.ps1</li></ul><p>Download these &amp; add them to the Repo’s “Scripts” folder.</p><p>If you don’t want to use Jeff’s scripts, Microsoft recommends <a href="https://github.com/Azure/Azure-DataFactory/blob/main/SamplesV2/ContinuousIntegrationAndDelivery/PrePostDeploymentScript.Ver2.ps1">this script</a> (at the moment) in their documentation.</p><p><strong>Environment Parameters:<br></strong>The environment-specific parameters are .json files, in the “deploymentParameters” schema defined by Microsoft:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df03a73d1628f8fca5a3b38b7e9b8b76/href">https://medium.com/media/df03a73d1628f8fca5a3b38b7e9b8b76/href</a></iframe><p>In this one, I only specify 2 parameter value overrides:</p><ul><li>The name of the ADF resource</li><li>The location/region of the ADF resource</li></ul><p>For the rest of the parameters — if there are any — the default values will be used.</p><p>To find out what parameters are available, check the “ARMTemplateForFactory.json” or “ARMTemplateParametersForFactory.json” files generated by the Build Pipeline!</p><p><strong>Step 3)<br>Setting up the Release (CD) Pipeline<br></strong>First, create a new Release Pipeline in Azure DevOps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*UhU6cSdySOxYil0ojYR3VQ.png" /><figcaption>Creating a new Release (CD) Pipeline in Azure DevOps.</figcaption></figure><p>If a prompt appears to select a template, select to start with an empty job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*iXKfeKEBz3aU_6OWIW2OwA.png" /><figcaption>Selection to start with an empty Release Pipeline.</figcaption></figure><p>First, we have to add the Artifact created by the Build Pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*x0egDKAGMKTJctMV7DzvzQ.png" /><figcaption>Add an Artifact to a Release Pipeline.</figcaption></figure><p>Note the lightning symbol on the upper-right corner of the Artifact. That’s the Continuous Deployment trigger. To reiterate the setup so far: whenever a branch is tagged with a version number, the Build Pipeline will start, creating a new Artifact. This CD trigger will fire, whenever a new Artifact is available, starting a Release, which will deploy the ARM templates of the ADF to the various environments.</p><p>Let’s add the Artifact &amp; setup the CD trigger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*6lXJY196neoNmY4R9Vv1JQ.png" /><figcaption>Adding an Artifact to the Release Pipeline.</figcaption></figure><p>For the “Source (build pipeline)” select the Build Pipeline created in the previous step. The “Source alias” will be a name, that can be used to reference the Artifact within the Release Pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*oM_t_VDPDk0uDYu6pm47zA.png" /><figcaption>Setup of the CD trigger: create a Release every time a new Artifact is available, created by the Build Pipeline.</figcaption></figure><p>Besides the CD trigger, additional filters can be defined, if additional restrictions have to be made, e.g.: only version tags on specific branches should trigger a Release or instead of version tags, Pull Requests (PRs) should trigger a release. Note, that if PRs should trigger a Release, the Build Pipeline should be modified accordingly to build the ARM templates when a PR is completed.</p><p>I prefer version tags, because it still can control when a batch of changes are released, but the two approaches could be mixed as well:</p><ul><li>For the Test environment, the CD trigger could be configured to deploy changes after every PR, to allow QA to test changes as soon as possible.</li><li>For the Production environment, the CD trigger could be configured to deploy changes only when a version tag is added to a branch, to keep a consistent release schedule &amp; make sure half-baked features won’t be released.</li></ul><p>Once the Artifact &amp; CD trigger is added and configured, next, the actual Release process has to be defined in the Stages. For example, each environment can be a Stage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FaNxifB20kpBNy9GMxgZhw.png" /><figcaption>Agent Job definition in the “Production” release stage. Make sure “azureps” is added as a demand/dependency to the Agent.</figcaption></figure><p>In each Stage, there is an (Agent) Job, which has 4 steps. Click on the “+” sign, on the right-hand side of the Agent Job to add steps/tasks: <strong>3 Azure PowerShell</strong> &amp; <strong>1 ARM Template Deployment</strong> task(s) in total:</p><ul><li><strong>Stopping the Triggers in the target environment’s ADF</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*c2I1SwEz-vMhjOfZ93XrJQ.png" /><figcaption>Azure PowerShell “Stop Triggers” task’s configuration.</figcaption></figure><p>Using the 3 dots button on the right-hand side, pick the “SetADFTriggersState.ps1” script from the Artifact.</p><ul><li><strong>Deploying the ARM templates</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*knDMfEzGRRNzY4D4_weoVA.png" /><figcaption>ARM Template Deployment task: “Azure Details” section’s configuration.</figcaption></figure><p>The “Azure Details” part of the configuration should be straightforward: select the Subscription, Resource Group &amp; Location details of the Target Environment/ADF. The Action should be “Create or Update Resource Group”. The Deployment Scope is “Resource Group”.</p><p>If an Azure Resource Manager connection isn’t available yet, click on the “Manage” link to create one. <strong>Note that this requires elevated permissions, so the help of an administrator might be needed</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*K-XCKRHg9nQzXa6G6TpSGw.png" /><figcaption>ARM Template Deployment task: “Template” section’s configurations.</figcaption></figure><p>Once the Connection-related configuration is done, in the “Template” part of the configuration the ARM Template (of the ADF) is given that will be deployed to the target. For the “Template” select the “ARMTemplateForFactory.json” file. As for the “Template Parameters”, select the file from the EnvironmentParameters folder of the Artifact, that was created earlier for the target environment.</p><p>The Template Location is either Linked Artifact (in this case it’ll use the ARM Template that’s in the Artifact, built by the Build Pipeline), or “URL of the file”, which takes an URL to the ARM Template to be deployed. This comes down to size: if an ADF’s ARM Template is too large and/or it uses Linked Templates, then it can’t be deployed directly using the “Linked Artifact” option. First, it needs to be uploaded to some kind of storage (e.g.: an Azure Storage Account’s blob storage), then deployed from there. [<a href="https://docs.microsoft.com/en-us/azure/data-factory/continuous-integration-delivery-linked-templates">More Info</a>]</p><p><strong>Make sure the Deployment Mode is “Incremental”!</strong> If left on “Complete”, the Resource Group will be overwritten &amp; any resource not part of the ARM Template (in this case, everything besides the ADF) will be deleted!</p><ul><li><strong>Cleaning up the “Orphaned” Resources</strong></li></ul><p>These are objects (pipelines, datasets, etc.) in ADF, which were deleted in the development phase. Since the deployment is incremental, these wouldn’t be deleted. For these resources to be deleted in the Target ADF as well, a PS script is executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*ZaWUAR1yIqUzwREY4HO7zQ.png" /><figcaption>Azure PowerShell “Delete Orphaned Resources” task’s configuration.</figcaption></figure><ul><li><strong>Re-starting the stopped Triggers in the Target ADF.</strong></li></ul><p>Once the ARM Templates were deployed &amp; the orphaned resources cleaned-up, the Triggers in ADF, stopped as the first step, can be re-started again. Same script as in the first task, just with a different “State” script argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*E0B6LyOqAjvI_Qa1mn7nqw.png" /><figcaption>Azure PowerShell “Restart Triggers” task’s configuration.</figcaption></figure><p>In case something goes wrong &amp; the deployment fails, the triggers should be restarted, so in the “Control Options” section, set it up to run even if a previous task (e.g.: the ARM Template Deployment) fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*gkSZPwt4AxCs3NXF3mYm9Q.png" /><figcaption>Azure PowerShell “Restart Triggers” task’s Control Options configuration.</figcaption></figure><p>…And that’s it!</p><p>It wasn’t short, but it wasn’t too difficult either! I promise, over the coming months, with each release, this CI/CD pipeline can save a lot of headache, compared to manually releasing/deploying ARM Templates between environments!</p><p><strong><em>If you’d like to learn more interesting things, tricks &amp; tips about Microsoft Azure’s resources in the data space, please follow me!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfbb15469108" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plumbersofdatascience/azure-data-factory-quick-easy-releases-with-ci-cd-bfbb15469108">Azure Data Factory: Quick &amp; Easy Releases with CI/CD</a> was originally published in <a href="https://medium.com/plumbersofdatascience">Plumbers Of Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Data Factory: Connect to Multiple Resources with One Linked Service]]></title>
            <link>https://medium.com/plumbersofdatascience/azure-data-factory-connect-to-multiple-resources-with-one-linked-service-47310423aba6?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/47310423aba6</guid>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[etl]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 15:42:48 GMT</pubDate>
            <atom:updated>2022-03-05T21:22:37.748Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*ASwr9uY2CqEMFMo5vXFKUw.png" /></figure><h4><strong>What is Azure Data Factory (ADF)?</strong></h4><p><strong>A</strong>zure <strong>D</strong>ata <strong>F</strong>actory (ADF) is a service on the Microsoft Azure platform. It is a fully managed, no-code (<em>just drag &amp; drop components onto a canvas</em>), serverless (<em>somewhat of a misnomer, but </em>— <em>servers are taken care of by Microsoft, costs are consumption-based, computing power allocated on demand</em>), integration service to build &amp; orchestrate ETL/ELT pipelines.</p><h4><strong>Problem Statement</strong></h4><p>In certain situations, data might need to be pulled from a large number of services / locations. In such situations, given the number of services are large enough, it’s not feasible to create &amp; maintain a dedicated Linked Service for each one of them in ADF.</p><p>For example, let’s say we have an application, where each client has its own Azure SQL Database in the backend of the application, where their data is stored. These databases might be spread across a number of Azure SQL Servers as well. Each client also has its own dedicated Azure Blob Storage.</p><p>We need to connect to each client’s database in the backend &amp; extract some data from a few tables, then place it into the respective client’s Azure Blob Storage.</p><h4><strong>Solution</strong></h4><p>In short, the solution is to create generic / parameterized resources in ADF (Linked Services, Datasets, Pipelines), which we can use and re-use, to do a type of task without explicitly defining the details.</p><p>Think of a function that takes 2 numbers as input parameters and adds them. Since we don’t know upfront all the numbers we might want to add in the future, we define the numbers to add as input parameters of this function, so we can provide the actual numbers we’d like to add, when they are known.</p><p>The same approach is used in ADF as well. Instead of defining exactly which Database the process should connect to, which table should be queried for data, and to where the data should be written, we define the process: connect to an Azure SQL Database, query a table in it &amp; export the results of the query to an Azure Blob Storage.</p><h4><strong>Step 1)<br>Create the Generic Linked Services</strong></h4><p>First, create a single generic / parameterized Azure SQL Database Linked Service, which we can use to connect to different Azure SQL Databases, based on the parameters we give the Linked Service when we use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*LuHFlWYxm2fnWve9IV2z_w.png" /><figcaption>Create a new Azure SQL Database Linked Service in ADF.</figcaption></figure><p>Let’s define parameters, which will be used to supply the Fully qualified domain name (FQDN) of the server, the database name, as well as the username and password combination used for authentication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*3925rgOmbT83x8qiQg-_Gw.png" /><figcaption>Parameters defined on the Generic Azure SQL Database Linked Service.</figcaption></figure><p>These parameters are used in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*0hKTzmx1Awiyfj86R9WEsQ.png" /><figcaption>Usage of the Parameters defined on the Generic Azure SQL Database Linked Service.</figcaption></figure><p><strong><em>Tip: </em></strong><em>If the connection string to the database and/or the credentials are stored in Azure Key Vault, the name of the secret to fetch can be parameterized the same way as well, providing security, besides the efficiency &amp; reusability of this approach!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*6m64eLl-0xgMPlrNVRW0zQ.png" /><figcaption>Generic Azure SQL Database Linked Service with the Secret to fetch from AKV parameterized.</figcaption></figure><p>I’ll follow best practices &amp; use the approach where the server’s connection string (<em>which includes the server FQDN, the database name, as well as the credentials and possible other connection details</em>) is stored in Azure Key Vault (AKV).</p><p>[ <a href="https://tiborvekony.medium.com/azure-data-factory-keep-your-secrets-in-azure-key-vault-fb9d0bbc5ca4">If you aren’t sure how to connect ADF to AKV, read my article on the topic!</a> ]</p><p>Similarly, to how we created a Generic Linked Service to connect to different Azure SQL Databases, depending on which secret (Connection String) from AKV we specify to be used to establish the connection, we can create a Generic Azure Blob Storage Linked Service as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*XMMgw2AUE0Os6evoHvXXbw.png" /><figcaption>Generic Azure Blob Storage Linked Service in ADF.</figcaption></figure><p>In this case, we store the Connection String to the Azure Blob Storage in AKV. These can be found here, on the Azure Blob Storage resource:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*ZWxwpPxqCMM7En4CxpYC0Q.png" /><figcaption>Account Keys &amp; Connection Strings to the Azure Blob Storage, on Azure Portal.</figcaption></figure><h4><strong>Step 2)<br>Create Generic Datasets, using the Generic Linked Services</strong></h4><p>In this step, we’ll create some Generic Datasets, that are using the Generic Azure SQL Database &amp; Azure Blob Storage Linked Services we created in the previous step!</p><p>First, let’s create a Generic Azure SQL Database Table Dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*DHgImmDfmxpbG2DWRI3UYg.png" /><figcaption>Parameters defined for the Generic Azure SQL Database Table Dataset in ADF.</figcaption></figure><p>I defined 3 parameters:</p><ul><li><strong>“lsConnectionStringSecretName”: </strong>This parameter has the same name as the one we defined in the Generic Azure SQL Database Linked Service. It could be different, I used the same name because later on when we supply the values it’s easier to identify where the value we provide will be consumed/used. This way, I can look at the prefix (“ls”) and tell it’ll be used in the <strong>L</strong>inked <strong>S</strong>ervice.<br>It’s value will be the name of the Secret in AKV, which holds the connection string to the Azure SQL Database.</li><li><strong>“dsTableSchema”:</strong> This parameter’s value will be the schema of the table in the Azure SQL Database.</li><li><strong>“dsTableName”: </strong>Finally, this will get the name of the table in the Azure SQL Database.</li></ul><p>In the “Connection” tab of the Dataset, I used the parameters the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*73s_ioa7-08F25buMVX1ug.png" /><figcaption>Usage of the Parameters defined in the Generic Azure SQL Database Table Dataset.</figcaption></figure><p>Note, that there is a menu called “Linked service properties”. This is normally not there, if the Linked Service used in the Dataset doesn’t have any parameters. In this field, we can pass values supplied to the Dataset as parameters, as input parameters to the Linked Service that the Dataset uses.</p><p>Next, similarly to the Generic Azure SQL Database Table Dataset, we create a Generic Azure Blob Storage File Dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6oy09IgduF7_Fb1MGxP2jQ.png" /><figcaption>Parameters defined in the Generic Azure Blob Storage File Dataset.</figcaption></figure><p>I’ve defined 4 parameters:</p><ul><li><strong>“lsConnectionStringSecretName”: </strong>This will get the name of the Secret in AKV, which holds the connection string to the Azure Blob Storage account.</li><li><strong>“dsContainerName”: </strong>This parameter will be the name of the container in the Azure Blob Storage, where we will store the data extracted from the Azure SQL Database tables.</li><li><strong>“dsDirectoryPath”:</strong> This parameter will be the directory path to the location, where we will store the data extracted from the Azure SQL Database tables.</li><li><strong>“dsFileName”: </strong>This parameter will be the name of the file/blob, which will contain the data extracted from an Azure SQL Database table.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a22YR4Z-88TiK4vxNRmYrw.png" /><figcaption>Usage of Parameters defined in the Generic Azure Blob Storage File Dataset.</figcaption></figure><h4><strong>Step 3)<br>Create a Generic Extraction Pipeline</strong></h4><p>Once we have the Generic Linked Services &amp; Datasets, that we can use to connect to different Azure SQL Databases &amp; Tables, as well as point to different Azure Blob Storage locations, depending on what parameters we supply, we can start setting up a Generic Extraction Pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*2VQgGWJmSIPpOKxbFPY3lA.png" /><figcaption>Generic Extraction Pipeline in ADF.</figcaption></figure><p>The most basic Generic Extraction Pipeline can be reduced to basically 3 activities (<em>or steps</em>) in ADF:</p><ul><li><strong>Lookup:</strong> In this step, we get the metadata for the Extraction Pipeline it should use. This metadata are the values for the parameters we’ve defined previously in the Generic Linked Services &amp; Datasets. In this example, the metadata is stored in an Azure SQL Database, in the <strong>[config].[ExtractMetadata]</strong> table.<br>It could be stored in any kind of external storage though, not just in Azure SQL Database tables. It could be any dataset (<em>e.g.: a file on an Azure Blob Storage, a table in Azure Table Storage, etc.</em>) that can be used with the Lookup activity in ADF.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55fc5dfd01bc86b2cd57f6d890d70697/href">https://medium.com/media/55fc5dfd01bc86b2cd57f6d890d70697/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*FncwjSj5morYYkgrPyN5nQ.png" /><figcaption>Contents of the [config].[ExtractMetadata] table.</figcaption></figure><ul><li><strong>Cycle (For Each): </strong>We need to cycle through / process each record of the metadata returned by the <strong>Lookup</strong> activity. Each record is a table, which contains data, that should be extracted to the target Azure Blob Storage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*omYIx_PQDmUbL9E82NYyZg.png" /><figcaption>For Each cycle in the Generic Extraction Pipeline in ADF. <strong><em>Items: activity(‘Lookup Metadata’).output.value</em></strong></figcaption></figure><ul><li><strong>Extraction Activity: </strong>For each record of the metadata returned, an extraction should take place. This extraction activity can be an API call, an invocation of another ADF pipeline, which handles the extraction, or a simple Copy activity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*RC4zSbraQ1ce6GmsheGswg.png" /><figcaption>“Source” Settings of the Extraction (Copy) activity in the For Each cycle of the Generic Extraction Pipeline.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*qiPwaC8REnFfZadWntC6gA.png" /><figcaption>“Sink” Settings of the Extraction (Copy) activity in the For Each cycle of the Generic Extraction Pipeline.</figcaption></figure><p>…And that’s it!</p><p>Depending on the requirements, the datasets could be further parameterized &amp; the metadata table could be expanded with additional details, for example instead of extracting the entire table’s contents from the source, we could store an SQL query in the metadata table to execute in the Azure SQL Database &amp; store the result.</p><h4><strong>Closing Thoughts</strong></h4><p>With metadata-driven, generic extraction approach, we can very easily scale our extraction processes. If we need to extract additional tables, we only need to insert a new record into the metadata table with the details.</p><p>We can also change the Source or Target of the Extraction easily, by changing the values of the secrets in AKV, or by changing the name of the secrets that should be used to establish the connection, in the metadata table.</p><p>With only 2 Linked Services, 2 Datasets &amp; 1 Pipeline in ADF, we can extract data from hundreds of databases, thousands of tables, to a single or multiple target locations, all based on what we have in the metadata table!</p><p><strong><em>If you’d like to learn more interesting things, tricks &amp; tips about Microsoft Azure’s resources in the data space, please follow me!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47310423aba6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/plumbersofdatascience/azure-data-factory-connect-to-multiple-resources-with-one-linked-service-47310423aba6">Azure Data Factory: Connect to Multiple Resources with One Linked Service</a> was originally published in <a href="https://medium.com/plumbersofdatascience">Plumbers Of Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks: Use Custom Python Libary to Share Functionality Without Compilation (3/3)]]></title>
            <link>https://tiborvekony.medium.com/databricks-use-custom-python-libary-to-share-functionality-without-compilation-3-3-e36c44f046bd?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/e36c44f046bd</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Sun, 30 Jan 2022 21:14:07 GMT</pubDate>
            <atom:updated>2022-01-30T22:39:20.928Z</atom:updated>
            <content:encoded><![CDATA[<h3>Databricks: Share Functionality with Custom Python Libary Without Compilation (3/3)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*aQgICxt-Hm3NQnWk.png" /></figure><p><strong><em>In my previous articles, I’ve explored options to share code / functionality between Databricks notebooks:<br>- Using a [</em></strong><a href="https://tiborvekony.medium.com/databricks-share-functions-across-notebooks-1-3-2fa645fbc508"><strong><em>Shared Function Notebook</em></strong></a>]<strong><em> in the 1st Part<br>- Writing a [</em></strong><a href="https://tiborvekony.medium.com/databricks-ci-cd-python-library-to-share-functionality-2-3-12e1ee649086"><strong><em>custom Python library, then building and deploying it to DBFS using CI/CD pipelines</em></strong></a><strong><em>] in the 2nd Part.</em></strong></p><h3>Summary of the Article</h3><p>In the last part of the series, I’ll showcase a method to share code / functions between notebooks in Databricks, using a custom python (other languages could be used as well) library, <strong>but without compiling it</strong>.</p><p>Why encapsulating common classes, functions, configuration &amp; other logic into a library is good? Well, instead of repeating the same code over-and-over again across dozens of places (in this case, dozens of notebooks), it’s much easier to keep it maintained &amp; use it, if it’s defined in a single place.</p><h3>Problem Statement</h3><p>In many cases, I’ve seen that the first 30–40% of Databricks notebooks is basically prepwork: defining variables &amp; functions, importing common libraries, environment configuration, etc.</p><p>This adds unnecessary clutter to the notebooks, which makes them less readable. After a while, copy-pasting the same setup/configuration steps for each notebooks gets tedious. Not to mention that, if the setup changes, each notebook needs to be changed individually.</p><h3>How to Share Functions Across Notebooks</h3><p>I’ll showcase three ways to share code between Notebooks in Databricks — with their pros &amp; cons:</p><ol><li>[<a href="https://tiborvekony.medium.com/databricks-share-functions-across-notebooks-1-3-2fa645fbc508">Creating a shared functions notebook.</a>]</li><li>[<a href="https://tiborvekony.medium.com/databricks-ci-cd-python-library-to-share-functionality-2-3-12e1ee649086">Compiling a library from code &amp; uploading it.</a>]</li><li><strong>Creating a library &amp; uploading the code — no compilation needed.</strong></li></ol><p>In this article, we’ll take a look at Option 3) Creating a library &amp; uploading the code — no compilation needed.</p><h4><strong>Creating a library</strong></h4><p>First, we’ll need a Python library, which encapsulates the functions, classes &amp; other components we want to use in the Databricks Notebooks.</p><p>In this demo, I’m using a very simple Python library, that I’ve uploaded to [<a href="https://github.com/vekontib/my-python-library/tree/main/SharedFunctionsLib">GitHub</a>]. I’ve used this library in the [<a href="https://tiborvekony.medium.com/databricks-ci-cd-python-library-to-share-functionality-2-3-12e1ee649086">previous article</a>] as well, to showcase how to compile &amp; deploy custom Python libraries to Databricks with CI/CD pipelines. This library (<em>SharedFunctionsLib</em>) only contains 4 files:</p><ul><li><strong>__init__.py</strong> :: This is an empty file, which lets the Python interpreter know that a directory contains code for a Python module</li><li><strong>setup.py</strong> :: This is a Python script,<strong> </strong>that is usually shipped with libraries or programs, written in the library’s language. It’s purpose is the correct installation of the software.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38edf0de7c6b46ed1d06310f8c47989c/href">https://medium.com/media/38edf0de7c6b46ed1d06310f8c47989c/href</a></iframe><ul><li><strong>akv.py :: </strong>This is a module in the custom library that I’ve written. Its name can be whatever you’d like. I gave it “akv” (azure key vault), because it contains a helper class to work with AKV in Databricks.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/177e2dfd47c9e3c4e4819bfe67181c6b/href">https://medium.com/media/177e2dfd47c9e3c4e4819bfe67181c6b/href</a></iframe><ul><li><strong>miscellaneous.py</strong> :: Similarly to <strong>akv.py</strong> this is a custom module in the library as well. It contains only a miscellaneous function — hence the name — , later this can be imported &amp; used in Databricks.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5205b5301342fdc73eacc9abae90e776/href">https://medium.com/media/5205b5301342fdc73eacc9abae90e776/href</a></iframe><p>Now that we’ve encapsulated all the functions &amp; classes in a Python library, unlike in the previous part, I won’t compile it.</p><h4>Creating a Repo in Databricks</h4><p>Databricks was integrated with Git providers in the past as well, but it was on a Notebook level &amp; it was rather clunky.</p><p>Databricks overhauled the old integration and it became Generally Available in October 2021. The new integration makes using Git providers with Databricks a whole lot easier — in short, it became quicker to review &amp; commit code, less navigation between windows, etc.</p><p>Besides making using Git a whole lot more smooth, a new feature was added as well: <strong>the option to store files in the Repo (Files in Repos)</strong>.</p><p>This new feature allows us — unlike the regular Workspace — to store files, including Python &amp; R libraries in the Repo, that we can import in Notebooks that are within the same Repo.</p><p><em>Disclaimer: As of now (2022, January), the Files in Repos feature is in Public Preview and needs to be enabled by an admin of your Databricks Workspace! Obviously, Repos needs to be enabled as well, the option for that is above the “Files in Repos” option.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*18TRgR_i65xHsUg1oyuSzA.png" /><figcaption>Files in Repos option enabled, in the Admin Console of a Databricks Workspace.</figcaption></figure><p>Let’s create a Repo now, I’ll add the Github Repo with my Python Library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YOIFtXyyhKi7h-miRQoTw.png" /><figcaption>Add Repo dialog in Databricks: Adding the my-python-library repo from Github.</figcaption></figure><p>In the dialog window, simply paste the URL of your Repo, choose the correct Git Provider from the Dropdown menu (if the dialog couldn’t infer it for some reason) &amp; change the name of the Repo, if you’d like it to have an alternative name in Databricks.</p><p>When all is done, click Create &amp; behold your very own new repo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*sKK2gPhOL1Vyxa61IbSDIQ.png" /><figcaption>Github Repo added to Databricks Repos.</figcaption></figure><p>In the regular Databricks Workspaces only Notebooks, (compiled) Libraries, Folders &amp; MLFlow Experiments are allowed, but in Repos, as any type of file can be stored. If I navigate into the “SharedFunctionsLib” folder, I can see the .py files there:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Q8V3cCu7nKKYUsUdUmt8zg.png" /><figcaption>Contents of the SharedFunctionsLib folder in the my-python-library Databricks Repo.</figcaption></figure><p>No further setup is needed, Notebooks within the same Repo (my-python-library in this case) can import the “SharedFunctionLib” folder &amp; use the functions, classes &amp; other components within.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*LvovtXjjW_plQIM5wfoz0w.png" /><figcaption>Importing &amp; using the SharedFunctionsLib custom Python library in a Notebook, within the my-python-library Databricks Repo.</figcaption></figure><p>As you can see on the above picture, using the <em>from … import * </em>statements, the Python library can be imported &amp; used, without us needing to compile it first.</p><p>Using custom libraries has never been easier! Besides that, files in Repos can be used to store small datasets (&lt;100 MB, as of now) and for defining an environment in a <em>requirements.txt </em>file, which can be ran using <em>pip </em>to setup the environment.</p><p>Files &lt;10 MB can also be edited within the Databricks Repo, though the editor doesn’t really have any options or features, I’m only ever using it to either quickly check the contents of a file or make minor edits.</p><h4>Closing Thoughts</h4><p>Depending on the current setup, you might use any one of the 3 options to share code / functionality, that I’ve showcased in this series.</p><p>If you already have most of your environment configuration &amp; common functions defined in a Notebook, you can [<a href="https://tiborvekony.medium.com/databricks-share-functions-across-notebooks-1-3-2fa645fbc508">encapsulate that in a Shared Functions notebook</a>] easily.</p><p>If you want the dynamic approach &amp; absolute control over your libraries, how they are built, deployed &amp; served, then you might want to [<a href="https://tiborvekony.medium.com/databricks-ci-cd-python-library-to-share-functionality-2-3-12e1ee649086">create a CI/CD pipeline to build &amp; deploy your libraries</a>].</p><p>If nothing is set-in-stone yet, just starting out &amp; want to be up &amp; running ASAP, but still want to have good version control &amp; options to adapt to changes in the future, then consider using Databricks Repos’ Files in Repos feature to use libraries without compilation.</p><h4>Resources / Interesting Things to Check Out:</h4><ul><li>[<a href="https://docs.databricks.com/_static/notebooks/files-in-repos.html">Databricks Notebook (Python) showcasing files-in-repo functionality</a>]</li><li>[<a href="https://docs.databricks.com/repos.html#work-with-python-and-r-modules">Databricks Repos documentation, working with Python &amp; R modules section</a>]</li><li>[<a href="https://databricks.com/blog/2021/10/07/databricks-repos-is-now-generally-available.html">Databricks Repos Generally Available Announcement Post</a>]</li></ul><p><strong><em>This article is the third &amp; final chapter of a 3 part series, in which I explore various options to share code / functions between Databricks notebooks. If you’d like to learn about the other interesting things, tips &amp; tricks, don’t forget to follow me!</em></strong></p><p><strong><em>If you’ve learned something new, share this article to show what you’ve just learned &amp; to make sure others will see it as well!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e36c44f046bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks: CI/CD Python Library to Share Functionality (2/3)]]></title>
            <link>https://tiborvekony.medium.com/databricks-ci-cd-python-library-to-share-functionality-2-3-12e1ee649086?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/12e1ee649086</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 23:11:18 GMT</pubDate>
            <atom:updated>2022-01-31T09:25:09.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*4nZ_3ZsjRxUGdiS4.png" /></figure><p><strong><em>In my [</em></strong><a href="https://tiborvekony.medium.com/databricks-share-functions-across-notebooks-1-3-2fa645fbc508"><strong><em>previous article</em></strong></a><strong><em>], I’ve explored another option to share code / functionality between Databricks notebooks, using a Shared Function Notebook.</em></strong></p><h3>Summary of the Article</h3><p>In this part of the series, I’ll showcase a method to share code / functions between notebooks in Databricks, using a custom python (other languages could be used as well) library.</p><p>Instead of repeating the same code over-and-over again, it’s much easier to keep it maintained &amp; use it, if it’s defined in a single place.</p><h3>Problem Statement</h3><p>In many cases, I’ve seen that the first 30–40% of Databricks notebooks is basically prepwork: defining variables &amp; functions, importing common libraries, environment configuration, etc.</p><p>This adds unnecessary clutter to the notebooks, which makes them less readable. After a while, copy-pasting the same setup/configuration steps for each notebooks gets tedious. Not to mention that, if the setup changes, each notebook needs to be changed individually.</p><h3>How to Share Functions Across Notebooks</h3><p>I’ll showcase three ways to share code between Notebooks in Databricks — with their pros &amp; cons:</p><ol><li>[<a href="https://tiborvekony.medium.com/databricks-share-functions-across-notebooks-1-3-2fa645fbc508">Creating a shared functions notebook.</a>]</li><li><strong>Compiling a library from code &amp; uploading it.</strong></li><li>[<a href="https://tiborvekony.medium.com/databricks-use-custom-python-libary-to-share-functionality-without-compilation-3-3-e36c44f046bd">Creating a library &amp; uploading the code — no compilation needed.</a>]</li></ol><p>In this article, we’ll take a look at Option 2) Compiling a library from code &amp; uploading it.</p><h4>Compiling a Library</h4><p>First, we’ll need a Python library, which encapsulates the functions, classes &amp; other components we want to use in the Databricks Notebooks.</p><p>In this demo, I’m using a very simple Python library, that I’ve uploaded to [<a href="https://github.com/vekontib/my-python-library/tree/main/SharedFunctionsLib">GitHub</a>]. This library (<em>SharedFunctionsLib</em>) only contains 4 files:</p><ul><li><strong>__init__.py</strong> :: This is an empty file, which lets the Python interpreter know that a directory contains code for a Python module</li><li><strong>setup.py</strong> :: This is a Python script,<strong> </strong>that is usually shipped with libraries or programs, written in the library’s language. It’s purpose is the correct installation of the software.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38edf0de7c6b46ed1d06310f8c47989c/href">https://medium.com/media/38edf0de7c6b46ed1d06310f8c47989c/href</a></iframe><ul><li><strong>akv.py :: </strong>This is a module in the custom library that I’ve written. Its name can be whatever you’d like. I gave it “akv” (azure key vault), because it contains a helper class to work with AKV in Databricks.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/177e2dfd47c9e3c4e4819bfe67181c6b/href">https://medium.com/media/177e2dfd47c9e3c4e4819bfe67181c6b/href</a></iframe><ul><li><strong>miscellaneous.py</strong> :: Similarly to <strong>akv.py</strong> this is a custom module in the library as well. It contains only a miscellaneous function — hence the name — , later this can be imported &amp; used in Databricks.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5205b5301342fdc73eacc9abae90e776/href">https://medium.com/media/5205b5301342fdc73eacc9abae90e776/href</a></iframe><p>Now that we’ve encapsulated all the functions &amp; classes in a Python library, it needs to be complied, before it can be installed onto a Databricks cluster &amp; used in Notebooks.</p><p>The library could be compiled on your desktop computer, then manually uploaded to Databricks to be installed on a cluster, but instead of all those manual steps, let’s setup a CI/CD pipeline.</p><h4>Continuous Integration (CI)</h4><p>To automatically compile the library, after changes are applied to the <strong>main branch</strong> (<em>though it could be any branch, or even tags, all depends on the trigger set in the build pipeline</em>) of the GitHub repo, I’ll use an Azure Build pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*tVwv18yptC42qqJUx9ZEPg.png" /><figcaption>Azure (Build) Pipeline in Azure DevOps.</figcaption></figure><p>After hitting the “Create Pipeline” button, Azure DevOps will take you through a fairly simple setup:</p><ul><li>Select the location of your code: in my case it’s GitHub</li><li>Then, select the repo, which contains the library to compile</li><li>Next, select the type of configuration: Python Package. This will create a nice template pipeline in YAML, as a starting point.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*GuvX2zLVDPGcTa2wKJm47g.png" /><figcaption>Template Azure Build Pipeline written in YAML.</figcaption></figure><p>I’ll slightly tweak this pipeline to work with my minimalistic Python library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e9d3a9e7bda5659342f75d96abbc809/href">https://medium.com/media/8e9d3a9e7bda5659342f75d96abbc809/href</a></iframe><p>The trigger is the <strong>main branch </strong>in the GitHub repo, whenever it’s changed, the build pipeline is executed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4daf33920e1bf6aeeac43bb191699df/href">https://medium.com/media/f4daf33920e1bf6aeeac43bb191699df/href</a></iframe><p>The library is build for multiple Python versions (2.7; 3.5; 3.6; 3.7) to ensure compatibility.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2f11b3c6ef24f264382bfbdd685570a/href">https://medium.com/media/a2f11b3c6ef24f264382bfbdd685570a/href</a></iframe><p>In the first script step (“Install Tools”), I’m installing tools on the agent, which are needed to compile the code it pulls from the GitHub repo. These are <strong>wheel</strong> and <strong>setuptools, </strong>hinting that in the end we’ll end up with a <strong>.whl</strong> file that we can import into Databricks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcca0ac9e83e362cf2e300df379fc57e/href">https://medium.com/media/fcca0ac9e83e362cf2e300df379fc57e/href</a></iframe><p>The second script step (“Building Package”) compiles the library, using the tools installed in the previous step. This step uses the <strong>setup.py</strong> file, discussed earlier. The output (compiled library) is placed into a “dist” folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee36f6ec3f1ed142e28e49507f037302/href">https://medium.com/media/ee36f6ec3f1ed142e28e49507f037302/href</a></iframe><p>In the third script step (“Copy built package from dist”) the complied library is simple moved from the <em>dist</em> folder into a staging area, the contents of which will be output at the end of the build pipeline as an artifact.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a075c48fa1006c4d33b1bece7dbb8853/href">https://medium.com/media/a075c48fa1006c4d33b1bece7dbb8853/href</a></iframe><p>In the last step, the build artifact is published, which will contain the compiled library. It could have other things as well, for example configuration files, scripts to be used in the Release (CD) Pipeline, etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b3f0fe73cfa00115741ce331aac73eb/href">https://medium.com/media/4b3f0fe73cfa00115741ce331aac73eb/href</a></iframe><p>This all depends on your requirements, you can put whatever you need in the Release (CD) Pipeline into this artifact to easily access it, the libraries could be even zipped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc_j8FAszMwgsNTTjbrh9g.png" /><figcaption>Contents of the artifact published by the Azure Build Pipeline. The artifact itself is named “SharedFunctionsLib”, the compiled Python library’s files are in the “libs” folder.</figcaption></figure><h4>Continuous Deployment (CD)</h4><p>Once the Azure Build Pipeline ran &amp; the build artifact is available, it can be used in a Release (CD) Pipeline to deploy its contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*NV5C5tMeunrRjzDlq4S3VA.png" /><figcaption>Azure Release Pipelines menu in Azure DevOps.</figcaption></figure><p>Let’s create a new Release Pipeline, by clicking on the “New” button highlighted in the picture above, and selecting “New release pipeline” from the dropdown menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*B2W2om7ooE2oHpQrGEqI-A.png" /><figcaption>Azure Release Pipeline templates menu. <strong>Make sure to select an “Empty Job”!</strong></figcaption></figure><p>It’ll prompt you to give (by default) “Stage 1” a proper name, I’ve named it “Databricks”. You can also give the Release pipeline a name, by clicking on the “New release pipeline” default name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*o3_cjAMlGo28r52XWKSs8g.png" /><figcaption>Newly created empty Release Pipeline in Azure DevOps.</figcaption></figure><p>Next, we need to select the artifact created &amp; published by the Build Pipeline. To do that, just click the “Add an artifact” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*IZxRPN78Udz2lZ0CH3WdbQ.png" /><figcaption>Adding a new artifact to the Release Pipeline. <strong>In the “Project” and “Source (build pipeline)” dropdown menus select your Project &amp; the Build Pipeline created as part of the previous step!</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*7tUaSNVoRNgP2p5D1W-0sg.png" /><figcaption>Continuous deployment trigger on the Artifact in the Release Pipeline.</figcaption></figure><p>If you don’t want to manually trigger the Release Pipeline, setup a Continuous deployment trigger, which will create a release whenever a new build artifact is available.</p><p>In tandem with the trigger of the Build Pipeline, the Python library will be compiled &amp; deployed, whenever the code changes in the repo.</p><p>Next, define the steps to be executed (deployment steps) in the “Databricks” stage, there will be only 2 steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*rDCsbdLGGATMF2e7LLbarg.png" /><figcaption>Steps in the Databricks stage in the Release Pipeline.</figcaption></figure><p>The first step is the use a specific version of the Python library, in my case it’s 3.7, you use whatever is compatible with your cluster in Databricks. Most likely it’ll be 3.x version as well.</p><p>The second step is to actually take the .whl files from the artifact &amp; copy them to Databricks’ DBFS (<strong><em>D</em></strong><em>ata</em><strong><em>B</em></strong><em>ricks </em><strong><em>F</em></strong><em>ile</em><strong><em>S</em></strong><em>ystem</em>), as this is one of the places, that the cluster can search for libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Yil5HALlpjWddEasFsvNA.png" /><figcaption>“Deploy Library to DBFS” step in the Databricks stage, in the Release Pipeline.</figcaption></figure><p>This step isn’t natively available among the activities offered in the Release Pipelines, it comes from a [<a href="https://marketplace.visualstudio.com/items?itemName=DataThirstLtd.databricksDeployScriptsTasks">free 3rd party plug-in, developed by Data Thirst</a>].</p><p>If you’re in an organization, you might not have the required privileges to add it yourself, but considering that this plug-in shows up in Microsoft’s official documentation &amp; is used by many, the request to add it usually goes through without any hiccups.</p><p>As for the configuration of this step:</p><ul><li>For the <strong>Azure Region</strong> select the region in which your Databricks Workspace is located. For me, it’s West US (“westus”).</li><li>For the <strong>Local Root Folder, </strong>specify the access path to the folder that you want to copy to DBFS. The easiest way to select this is to hit the 3 dots on the right-hand side of the text field &amp; select it from the menu.</li><li><strong>Target folder in DBFS </strong>should be the access path to the target folder in DBFS. I just copy it into a “libs” folder in the root of the DBFS. If it’s not there yet, it’ll be created.</li><li><strong>Databricks bearer token </strong>to authenticate this copy activity. To create one, follow the [<a href="https://docs.databricks.com/dev-tools/api/latest/authentication.html">official documentation</a>] on Databricks’ site. It’s easy, though it requires elevated privileges. If you don’t have them &amp; can’t create one, you have to ask your admin to do so.</li></ul><p>Once all the above is done, a release can be created / the Release Pipeline executed, which will copy the compiled Python library to DBFS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*CHuUKg0p8Mc2W5U_IwId7w.png" /><figcaption>The compiled Python library in DBFS.</figcaption></figure><p>Click the arrow on the right-hand side of the compiled library (py3 for me: “<em>SharedFunctionsLib-0.0.1-py3-no…</em>”), then “Copy Path”, and make sure to copy the Spark API Format path:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*hc59odPrf2E1ozt9QMoipw.png" /><figcaption>File Paths to the compiled Python library in DBFS.</figcaption></figure><p>Next, now that the library is available in DBFS, it can be installed onto a cluster:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0HUimQyFi9ucZzaEp4NoA.png" /><figcaption>Installing the library to a cluster.</figcaption></figure><p>Make sure to select to correct Library Source (<em>DBFS/ADLS</em>) &amp; Library Type (<em>Python Whl</em>)! <strong>Note: The cluster must be running to install libraries!</strong></p><p>Once the library finished installing to the cluster, it can be used in Notebooks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*FZPZlCK1Wsqq2yj0U77qdQ.png" /><figcaption>Using the custom library in a Databricks Notebook.</figcaption></figure><p><strong><em>This article is the second chapter of a 3 part series, in which I explore various options to share code / functions between Databricks notebooks. If you’d like to learn about the other options (creating &amp; importing libraries — without compiling them), don’t forget to follow me to get notified when the next chapter is published!!!</em></strong></p><p><strong><em>If you’ve learned something new, share this article to show what you’ve just learned &amp; to make sure others will see it as well!!!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12e1ee649086" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks: Share Functions across Notebooks (1/3)]]></title>
            <link>https://tiborvekony.medium.com/databricks-share-functions-across-notebooks-1-3-2fa645fbc508?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fa645fbc508</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 13:23:57 GMT</pubDate>
            <atom:updated>2022-01-31T09:25:38.205Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*dzetgOUmEBeFoWh3.png" /></figure><h4>Summary of the Article</h4><p>In this series of articles I will showcase a few methods to share functions &amp; variables between Databricks Notebooks. This is done to reduce code repetition, increase consistency, efficiency &amp; reusability.</p><h4>Problem Statement</h4><p>In many cases, I’ve seen that the first 30–40% of Databricks notebooks is basically prepwork: defining variables &amp; functions, importing common libraries, environment configuration, etc.</p><p>This adds unnecessary clutter to the notebooks, which makes them less readable. After a while, copy-pasting the same setup/configuration steps for each notebooks gets tedious. Not to mention that, if the setup changes, each notebook needs to be changed individually.</p><h3>How to Share Functions Across Notebooks</h3><p>I’ll showcase three ways to share code between Notebooks in Databricks — with their pros &amp; cons:</p><ol><li><strong>Creating a shared functions notebook.</strong></li><li>[<a href="https://tiborvekony.medium.com/databricks-ci-cd-python-library-to-share-functionality-2-3-12e1ee649086">Compiling a library from code &amp; uploading it.</a>]</li><li>[<a href="https://tiborvekony.medium.com/databricks-use-custom-python-libary-to-share-functionality-without-compilation-3-3-e36c44f046bd">Creating a library &amp; uploading the code — no compilation needed.</a>]</li></ol><p>In this article, we’ll take a look at Option 1) Creating a shared functions notebook.</p><h4><strong>Creating a Shared Functions Notebook</strong></h4><p>This is a beginner-friendly, easy, straightforward approach.</p><p>Using the “%run” magic command, notebooks can execute other notebooks. While doing so, the variables &amp; functions defined in the executed notebook become available for the executor notebook as well.</p><p>This happens, because in the background, whenever a notebook is attached to a spark cluster, an <a href="https://docs.databricks.com/notebooks/notebooks-manage.html#execution-contexts">execution context</a> is created, which contains the state of the <a href="https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop">REPL</a> environments (one for each programming language — SQL, Python, Scala, R).</p><p>When <em>Notebook A</em> executes <em>Notebook B, </em>it is executed in the same execution context, which was created when <em>Notebook A</em> was attached to the cluster. This means, that they have access to the same state, meaning they can access the same variables, functions, etc.</p><p>Let’s see a simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*pFkoF0MmmWdIytWMsXYXBA.png" /><figcaption>“_Main” Notebook in Databricks, which will execute another Notebook (cmd3).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*RUCYK-oonzovviVBZdhhRA.png" /><figcaption>“_Shared” Notebook in Datarbricks, containing the variables, funtions, setup process, etc. to be shared across other Notebooks.</figcaption></figure><p>The expected results are:</p><ul><li>To see the variable defined in the _Main Notebook to be printed as the result of <em>cmd3.</em></li><li>To see both the variable defined in _Main, as well as in _Shared, to be printed using the function defined in _Shared, as the result of <em>cmd4</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*vmWOs9JIEPNphQRUjkysZQ.png" /><figcaption>Results of the test, as expected.</figcaption></figure><p>One very important limitation is, that due to each programming language supported in Databricks (SQL, Python, Scala, R) having its own REPL environment, variables defined in one programming language cannot be accessed by commands written in another programming language. E.g.: variables defined in Python cannot be accessed by commands written in Scala.</p><p>To somewhat circumvent this limitation, the values of variables can be written to the preferred storage (to files) and read by commands in another language.</p><h3>Summary (Pros. &amp; Cons.)</h3><p>Shared Functions Notebook:</p><ul><li>[+] Easy to setup, just encapsulate the shared code into a separate notebook.</li><li>[+] Readable to the naked eye, no need to compile/build it. No mandatory auxiliary files (license, README, setup, etc.).</li><li>[+] Familiar source control process, as it’s just another notebook.</li><li>[-] If it gets large, it becomes hard to maintain.</li><li>[-] Running it at the start of each execution, to get it into the execution context can be a lot of overhead and slow the overall process.</li></ul><p><strong><em>This article is the first chapter of a 3 part series, in which I explore various options to share code / functions between Databricks notebooks. If you’d like to learn about the other options (creating &amp; importing libraries), don’t forget to follow me to get notified when the next chapter is published!!!</em></strong></p><p><strong><em>If you’ve learned something new, share this article to show what you’ve just learned &amp; to make sure others will see it as well!!!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fa645fbc508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Data Factory: Keep your secrets in Azure Key Vault]]></title>
            <link>https://tiborvekony.medium.com/azure-data-factory-keep-your-secrets-in-azure-key-vault-fb9d0bbc5ca4?source=rss-3ed469f03ece------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb9d0bbc5ca4</guid>
            <category><![CDATA[adf]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[azure-key-vault]]></category>
            <dc:creator><![CDATA[Tibor Vekony]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 00:27:39 GMT</pubDate>
            <atom:updated>2022-01-05T00:27:39.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bni9muuAlFqsNAFm67-M1w.png" /></figure><h4>Summary of the Article</h4><p>This article will showcase the options currently available to link <strong>A</strong>zure <strong>K</strong>ey <strong>V</strong>ault (AKV) with <strong>A</strong>zure <strong>D</strong>ata <strong>F</strong>actory (ADF). Besides the basic how-to, I’ll also show how the linked AKV can be used in ADF.</p><p><strong><em>In the next two sections, I’ll quickly go over what ADF and AKV are. If you’re already familiar with them, feel free to skip ahead!</em></strong></p><h4>What is Azure Data Factory (ADF)?</h4><p><strong>A</strong>zure <strong>D</strong>ata <strong>F</strong>actory (ADF) is a service on the Microsoft Azure platform. It is a fully managed, no-code (<em>drag &amp; drop components onto a canvas</em>), serverless (<em>servers are taken care of by Microsoft, costs are consumption-based, computing power allocated on demand. Yes, “serverless” is a misnomer</em>), integration service to build &amp; orchestrate ETL/ELT pipelines.</p><h4>What is Azure Key Vault (AKV)?</h4><p><strong>A</strong>zure <strong>K</strong>ey <strong>V</strong>ault (AKV) is a service on the Microsoft Azure platform, for securely storing and accessing secrets. A secret is anything that shouldn’t be shared publicly or even within the company, prime candidates are: API keys, passwords, user names, connection strings, certificates &amp; cryptographic keys, among many other things. AKV also logs which secrets were used when &amp; by whom.</p><h4>How to Connect ADF to AKV?</h4><p>It’s pretty simple, really.</p><p>In ADF, navigate to the “Manage” menu, create a new Linked Service, of the Azure Key Vault type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*bJ4ooQkv6hYlJEcSA7kZdA.png" /><figcaption>Creating a new Azure Key Vault (AKV) Linked Service in Azure Data Factory (ADF).</figcaption></figure><p>The first thing we’ll need to decide is the method of authentication for ADF to use when connecting to AKV. There are only 2, so we don’t have many choices:</p><ol><li>Managed Identity</li><li>User-assigned Managed Identity</li></ol><p>Which one to choose boils down to whether the identity should be kept, if the ADF resource gets deleted or if the same identity will be assigned to multiple resources. If the answer is yes to either of them, select User-assigned Managed Identity, if no, select Managed Identity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*_Z91bfUESuS7Q6p0mapIaQ.png" /><figcaption>Screen in Azure Data Factory, when creating an Azure Key Vault Linked Service.</figcaption></figure><p>For this exercise, I’ve choosen Managed Identity, but the process with a User-assigned Managed Identity is the same, after creating &amp; selecting the User-assigned Managed Identity. They can be created [<a href="https://portal.azure.com/#blade/HubsExtension/BrowseResource/resourceType/Microsoft.ManagedIdentity%2FuserAssignedIdentities">here</a>].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*lKboP-zuOyMRvha3L_4-Dg.png" /><figcaption>Screen in Azure Data Factory for selecting a User-assigned Managed Identity.</figcaption></figure><p>Next, from the dropdown menus (“Azure subscription” &amp; “Azure key vault name”) select the Azure Subscription containing the AKV. If the correct subscription was selected, the AKV should be visible in the “Azure key vault name” dropdown menu.</p><p>Below the dropdown menus, the UI very helpfully shows the name &amp; object ID of the Managed Identity of the ADF resource (<em>I’ve deleted them on the picture above</em>), as well as a [<a href="https://docs.microsoft.com/en-us/azure/data-factory/store-credentials-in-key-vault#steps">link</a>] to the documentation on how to grant ADF access to AKV. <strong>Note the Save button!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*tU6R_GRLlrZbE6hBJlV2hw.png" /><figcaption>How to add Access Policy in AKV.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*m8_NFW7KZ91J2MyoFMjcgA.png" /><figcaption>Creating a new Access Policy for the Managed Identity.</figcaption></figure><p>Usually, only the List and Get permissions are assigned, for any type (Secret, Key, Certificate), as ADF is a user/consumer of secrets &amp; doesn’t usually manage them.</p><p>After assigning the permissions, ensure the correct principal is selected. Click on the “None selected” button besides the “Select principal” label &amp; paste the object ID or name that the UI in ADF listed.</p><p>Click on “Add”, then <strong>make sure to click the Save button on the Access Policies screen, otherwise the Access Policy won’t be applied!</strong></p><p>Afterwards, the Create button in ADF can be clicked to create the AKV Linked Service, which can used in other Linked Services in ADF to retrieve secrets from that AKV.</p><h4><strong>How to access AKV in ADF</strong></h4><p>There are 2 ways to access &amp; use the secrets stored in AKV:</p><ol><li>via the Linked Service</li><li>via the AKV’s REST API</li></ol><p>Both can be valid. Which one to use will depend on <strong>where</strong> the secret will be used.</p><p>If the secret is needed within another Linked Service, then the AKV Linked Service should be used. On the other hand, if the secret is needed within a pipeline, then the REST API should be used.</p><h4>AKV Linked Service in other Linked Services</h4><p>During creation of Linked Services, the UI for many of them provides the option to use an existing AKV Linked Service to fetch secrets from, for properties like passwords or credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*nCJGzBK_BadfXMht5CU_Bg.png" /><figcaption>Part of the SFTP Linked Service creation screen in ADF. The UI provides an option to use a secret in AKV as the password for the connection.</figcaption></figure><p>In other cases though, the UI doesn’t provide the option to use an AKV secret. Using the picture above as an example, the UI doesn’t allow to use a secret as the username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*JQSJpL87mjaLNZtz4ZJAig.png" /><figcaption>Setting a String as value for a property vs. Setting a secret as the value for a property</figcaption></figure><p>By editing the JSON definition of a Linked Service (<em>it can be viewed by clicking on the curly braces icon in the list of Linked Services in ADF</em>) directly, it is possible to use secrets from an existing AKV Linked Service as values for properties that the UI would normally not allow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*6xnK8bIqEcEclRdCjIXvlg.png" /><figcaption>Edited JSON definition of an SFTP Linked Service. Note that the username is defined as a secret coming from a linked AKV. Normally, this is not possible to setup via the UI.</figcaption></figure><p>This can be combined with parameterization of the Linked Service too, if the name of the secret is unknown or if it will be determined only during runtime. In the above example, the name of the secret is parameterized.</p><h4>Using Secrets from AKV in Pipelines</h4><p>If a secret from AKV is needed within a pipeline, it can be retrieved via making an HTTP request to the REST API of the AKV, using a Web Activity in ADF.</p><p><strong>To retrieve secrets from AKV via the REST API, setting up a Linked Service to the AKV is not a pre-requisite.</strong></p><p>As an example, let’s say that within ADF an external API must be called, which requires an API key. This API key — following best practices — is stored in AKV.</p><p>To retrieve the API key in ADF, a simple Web Activity can be used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*4VLMjjD2OGnjdO-ted5hOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*NNqFV-J7VE2qt6xTojrb1Q.png" /><figcaption>JSON definition of the Web Activity retrieving secrets from AKV.</figcaption></figure><p>In this example, I’ve selected <strong>MSI / Managed Identity </strong>as the method of authentication within the Web Activity. <strong>User-assigned Managed Identity </strong>could be used as well, if one is set-up with the AKV.</p><p><strong>An API version must be specified</strong> as well as a query parameter in the URL that’s called. In the above example, it’s 7.0 (<em>?api-version=7.0</em>). If an API version isn’t specified, the activity will fail.</p><p>Another important bit is to make sure that the <strong>Resource</strong> (to which authentication happens) is set to “https://vault.azure.net”.</p><p>As this activity handles secrets, it’s a good idea to check the “Secure Output” option to avoid revealing the secrets within the logs.</p><p>The output of the Web Activity will contain the HTTP response from AKV, which will have the secret, if everything went well. This can be saved in a variable and used in other activities in the pipeline, or pass to other pipelines as a parameter.</p><h4>Summary</h4><p>Key learnings from this article:</p><ol><li>How to create an AKV Linked Service &amp; which authentication method to use.</li><li>AKV Linked Services can be used with other Linked Services. They can be used even if the UI doesn’t provide an option to do so.</li><li>If a secret is needed within a pipeline, it can be fetched via a Web Activity sending an HTTP request to the REST API of AKV.</li></ol><p><strong><em>If you’d like to learn more interesting things, tricks &amp; tips about Microsoft Azure, please follow me!!!</em></strong></p><p><strong><em>If you’ve learned something new, share this article to show what you’ve just learned &amp; to make sure others will see it as well!!!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb9d0bbc5ca4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>