New Toy at Work: Databricks
We have an existing system, Scorecard, that we want to migrate to Databricks. The first thing I thought was "Oh no, Databricks only executes notebooks, and all my files are in unmanaged .py files. Am I going to have to re-write my all this existing code as notebooks?!". No you do not! It is very easy to migrate from a python program to a Databricks notebook with hardly any modification.
We recently procured Databricks to replace our Windows Server and Airflow jobs. Databricks gives us many capabilities. It providing a professional data engineering as well as a data science environment, getting us off unlicensed free services like Collab, or Jupyter which doesn't play well with our proxy. It will allow non-programmers to monitor and trigger workflows, and makes it easy to diagnose issues through email services. It supports Git, and is really and all-in-one IDE, including a strong AI for code completion, documentation, and API reference, that is trained thoroughly on Databricks Systems and seldom hallucinates.
There are three main goals I wanted to accomplish in this migration.
- First I wanted to use git to pull my existing python libraries into Git and do a complete migration.
- Second I needed to replace the plaintext dotenv file with an encrypted secret system.
-
Third I needed to migrate my non-databricks .py files into the new system, without having to put everything into notebooks and re-writing everything.
So I want to share how I got these three critical tasks accomplished.
Connecting to Git
There are two locations to create a Git repository. The old way was to use the
directory, or create a service user the team can log in as to execute the code. this is on my to-do list./Repolocation at the root of the workspace. This would be visible and editable to everyone. What Databricks encourages you to do now is to place your repo inside your home directory. For me this is at/Workspace/Users/<**@***il.address>/<my-repo-name>This will keep your code separate and private. I am not sure the best way to deploy the production code, either pull the production repo into the/ReposHow do you connect to a GitHub Repo? I will be brief. First you create a Personal Access Token inside GitHub. Then you paste your token under User Icon > Settings > Linked Accounts > Git Integration. You may paste your PAT here.
To create a repo, you right click the Workspace tab and right-click on the house icon on your home
, and select Create > Git Folder. You should be authenticated with your PAT, just give the URL of your repo. If you click on the box with the branch name, that is your Git interface, where you may pull, branch, stage, and commit your files. Pretty minimal, but it gets the job done without leaving the Databricks web interface./Workspace/Users/<yo**@***il.address>or~/Handling Secrets
It took me a little while to grok this, but it is easy. Although you may execute any python script by calling
, everything ultimately has to be inside a notebook at the root level. And it is inside this notebook that you set your environment variables. The environment is the Notebook.%sh python <your_script.py>But before we get any further, how do you create secrets? To create secrets, you must use the CLI, either the CLI on your local computer, or the Web CLI found in the lower-right hand corner of the code pane.
Inside the CLI you create a scope. This may be shared across users.
12databricks secrets create-scope --scope my-secret-scope --initial-manage-principal usersdatabricks secrets list-scopesNow that you have a scope, you may set key-value pairs, again in the Web CLI.
1234567databricks secrets put-secret --json '{"scope": "my-secret-scope","key": "SECRET_KEY_EXAMPLE","string_value": "0a0a0a0a0a0a0a0a0a0a0a0a"}'#to list your secret keys, but not valuesdatabricks secrets list-secrets my-secret-scope
Although the secrets are not completely secure, it will do a decent job obfuscating them for the standard terminal user, so they may use secrets without knowing them. If you do print(MY_SECRET_KEY_EXAMPLE) it will say [REDACTED]
Now that the secrets are in the vault, how do I access them?
I wrote a little script to do this.
|
1 2 3 4 5 |
import os def set_environment_from_key(key): secret = dbutils.secrets.get(scope="<your-secret-scope>", key=key) os.environ[key] = secret |
|
1 |
the command |
|
1 |
dbutils.secrets.get(scope, key) |
is how you use spark to pull in secrets stored inside your secret scope. The custom function set_environment_from_key() is sets the secret. You use this as follows:
|
1 2 |
set_environment_from_key('AWS_ACCESS_KEY_ID') set_environment_from_key('AWS_SECRET_ACCESS_KEY') |
Etc. Now those secrets exist within the scope of your block of code. So you instantiate these variables in a block of code. The secrets live as environment variables inside your block of code in the notebook. You may execute your python script, and it will be aware of the environment variables set in the notebook. Here is a complete example:
|
1 2 3 4 5 6 7 8 9 |
import os def set_environment_from_key(key): secret = dbutils.secrets.get(scope="<your-secret-scope>", key=key) os.environ[key] = secret set_environment_from_key('AWS_REGION') !python /Workspace/Users/<email-address>/<repo-dirname>/test_script.py |
Inside your test_script.py you may pull the environment variables as if they were in a dotenv file.
|
1 2 3 4 5 6 7 8 9 |
class Secrets: def __init__(self, is_production: bool = False): self.AWS_REGION = os.getenv('AWS_REGION') self.AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') ... #pull your secrets from the environment here #and instantiate them in the Secrets Data Transfer Object. ... |
To make secret handling easy on myself, for the Scorecard project I created a class called Secrets where I instantiate all my environmental variables, including dev and prod flags, into this object. I set these secrets once in a Secrets class, and pass the instantiated object in when I instantiate my other other classes, rather than each class pulling their own secrets.
Executing Legacy .py Files
To bring it all together, I may execute my code from my legacy .py files by
- installing dependencies
- setting environment variables
- calling the script.
Here is how you run pytest
|
1 2 3 4 |
%pip install pytest #install dependencies here #after installing using pip, restart python %restart_python |
In a new block, set your environment and execute pytest
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import os def set_environment_from_key(key): secret = dbutils.secrets.get(scope="ops-secret-scope", key=key) os.environ[key] = secret set_environment_from_key('AWS_REGION') ... #set other environment variables here !pytest test_unit.py |
Inside test_unit.py
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#import statements here from scorecard_secrets import Secrets from scorecard_s3 import S3 class Test_All: def setup_method(self): #set secrets once. self.secrets = Secrets(is_production=False) ### test S3 ### def test_s3_initialize(self): #testing my custom s3 library. #Pass in the secret object. s3 = S3(self.secrets) assert s3.client is not None assert s3.resource is not None |
Conclusion
So not only am I executing using pytest, which is outside a notebook, I am creating a Secrets object by importing scorecard_secrets, also a .py file not in a notebook, instantiating it in my Test class, and passing it in to other python classes I already created, which were never in notebooks. Really I was able to import my entire Scorecard app without hardly any changes, except for setting the environment variables in the outermost block in the outermost notebook.test_unit.py
I hope this will help you get started in your Databricks journey. It is totally doable to migrate your existing python workflows over to Databricks.
Leave A Reply