Nota:
El acceso a esta página requiere autorización. Puede intentar iniciar sesión o cambiar directorios.
El acceso a esta página requiere autorización. Puede intentar cambiar los directorios.
En este artículo se muestra cómo usar el proveedor de Terraform de Databricks para crear un clúster, un cuaderno y un trabajo en un área de trabajo de Azure Databricks existente.
También puede adaptar las configuraciones de Terraform de este artículo para crear clústeres, cuadernos y trabajos personalizados en las áreas de trabajo.
Paso 1: Crear y configurar el proyecto de Terraform
Cree un proyecto de Terraform siguiendo las instrucciones de la sección Requisitos del artículo de información general del proveedor de Databricks Terraform.
Para crear un clúster, cree un archivo denominado
cluster.tfy agregue el siguiente contenido al archivo. Este contenido crea un clúster con la menor cantidad de recursos permitidos. Este clúster usa la versión de soporte técnico a largo plazo (LTS) de Databricks Runtime más reciente.Para un clúster que funciona con el Unity Catalog:
variable "cluster_name" {} variable "cluster_autotermination_minutes" {} variable "cluster_num_workers" {} variable "cluster_data_security_mode" {} # Create the cluster with the "smallest" amount # of resources allowed. data "databricks_node_type" "smallest" { local_disk = true } # Use the latest Databricks Runtime # Long Term Support (LTS) version. data "databricks_spark_version" "latest_lts" { long_term_support = true } resource "databricks_cluster" "this" { cluster_name = var.cluster_name node_type_id = data.databricks_node_type.smallest.id spark_version = data.databricks_spark_version.latest_lts.id autotermination_minutes = var.cluster_autotermination_minutes num_workers = var.cluster_num_workers data_security_mode = var.cluster_data_security_mode } output "cluster_url" { value = databricks_cluster.this.url }Para un clúster de uso completo:
variable "cluster_name" { description = "A name for the cluster." type = string default = "My Cluster" } variable "cluster_autotermination_minutes" { description = "How many minutes before automatically terminating due to inactivity." type = number default = 60 } variable "cluster_num_workers" { description = "The number of workers." type = number default = 1 } # Create the cluster with the "smallest" amount # of resources allowed. data "databricks_node_type" "smallest" { local_disk = true } # Use the latest Databricks Runtime # Long Term Support (LTS) version. data "databricks_spark_version" "latest_lts" { long_term_support = true } resource "databricks_cluster" "this" { cluster_name = var.cluster_name node_type_id = data.databricks_node_type.smallest.id spark_version = data.databricks_spark_version.latest_lts.id autotermination_minutes = var.cluster_autotermination_minutes num_workers = var.cluster_num_workers } output "cluster_url" { value = databricks_cluster.this.url }Para crear un clúster, cree otro archivo denominado
cluster.auto.tfvarsy agregue el siguiente contenido al archivo. Este archivo contiene valores de variable para personalizar el clúster. Reemplace los valores de los marcadores de posición por sus propios valores.Para un clúster que funciona con el Unity Catalog:
cluster_name = "My Cluster" cluster_autotermination_minutes = 60 cluster_num_workers = 1 cluster_data_security_mode = "SINGLE_USER"Para un clúster de uso completo:
cluster_name = "My Cluster" cluster_autotermination_minutes = 60 cluster_num_workers = 1Para crear un cuaderno, cree otro archivo denominado
notebook.tfy agregue el siguiente contenido al archivo:variable "notebook_subdirectory" { description = "A name for the subdirectory to store the notebook." type = string default = "Terraform" } variable "notebook_filename" { description = "The notebook's filename." type = string } variable "notebook_language" { description = "The language of the notebook." type = string } resource "databricks_notebook" "this" { path = "${data.databricks_current_user.me.home}/${var.notebook_subdirectory}/${var.notebook_filename}" language = var.notebook_language source = "./${var.notebook_filename}" } output "notebook_url" { value = databricks_notebook.this.url }Si va a crear un clúster, guarde el siguiente código de cuaderno en un archivo en el mismo directorio que el archivo
notebook.tf:Para el cuaderno de Python, use el código siguiente:
# Databricks notebook source external_location = "<your_external_location>" catalog = "<your_catalog>" dbutils.fs.put(f"{external_location}/foobar.txt", "Hello world!", True) display(dbutils.fs.head(f"{external_location}/foobar.txt")) dbutils.fs.rm(f"{external_location}/foobar.txt") display(spark.sql(f"SHOW SCHEMAS IN {catalog}")) # COMMAND ---------- from pyspark.sql.functions import col # Set parameters for isolation in workspace and reset demo username = spark.sql("SELECT regexp_replace(current_user(), '[^a-zA-Z0-9]', '_')").first()[0] database = f"{catalog}.e2e_lakehouse_{username}_db" source = f"{external_location}/e2e-lakehouse-source" table = f"{database}.target_table" checkpoint_path = f"{external_location}/_checkpoint/e2e-lakehouse-demo" spark.sql(f"SET c.username='{username}'") spark.sql(f"SET c.database={database}") spark.sql(f"SET c.source='{source}'") spark.sql("DROP DATABASE IF EXISTS ${c.database} CASCADE") spark.sql("CREATE DATABASE ${c.database}") spark.sql("USE ${c.database}") # Clear out data from previous demo execution dbutils.fs.rm(source, True) dbutils.fs.rm(checkpoint_path, True) # Define a class to load batches of data to source class LoadData: def __init__(self, source): self.source = source def get_date(self): try: df = spark.read.format("json").load(source) except: return "2016-01-01" batch_date = df.selectExpr("max(distinct(date(tpep_pickup_datetime))) + 1 day").first()[0] if batch_date.month == 3: raise Exception("Source data exhausted") return batch_date def get_batch(self, batch_date): return ( spark.table("samples.nyctaxi.trips") .filter(col("tpep_pickup_datetime").cast("date") == batch_date) ) def write_batch(self, batch): batch.write.format("json").mode("append").save(self.source) def land_batch(self): batch_date = self.get_date() batch = self.get_batch(batch_date) self.write_batch(batch) RawData = LoadData(source) # COMMAND ---------- RawData.land_batch() # COMMAND ---------- # Import functions from pyspark.sql.functions import col, current_timestamp # Configure Auto Loader to ingest JSON data to a Delta table (spark.readStream .format("cloudFiles") .option("cloudFiles.format", "json") .option("cloudFiles.schemaLocation", checkpoint_path) .load(file_path) .select("*", col("_metadata.file_path").alias("source_file"), current_timestamp().alias("processing_time")) .writeStream .option("checkpointLocation", checkpoint_path) .trigger(availableNow=True) .option("mergeSchema", "true") .toTable(table)) # COMMAND ---------- df = spark.read.table(table_name) # COMMAND ---------- display(df)Para el cuaderno de Python para inicio rápido: Ejecución de un trabajo de Spark en el área de trabajo de Azure Databricks mediante el Azure Portal, un archivo denominado
notebook-quickstart-create-databricks-workspace-portal.pycon el siguiente contenido:# Databricks notebook source blob_account_name = "azureopendatastorage" blob_container_name = "citydatacontainer" blob_relative_path = "Safety/Release/city=Seattle" blob_sas_token = r"" # COMMAND ---------- wasbs_path = 'wasbs://%s@%s.blob.core.windows.net/%s' % (blob_container_name, blob_account_name,blob_relative_path) spark.conf.set('fs.azure.sas.%s.%s.blob.core.windows.net' % (blob_container_name, blob_account_name), blob_sas_token) print('Remote blob path: ' + wasbs_path) # COMMAND ---------- df = spark.read.parquet(wasbs_path) print('Register the DataFrame as a SQL temporary view: source') df.createOrReplaceTempView('source') # COMMAND ---------- print('Displaying top 10 rows: ') display(spark.sql('SELECT * FROM source LIMIT 10'))Si va a crear un cuaderno, cree otro archivo denominado
notebook.auto.tfvarsy agregue el siguiente contenido al archivo. Este archivo contiene valores de variable para personalizar la configuración del cuaderno.Para el cuaderno de Python:
notebook_subdirectory = "Terraform" notebook_filename = "notebook-getting-started-lakehouse-e2e.py" notebook_language = "PYTHON"Para el cuaderno de Python para Inicio rápido: Ejecución de un trabajo de Spark en un área de trabajo de Azure Databricks con Azure Portal:
notebook_subdirectory = "Terraform" notebook_filename = "notebook-quickstart-create-databricks-workspace-portal.py" notebook_language = "PYTHON"Para crear el trabajo, cree otro archivo denominado
job.tfy agregue el siguiente contenido al archivo. Este contenido crea un trabajo para ejecutar el cuaderno.variable "job_name" { description = "A name for the job." type = string default = "My Job" } variable "task_key" { description = "A name for the task." type = string default = "my_task" } resource "databricks_job" "this" { name = var.job_name task { task_key = var.task_key existing_cluster_id = databricks_cluster.this.cluster_id notebook_task { notebook_path = databricks_notebook.this.path } } email_notifications { on_success = [ data.databricks_current_user.me.user_name ] on_failure = [ data.databricks_current_user.me.user_name ] } } output "job_url" { value = databricks_job.this.url }Si va a crear un trabajo, cree otro archivo denominado
job.auto.tfvarsy agregue el siguiente contenido al archivo. Este archivo contiene un valor variable para personalizar la configuración del trabajo.job_name = "My Job" task_key = "my_task"
Paso 2: Ejecución de la configuración
En este paso, ejecutará las configuraciones de Terraform para implementar el clúster, el cuaderno y el trabajo en el área de trabajo de Azure Databricks.
Compruebe si las configuraciones de Terraform son válidas mediante la ejecución del comando
terraform validate. Si se notifican errores, corríjalos y vuelva a ejecutar el comando.terraform validateCompruebe lo que Hará Terraform en el área de trabajo, antes de que Terraform lo haga realmente, ejecutando el comando
terraform plan.terraform planImplemente el clúster, el cuaderno y el trabajo en el área de trabajo mediante la ejecución del comando
terraform apply. Al solicitar la implementación, escribayesy pulse Introducir.terraform applyTerraform implementa los recursos especificados en el proyecto. La implementación de estos recursos (especialmente un clúster) puede tardar varios minutos.
Paso 3: Explorar los recursos
Si ha creado un clúster, en la salida del
terraform applycomando, copie el vínculo junto acluster_urly péguelo en la barra de direcciones del explorador web.Si ha creado un cuaderno, en la salida del
terraform applycomando, copie el vínculo junto anotebook_urly péguelo en la barra de direcciones del explorador web.Nota:
Antes de usar el cuaderno, es posible que tenga que personalizar su contenido. Consulte la documentación relacionada sobre cómo personalizar el cuaderno.
Si ha creado un trabajo, en la salida del
terraform applycomando, copie el vínculo junto ajob_urly péguelo en la barra de direcciones del explorador web.Nota:
Antes de ejecutar el cuaderno, es posible que tenga que personalizar su contenido. Consulte los vínculos al principio de este artículo para obtener documentación relacionada sobre cómo personalizar el cuaderno.
Si ha creado un trabajo, ejecute el trabajo de la siguiente manera:
- Haga clic en Ejecutar ahora en la página de trabajos.
- Una vez que el trabajo termine de ejecutarse, para ver los resultados de la ejecución del trabajo, en la lista Ejecuciones completadas (últimos 60 días) de la página del trabajo, haga clic en la entrada de hora más reciente en la columna Hora de inicio . El panel Salida muestra el resultado de ejecutar el código del cuaderno.
Paso 4: Limpieza
En este paso, eliminará los recursos anteriores del área de trabajo.
Compruebe lo que Hará Terraform en el área de trabajo, antes de que Terraform lo haga realmente, ejecutando el comando
terraform plan.terraform planElimine el clúster, el cuaderno y el trabajo del área de trabajo mediante la ejecución del comando
terraform destroy. Al solicitar la eliminación, escribayesy pulse Introducir.terraform destroyTerraform elimina los recursos especificados en el proyecto.