Continuous integration and delivery on Azure Databricks using Azure DevOps

Note

This article covers Azure DevOps, which is neither provided nor supported by Databricks. To contact the provider, see Azure DevOps Services support.

Continuous integration and continuous delivery (CI/CD) refers to the process of developing and delivering software in short, frequent cycles through the use of automation pipelines. While this is by no means a new process, having been ubiquitous in traditional software engineering for decades, it is becoming an increasingly necessary process for data engineering and data science teams. In order for data products to be valuable, they must be delivered in a timely manner. Additionally, consumers must have confidence in the validity of outcomes within these products. By automating the building, testing, and deployment of code, development teams are able to deliver releases more frequently and reliably than the more manual processes that are still prevalent across many data engineering and data science teams.

Continuous integration begins with the practice of having you commit your code with some frequency to a branch within a source code repository. Each commit is then merged with the commits from other developers to ensure that no conflicts were introduced. Changes are further validated by creating a build and running automated tests against that build. This process ultimately results in an artifact, or deployment bundle, that will eventually be deployed to a target environment, in this case an Azure Databricks workspace.

Overview of a typical Azure Databricks CI/CD pipeline

Though it can vary based on your needs, a typical configuration for an Azure Databricks pipeline includes the following steps:

Continuous integration:

  1. Code
    1. Develop code and unit tests in an Azure Databricks notebook or using an external IDE.
    2. Manually run tests.
    3. Commit code and tests to a git branch.
  2. Build
    1. Gather new and updated code and tests.
    2. Run automated tests.
    3. Build libraries and non-notebook Apache Spark code.
  3. Release: Generate a release artifact.

Continuous delivery:

  1. Deploy
    1. Deploy notebooks.
    2. Deploy libraries.
  2. Test: Run automated tests and report results.
  3. Operate: Programmatically schedule data engineering, analytics, and machine learning workflows.

Develop and commit your code

One of the first steps in designing a CI/CD pipeline is deciding on a code commit and branching strategy to manage the development and integration of new and updated code without adversely affecting the code currently in production. Part of this decision involves choosing a version control system to contain your code and facilitate the promotion of that code. Azure Databricks supports integrations with GitHub and Bitbucket, which allow you to commit notebooks to a git repository.

If your version control system is not among those supported through direct notebook integration, or if you want more flexibility and control than the self-service git integration, you can use the Databricks CLI to export notebooks and commit them from your local machine. This script should be run from within a local git repository that is set up to sync with the appropriate remote repository. When executed, this script should:

  1. Check out the desired branch.
  2. Pull new changes from the remote branch.
  3. Export notebooks from the Azure Databricks workspace using the Azure Databricks workspace CLI.
  4. Prompt the user for a commit message or use the default if one is not provided.
  5. Commit the updated notebooks to the local branch.
  6. Push the changes to the remote branch.

The following script performs these steps:

git checkout <branch>
git pull
databricks workspace export_dir --profile <profile> -o <path> ./Workspace

dt=`date '+%Y-%m-%d %H:%M:%S'`
msg_default="DB export on $dt"
read -p "Enter the commit comment [$msg_default]: " msg
msg=${msg:-$msg_default}
echo $msg

git add .
git commit -m "<commit-message>"
git push

If you prefer to develop in an IDE rather than in Azure Databricks notebooks, you can use the VCS integration features built into modern IDEs or the git CLI to commit your code.

Azure Databricks provides Databricks Connect, an SDK that connects IDEs to Azure Databricks clusters. This is especially useful when developing libraries, as it allows you to run and unit test your code on Azure Databricks clusters without having to deploy that code. See Databricks Connect limitations to determine whether your use case is supported.

Note

Databricks now recommends that you use dbx by Databricks Labs for local development instead of Databricks Connect.

Depending on your branching strategy and promotion process, the point at which a CI/CD pipeline will initiate a build will vary. However, committed code from various contributors will eventually be merged into a designated branch to be built and deployed. Branch management steps run outside of Azure Databricks, using the interfaces provided by the version control system.

There are numerous CI/CD tools you can use to manage and execute your pipeline. This article illustrates how to use the Azure DevOps automation server. CI/CD is a design pattern, so the steps and stages outlined in this article should transfer with a few changes to the pipeline definition language in each tool. Furthermore, much of the code in this example pipeline runs standard Python code, which you can invoke in other tools.

For information about using Jenkins with Azure Databricks, see CI/CD with Jenkins on Azure Databricks.

Define your build pipeline

Azure DevOps provides a cloud hosted interface for defining the stages of your CI/CD pipeline using YAML. You define the build pipeline, which runs unit tests and builds a deployment artifact, in the Pipelines interface. Then, to deploy the code to an Azure Databricks workspace, you specify this deployment artifact in a release pipeline.

In your Azure DevOps project, open the Pipelines menu and click Pipelines.

Azure DevOps Pipeline menu

Click the New Pipeline button to open the Pipeline editor, where you define your build in the azure-pipelines.yml file.

You can use the Git branch selector Git branch selector to customize the build process for each branch in your Git repository.

Azure DevOps Pipeline editor

The azure-pipelines.yml file is stored by default in the root directory of the git repository for the pipeline. Environment variables referenced by the pipeline are configured using the Variables button.

Azure DevOps Variables button

For more information on Azure DevOps and build pipelines, see the Azure DevOps documentation.

Configure your build agent

To execute the pipeline, Azure DevOps provides cloud-hosted, on-demand execution agents that support deployments to Kubernetes, VMs, Azure Functions, Azure Web Apps, and many more targets. In this example, you use an on-demand agent to automate the deployment of code to the target Azure Databricks workspace. Tools or packages required by the pipeline must be defined in the pipeline script and installed on the agent at execution time.

This example requires the following dependencies:

  • Conda - Conda is an open source environment management system
  • Python - used to run tests, build a deployment wheel, and execute deployment scripts. The version of Python is important, because tests require that the version of Python running on the agent match that of the Azure Databricks cluster. This example uses Databricks Runtime 7.3, which includes Python 3.7.
  • Python libraries: requests, databricks-connect, databricks-cli, pytest

Here is an example pipeline (azure-pipelines.yml). The complete script follows. This article steps through each section of the script.

# Azure Databricks Build Pipeline
# azure-pipelines.yml

trigger:
- release

pool:
  name: Hosted Ubuntu 1604

steps:
- task: UsePythonVersion@0
  displayName: 'Use Python 3.7'
  inputs:
    versionSpec: 3.7

- script: |
    pip install pytest requests setuptools wheel
    pip install -U databricks-connect==7.3.*
  displayName: 'Load Python Dependencies'

- script: |
    echo "y
    $(WORKSPACE-REGION-URL)
    $(CSE-DEVELOP-PAT)
    $(EXISTING-CLUSTER-ID)
    $(WORKSPACE-ORG-ID)
    15001" | databricks-connect configure
  displayName: 'Configure DBConnect'

- checkout: self
  persistCredentials: true
  clean: true

- script: git checkout release
  displayName: 'Get Latest Branch'

- script: |
    python -m pytest --junit-xml=$(Build.Repository.LocalPath)/logs/TEST-LOCAL.xml
$(Build.Repository.LocalPath)/libraries/python/dbxdemo/test*.py || true

  displayName: 'Run Python Unit Tests for library code'

- task: PublishTestResults@2
  inputs:
    testResultsFiles: '**/TEST-*.xml'
    failTaskOnFailedTests: true
    publishRunAttachments: true

- script: |
    cd $(Build.Repository.LocalPath)/libraries/python/dbxdemo
    python3 setup.py sdist bdist_wheel
    ls dist/
  displayName: 'Build Python Wheel for Libs'

- script: |
    git diff --name-only --diff-filter=AMR HEAD^1 HEAD | xargs -I '{}' cp --parents -r '{}' $(Build.BinariesDirectory)

    mkdir -p $(Build.BinariesDirectory)/libraries/python/libs
    cp $(Build.Repository.LocalPath)/libraries/python/dbxdemo/dist/*.* $(Build.BinariesDirectory)/libraries/python/libs

    mkdir -p $(Build.BinariesDirectory)/cicd-scripts
    cp $(Build.Repository.LocalPath)/cicd-scripts/*.* $(Build.BinariesDirectory)/cicd-scripts

  displayName: 'Get Changes'

- task: ArchiveFiles@2
  inputs:
    rootFolderOrFile: '$(Build.BinariesDirectory)'
    includeRootFolder: false
    archiveType: 'zip'
    archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'
    replaceExistingArchive: true

- task: PublishBuildArtifacts@1
  inputs:
    ArtifactName: 'DatabricksBuild'

Set up the pipeline

In the setup stage you configure the build agent, Databricks CLI, and Databricks Connect with connection information.

# Specify the trigger event to start the build pipeline.
# In this case, new code merged into the release branch initiates a new build.
trigger:
- release

# Specify the OS for the agent
pool:
  name: Hosted Ubuntu 1604

# Install Python. The version must match the version on the Databricks cluster.
steps:
- task: UsePythonVersion@0
  displayName: 'Use Python 3.7'
  inputs:
    versionSpec: 3.7

# Install required Python modules, including databricks-connect, required to execute a unit test
# on a cluster.
- script: |
    pip install pytest requests setuptools wheel
    pip install -U databricks-connect==7.3.*
  displayName: 'Load Python Dependencies'

# Use environment variables to pass Databricks login information to the Databricks Connect
# configuration function
- script: |
    echo "y
    $(WORKSPACE-REGION-URL)
    $(CSE-DEVELOP-PAT)
    $(EXISTING-CLUSTER-ID)
    $(WORKSPACE-ORG-ID)
    15001" | databricks-connect configure
  displayName: 'Configure DBConnect'

Get the latest changes

This stage downloads code from the designated branch to the agent execution agent.

- checkout: self
  persistCredentials: true
  clean: true

- script: git checkout release
  displayName: 'Get Latest Branch'

Unit tests in Azure Databricks notebooks

For library code developed outside an Azure Databricks notebook, the process is like traditional software development practices. You write a unit test using a testing framework, like the Python pytest module, and use JUnit-formatted XML files to store the test results.

Azure Databricks code is Apache Spark code intended to be executed on Azure Databricks clusters. To unit test this code, you can use the Databricks Connect SDK configured in Set up the pipeline.

Test library code using Databricks Connect

This stage of the pipeline invokes the unit tests, specifying the name and location for both the tests and the output files.

- script: |
    python -m pytest --junit-xml=$(Build.Repository.LocalPath)/logs/TEST-LOCAL.xml $(Build.Repository.LocalPath)/libraries/python/dbxdemo/test*.py || true
    ls logs
  displayName: 'Run Python Unit Tests for library code'

The following snippet (addcol.py) is a library function that might be installed on an Azure Databricks cluster. This simple function adds a new column, populated by a literal, to an Apache Spark DataFrame.

# addcol.py
import pyspark.sql.functions as F

def with_status(df):
    return df.withColumn("status", F.lit("checked"))

The following test, test-addcol.py, passes a mock DataFrame object to the with_status function, defined in addcol.py. The result is then compared to a DataFrame object containing the expected values. If the values match, the test passes.

# test-addcol.py
import pytest

from dbxdemo.spark import get_spark
from dbxdemo.appendcol import with_status

class TestAppendCol(object):

    def test_with_status(self):
        source_data = [
            ("pete", "pan", "peter.pan@databricks.com"),
            ("jason", "argonaut", "jason.argonaut@databricks.com")
        ]
        source_df = get_spark().createDataFrame(
            source_data,
            ["first_name", "last_name", "email"]
        )

        actual_df = with_status(source_df)

        expected_data = [
            ("pete", "pan", "peter.pan@databricks.com", "checked"),
            ("jason", "argonaut", "jason.argonaut@databricks.com", "checked")
        ]
        expected_df = get_spark().createDataFrame(
            expected_data,
            ["first_name", "last_name", "email", "status"]
        )

        assert(expected_df.collect() == actual_df.collect())

Package library code

This stage of the pipeline packages the library code into a Python wheel.

- script: |
    cd $(Build.Repository.LocalPath)/libraries/python/dbxdemo
    python3 setup.py sdist bdist_wheel
    ls dist/
  displayName: 'Build Python Wheel for Libs'

Publish test results

After all unit tests have been executed, publish the results to Azure DevOps. This lets you visualize reports and dashboards related to the status of the build process.

- task: PublishTestResults@2
  inputs:
    testResultsFiles: '**/TEST-*.xml'
    failTaskOnFailedTests: true
    publishRunAttachments: true

Generate and store a deployment artifact

The final step of the build pipeline is to generate the deployment artifact. To do this, you gather all the new or updated code to be deployed to the Azure Databricks environment, including the notebook code to be deployed to the workspace, .whl libraries that were generated by the build process, and the result summaries for the tests, for archiving purposes.

# Use git diff to flag files added in the most recent git merge
- script: |
    git diff --name-only --diff-filter=AMR HEAD^1 HEAD | xargs -I '{}' cp --parents -r '{}' $(Build.BinariesDirectory)

# Add the wheel file you just created along with utility scripts used by the Release pipeline
# The implementation in your Pipeline may be different.
# The objective is to add all files intended for the current release.
    mkdir -p $(Build.BinariesDirectory)/libraries/python/libs
    cp $(Build.Repository.LocalPath)/libraries/python/dbxdemo/dist/*.* $(Build.BinariesDirectory)/libraries/python/libs

    mkdir -p $(Build.BinariesDirectory)/cicd-scripts
    cp $(Build.Repository.LocalPath)/cicd-scripts/*.* $(Build.BinariesDirectory)/cicd-scripts
  displayName: 'Get Changes'

# Create the deployment artifact and publish it to the artifact repository
- task: ArchiveFiles@2
  inputs:
    rootFolderOrFile: '$(Build.BinariesDirectory)'
    includeRootFolder: false
    archiveType: 'zip'
    archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip'
    replaceExistingArchive: true

- task: PublishBuildArtifacts@1
  inputs:
    ArtifactName: 'DatabricksBuild'

Define your release pipeline

The release pipeline deploys the artifact to an Azure Databricks environment. Separating the release pipeline from the build pipeline allows you to create a build without deploying it, or to deploy artifacts from multiple builds at one time.

  1. In your Azure DevOps project, go to the Pipelines menu and click Releases.

    Azure DevOps Releases

  2. On the right side of the screen is a list of featured templates for common deployment patterns. For this pipeline, click Empty Job.

    Azure DevOps release pipeline 1

  3. In the Artifacts box on the left side of the screen, click Add and select the build pipeline created earlier.

    Azure DevOps release pipeline 2

You can configure how the pipeline is triggered by clicking Lightning bolt icon, which displays triggering options on the right side of the screen. If you want a release to be initiated automatically based on build artifact availability or after a pull request workflow, enable the appropriate trigger.

Azure DevOps release pipeline stage 1

To add steps or tasks for the deployment, click the link within the stage object.

Azure DevOps release pipeline add stage

Add tasks

To add tasks, click the plus sign in the Agent job section, indicated by the red arrow in the following figure. A searchable list of available tasks appears. There is also a Marketplace for third-party plug-ins that can be used to supplement the standard Azure DevOps tasks.

Azure DevOps add task

Set Python version

The first task you add is Use Python version. As with the build pipeline, you want to make sure that the Python version is compatible with the scripts called in subsequent tasks.

Azure DevOps set python version 1

In this case, set the Python version to 3.7.

Azure DevOps set python version 2

Unpackage the build artifact

Extract the archive using the Extract files task. Set the Archive file patterns to *.zip, and set the Destination folder to the system variable, “$(agent.builddirectory)”. You can optionally set the Display name; this is the name that appears on the screen under Agent job.

Azure DevOps unpackage

Deploy the notebooks to the workspace

To deploy the notebooks, this example uses the third-party task Databricks Deploy Notebooks developed by Data Thirst.

  • Enter environment variables to set the values for Azure Region and Databricks bearer token.
  • Set the Source files path to the path of the extracted directory containing your notebooks.
  • Set the Target files path to the desired path within the Azure Databricks workspace directory structure.

Azure DevOps deploy notebook

Deploy the library to DBFS

To deploy the Python *.war file, use the third-party task Databricks files to DBFS, also developed by Data Thirst.

  • Enter environment variables to set the values for Azure Region and Databricks bearer token.
  • Set the Local Root Folder to the path of the extracted directory containing the Python libraries.
  • Set the Target folder in DBFS to the desired DBFS path.

Azure DevOps file deploy

Install the library on a cluster

The final code deployment task installs the library onto a specific cluster. To do this, you create a Python script task. The Python script, installWhlLibrary.py, is in the artifact created by our build pipeline.

Note

As a security best practice, when authenticating with automated tools, systems, scripts, and apps, Databricks recommends you use access tokens belonging to service principals instead of workspace users. To create access tokens for service principals, see Manage access tokens for a service principal.

  • Set the Script path to $(agent.builddirectory)/cicd-scripts/installWhlLibrary.py. The installWhlLibrary.py script takes five arguments:
    • shard - the URL for the target workspace (for example, https://<region>.azuredatabricks.net)
    • token - a personal access token for workspace
    • clusterid - the ID for the cluster on which to install the library
    • libs - the extracted directory containing the libraries
    • dbfspath - the path within the DBFS file system to retrieve the libraries

Azure DevOps install library

Before installing a new version of a library on an Azure Databricks cluster, you must uninstall the existing library. To do this, invoke the Databricks REST API in a Python script to perform the following steps:

  1. Check if the library is installed.
  2. Uninstall the library.
  3. Restart the cluster if any uninstalls were performed.
  4. Wait until the cluster is running again before proceeding.
  5. Install the library.
# installWhlLibrary.py
#!/usr/bin/python3
import json
import requests
import sys
import getopt
import time
import os

def main():
    shard = ''
    token = ''
    clusterid = ''
    libspath = ''
    dbfspath = ''

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hstcld',
                                   ['shard=', 'token=', 'clusterid=', 'libs=', 'dbfspath='])
    except getopt.GetoptError:
        print(
            'installWhlLibrary.py -s <shard> -t <token> -c <clusterid> -l <libs> -d <dbfspath>')
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print(
                'installWhlLibrary.py -s <shard> -t <token> -c <clusterid> -l <libs> -d <dbfspath>')
            sys.exit()
        elif opt in ('-s', '--shard'):
            shard = arg
        elif opt in ('-t', '--token'):
            token = arg
        elif opt in ('-c', '--clusterid'):
            clusterid = arg
        elif opt in ('-l', '--libs'):
            libspath=arg
        elif opt in ('-d', '--dbfspath'):
            dbfspath=arg

    print('-s is ' + shard)
    print('-t is ' + token)
    print('-c is ' + clusterid)
    print('-l is ' + libspath)
    print('-d is ' + dbfspath)

    # Uninstall library if exists on cluster
    i=0

    # Generate array from walking local path
    libslist = []
    for path, subdirs, files in os.walk(libspath):
        for name in files:

            name, file_extension = os.path.splitext(name)
            if file_extension.lower() in ['.whl']:
                libslist.append(name + file_extension.lower())

    for lib in libslist:
        dbfslib = dbfspath + '/' + lib

        if (getLibStatus(shard, token, clusterid, dbfslib) is not None:
            print(dbfslib + ' before:' + getLibStatus(shard, token, clusterid, dbfslib))
            print(dbfslib + " exists. Uninstalling.")
            i = i + 1
            values = {'cluster_id': clusterid, 'libraries': [{'whl': dbfslib}]}

            resp = requests.post(shard + '/api/2.0/libraries/uninstall', data=json.dumps(values), auth=("token", token))
            runjson = resp.text
            d = json.loads(runjson)
            print(dbfslib + ' after:' + getLibStatus(shard, token, clusterid, dbfslib))

            # Restart if libraries uninstalled
            if i > 0:
                values = {'cluster_id': clusterid}
                print("Restarting cluster:" + clusterid)
                resp = requests.post(shard + '/api/2.0/clusters/restart', data=json.dumps(values), auth=("token", token))
                restartjson = resp.text
                print(restartjson)

                p = 0
                waiting = True
                while waiting:
                    time.sleep(30)
                    clusterresp = requests.get(shard + '/api/2.0/clusters/get?cluster_id=' + clusterid,
                                           auth=("token", token))
                    clusterjson = clusterresp.text
                    jsonout = json.loads(clusterjson)
                    current_state = jsonout['state']
                    print(clusterid + " state:" + current_state)
                    if current_state in ['TERMINATED', 'RUNNING','INTERNAL_ERROR', 'SKIPPED'] or p >= 10:
                        break
                    p = p + 1

        print("Installing " + dbfslib)
        values = {'cluster_id': clusterid, 'libraries': [{'whl': 'dbfs:' + dbfslib}]}

        resp = requests.post(shard + '/api/2.0/libraries/install', data=json.dumps(values), auth=("token", token))
        runjson = resp.text
        d = json.loads(runjson)
        print(dbfslib + ' after:' + getLibStatus(shard, token, clusterid, dbfslib))

def getLibStatus(shard, token, clusterid, dbfslib):

    resp = requests.get(shard + '/api/2.0/libraries/cluster-status?cluster_id='+ clusterid, auth=("token", token))
    libjson = resp.text
    d = json.loads(libjson)
    if (d.get('library_statuses')):
        statuses = d['library_statuses']

        for status in statuses:
            if (status['library'].get('whl')):
                if (status['library']['whl'] == 'dbfs:' + dbfslib):
                    return status['status']
    else:
        # No libraries found
        return "not found"

if __name__ == '__main__':
    main()

Run integration tests from an Azure Databricks notebook

You can also run tests directly from notebooks containing asserts. In this case, you use the same test you used in the unit test, but now it imports the installed appendcol library from the whl that you just installed on the cluster.

To automate this test and include it in the CI/CD pipeline, use the Databricks REST API to execute the notebook from the CI/CD server. This allows you to check whether the notebook execution passed or failed using pytest. Any assert failures appear in the JSON output returned by the REST API and in the JUnit test results.

Step 1: Configure the test environment

Create a Command line task as shown. This task includes commands that create directories for the notebook execution logs and the test summaries. It also includes a pip command to install the required pytest and requests modules.

Azure DevOps configure test environment

Step 2: Run the notebook

Note

As a security best practice, when authenticating with automated tools, systems, scripts, and apps, Databricks recommends you use access tokens belonging to service principals instead of workspace users. To create access tokens for service principals, see Manage access tokens for a service principal.

Create a Python script task and configure it as follows:

  • Set the Script path to $(agent.builddirectory)/cicd-scripts/executeNotebook.py. This script takes six arguments:
    • shard - the URL for the target workspace (for example,https://eastus.azuredatabricks.net)
    • token - a personal access token for workspace
    • clusterid - the ID for the cluster on which to execute the test
    • localpath - the extracted directory containing the test notebooks
    • workspacepath - the path within the workspace to which to test notebooks were deployed
    • outfilepath - the path you created to store the JSON output returned by the REST API

Azure DevOps execute notebooks

The executenotebook.py script runs the notebook using the jobs runs submit endpoint which submits an anonymous job. Because this endpoint is asynchronous, it uses the job ID initially returned by the REST call to the poll for the status of the job. After the job completes, the JSON output is saved to the path specified by the function arguments passed at invocation.

# executenotebook.py
#!/usr/bin/python3
import json
import requests
import os
import sys
import getopt
import time

def main():
    shard = ''
    token = ''
    clusterid = ''
    localpath = ''
    workspacepath = ''
    outfilepath = ''

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hs:t:c:lwo',
                                   ['shard=', 'token=', 'clusterid=', 'localpath=', 'workspacepath=', 'outfilepath='])
    except getopt.GetoptError:
        print(
            'executenotebook.py -s <shard> -t <token>  -c <clusterid> -l <localpath> -w <workspacepath> -o <outfilepath>)')
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print(
                'executenotebook.py -s <shard> -t <token> -c <clusterid> -l <localpath> -w <workspacepath> -o <outfilepath>')
            sys.exit()
        elif opt in ('-s', '--shard'):
            shard = arg
        elif opt in ('-t', '--token'):
            token = arg
        elif opt in ('-c', '--clusterid'):
            clusterid = arg
        elif opt in ('-l', '--localpath'):
            localpath = arg
        elif opt in ('-w', '--workspacepath'):
            workspacepath = arg
        elif opt in ('-o', '--outfilepath'):
            outfilepath = arg

    print('-s is ' + shard)
    print('-t is ' + token)
    print('-c is ' + clusterid)
    print('-l is ' + localpath)
    print('-w is ' + workspacepath)
    print('-o is ' + outfilepath)
    # Generate array from walking local path

    notebooks = []
    for path, subdirs, files in os.walk(localpath):
        for name in files:
            fullpath = path + '/' + name
            # removes localpath to repo but keeps workspace path
            fullworkspacepath = workspacepath + path.replace(localpath, '')

            name, file_extension = os.path.splitext(fullpath)
            if file_extension.lower() in ['.scala', '.sql', '.r', '.py']:
                row = [fullpath, fullworkspacepath, 1]
                notebooks.append(row)

    # run each element in array
    for notebook in notebooks:
        nameonly = os.path.basename(notebook[0])
        workspacepath = notebook[1]

        name, file_extension = os.path.splitext(nameonly)

        # workpath removes extension
        fullworkspacepath = workspacepath + '/' + name

        print('Running job for:' + fullworkspacepath)
        values = {'run_name': name, 'existing_cluster_id': clusterid, 'timeout_seconds': 3600, 'notebook_task': {'notebook_path': fullworkspacepath}}

        resp = requests.post(shard + '/api/2.0/jobs/runs/submit',
                             data=json.dumps(values), auth=("token", token))
        runjson = resp.text
        print("runjson:" + runjson)
        d = json.loads(runjson)
        runid = d['run_id']

        i=0
        waiting = True
        while waiting:
            time.sleep(10)
            jobresp = requests.get(shard + '/api/2.0/jobs/runs/get?run_id='+str(runid),
                             data=json.dumps(values), auth=("token", token))
            jobjson = jobresp.text
            print("jobjson:" + jobjson)
            j = json.loads(jobjson)
            current_state = j['state']['life_cycle_state']
            runid = j['run_id']
            if current_state in ['TERMINATED', 'INTERNAL_ERROR', 'SKIPPED'] or i >= 12:
                break
            i=i+1

        if outfilepath != '':
            file = open(outfilepath + '/' +  str(runid) + '.json', 'w')
            file.write(json.dumps(j))
            file.close()

if __name__ == '__main__':
    main()

Step 3: Generate and evaluate test results

This task executes a Python script using pytest to determine if the asserts in the test notebooks passed or failed.

Create a Command line task. The Script should be:

python -m pytest --junit-xml=$(agent.builddirectory)\logs\xml\TEST-notebookout.xml --jsonpath=$(agent.builddirectory)\logs\json\ $(agent.builddirectory)\cicd-scripts\evaluatenotebookruns.py || true

The arguments are:

  • junit-xml - the path in which to generate the JUnit test summary logs
  • jsonpath - the path you created to store the JSON output returned by the REST API

Azure DevOps generate test results

The script evaluatenotebookruns.py defines the test_job_run function, which parses and evaluates the JSON generated by the previous task. Another test, test_performance, looks for tests that run longer than expected.

# evaluatenotebookruns.py
import unittest
import json
import glob
import os

class TestJobOutput(unittest.TestCase):

    test_output_path = '#ENV#'

    def test_performance(self):
        path = self.test_output_path
        statuses = []

        for filename in glob.glob(os.path.join(path, '*.json')):
            print('Evaluating: ' + filename)
            data = json.load(open(filename))
            duration = data['execution_duration']
            if duration > 100000:
                status = 'FAILED'
            else:
                status = 'SUCCESS'

            statuses.append(status)

        self.assertFalse('FAILED' in statuses)

    def test_job_run(self):
        path = self.test_output_path
        statuses = []

        for filename in glob.glob(os.path.join(path, '*.json')):
            print('Evaluating: ' + filename)
            data = json.load(open(filename))
            status = data['state']['result_state']
            statuses.append(status)

        self.assertFalse('FAILED' in statuses)

if __name__ == '__main__':
    unittest.main()

Publish test results

Use the Publish Test Results task to archive the JSON results and publish the test results to Azure DevOps Test Hub. This enables you to visualize reports and dashboards related to the status of the test runs.

Azure DevOps publish test results

At this point, you have completed an integration and deployment cycle using the CI/CD pipeline. By automating this process, you ensure that your code is tested and deployed by an efficient, consistent, and repeatable process.