Terraform을 사용하여 클러스터, Notebook 및 작업 만들기

이 문서에서는 Databricks Terraform 공급자를 사용하여 기존 Azure Databricks 작업 영역에서 클러스터, Notebook작업을 만드는 방법을 보여줍니다.

이 문서는 다음 Azure Databricks 시작 문서의 도우미입니다.

이 문서의 Terraform 구성을 조정하여 작업 영역에서 사용자 지정 클러스터, Notebook 및 작업을 만들 수도 있습니다.

1단계: Terraform 프로젝트 만들기 및 구성

  1. Databricks Terraform 공급자 개요 문서의 요구 사항 섹션에 있는 지침에 따라 Terraform 프로젝트를 만듭니다.

  2. 클러스터를 만들려면 이름이 지정된 cluster.tf파일을 만들고 파일에 다음 콘텐츠를 추가합니다. 이 콘텐츠는 허용되는 리소스가 가장 적은 클러스터를 만듭니다. 이 클러스터는 최신 Databricks LTS Runtime(장기 지원) 버전을 사용합니다.

    Unity 카탈로그와 함께 작동하는 클러스터의 경우:

    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
    }
    

    다목적 클러스터의 경우:

    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
    }
    
  3. 클러스터를 만들려면 이름이 다른 cluster.auto.tfvars파일을 만들고 다음 콘텐츠를 파일에 추가합니다. 이 파일에는 클러스터를 사용자 지정하기 위한 변수 값이 포함되어 있습니다. 자리 표시자 값을 사용자 고유의 값으로 바꿉니다.

    Unity 카탈로그와 함께 작동하는 클러스터의 경우:

    cluster_name                    = "My Cluster"
    cluster_autotermination_minutes = 60
    cluster_num_workers             = 1
    cluster_data_security_mode      = "SINGLE_USER"
    

    다목적 클러스터의 경우:

    cluster_name                    = "My Cluster"
    cluster_autotermination_minutes = 60
    cluster_num_workers             = 1
    
  4. Notebook을 만들려면 이름이 다른 notebook.tf파일을 만들고 파일에 다음 콘텐츠를 추가합니다.

    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
    }
    
  5. 클러스터를 만드는 경우 파일과 동일한 디렉터리의 파일에 다음 Notebook 코드를 저장합니다 notebook.tf .

    자습서: 엔드투엔드 레이크하우스 분석 파이프라인 실행을 위한 Python Notebook의 경우 다음 콘텐츠가 포함된 notebook-getting-started-lakehouse-e2e.py라는 파일이 있습니다.

    # 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)
    

    빠른 시작: Azure Portal을 사용하여 Azure Databricks 작업 영역에서 Spark 작업 실행에 대한 Python Notebook의 경우 다음 콘텐츠가 포함된 notebook-quickstart-create-databricks-workspace-portal.py라는 파일입니다.

    # 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'))
    
  6. Notebook을 만드는 경우 이름이 다른 notebook.auto.tfvars파일을 만들고 파일에 다음 콘텐츠를 추가합니다. 이 파일에는 Notebook 구성을 사용자 지정하기 위한 변수 값이 포함되어 있습니다.

    자습서: 엔드투엔드 레이크하우스 분석 파이프라인 실행을 위한 Python Notebook의 경우:

    notebook_subdirectory = "Terraform"
    notebook_filename     = "notebook-getting-started-lakehouse-e2e.py"
    notebook_language     = "PYTHON"
    

    빠른 시작: Azure Portal을 사용하여 Azure Databricks 작업 영역에서 Spark 작업 실행에 대한 Python Notebook의 경우:

    notebook_subdirectory = "Terraform"
    notebook_filename     = "notebook-quickstart-create-databricks-workspace-portal.py"
    notebook_language     = "PYTHON"
    
  7. Notebook을 만드는 경우 Azure Databricks 작업 영역에서 다음 지침을 참조하여 Notebook이 성공적으로 실행되도록 요구 사항을 설정해야 합니다.

  8. 작업을 만들려면 이름이 다른 job.tf파일을 만들고 파일에 다음 콘텐츠를 추가합니다. 이 콘텐츠는 Notebook을 실행하는 작업을 만듭니다.

    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
    }
    
  9. 작업을 만드는 경우 job.auto.tfvars라는 다른 파일을 만들고 다음 콘텐츠를 파일에 추가합니다. 이 파일에는 작업 구성을 사용자 지정하기 위한 변수 값이 포함되어 있습니다.

    job_name = "My Job"
    task_key = "my_task"
    

2단계: 구성 실행

이 단계에서는 Terraform 구성을 실행하여 클러스터, Notebook 및 작업을 Azure Databricks 작업 영역에 배포합니다.

  1. terraform validate 명령을 실행하여 Terraform 구성이 유효한지 확인합니다. 오류가 보고되면 수정하고 명령을 다시 실행합니다.

    terraform validate
    
  2. Terraform이 실제로 작업을 수행하기 전에 terraform plan 명령을 실행하여 작업 영역에서 Terraform이 수행할 작업을 확인합니다.

    terraform plan
    
  3. terraform apply 명령을 실행하여 클러스터, Notebook 및 작업을 작업 영역에 배포합니다. 배포하라는 메시지가 표시되면 yes를 입력하고 Enter를 누릅니다.

    terraform apply
    

    Terraform은 프로젝트에 지정된 리소스를 배포합니다. 이러한 리소스(특히 클러스터)를 배포하는 데 몇 분 정도 걸릴 수 있습니다.

단계 3: 결과 살펴보기

  1. 클러스터를 만든 경우 terraform apply 명령의 출력에서 cluster_url 옆에 있는 링크를 복사하여 웹 브라우저의 주소 표시줄에 붙여넣습니다.

  2. Notebook을 만든 경우 terraform apply 명령의 출력에서 notebook_url 옆에 있는 링크를 복사하여 웹 브라우저의 주소 표시줄에 붙여넣습니다.

    참고 항목

    Notebook을 사용하기 전에 해당 콘텐츠를 사용자 지정해야 할 수 있습니다. Notebook을 사용자 지정하는 방법에 대한 관련 설명서를 참조하세요.

  3. 작업을 만든 경우 terraform apply 명령의 출력에서 job_url 옆에 있는 링크를 복사하여 웹 브라우저의 주소 표시줄에 붙여넣습니다.

    참고 항목

    Notebook을 실행하기 전에 해당 콘텐츠를 사용자 지정해야 할 수 있습니다. Notebook을 사용자 지정하는 방법에 대한 관련 설명서는 이 문서의 시작 부분에 있는 링크를 참조하세요.

  4. 작업을 만든 경우 다음과 같이 작업을 실행합니다.

    1. 작업 페이지에서 지금 실행을 클릭합니다.
    2. 작업 실행이 완료된 후 작업 실행 결과를 보려면 작업 페이지의 완료된 실행(지난 60일) 목록에서 시작 시간 열의 가장 최근 시간 항목을 클릭합니다. 출력 창에는 Notebook의 코드를 실행한 결과가 표시됩니다.

4단계: 정리

이 단계에서는 작업 영역에서 이전 리소스를 삭제합니다.

  1. Terraform이 실제로 작업을 수행하기 전에 terraform plan 명령을 실행하여 작업 영역에서 Terraform이 수행할 작업을 확인합니다.

    terraform plan
    
  2. terraform destroy 명령을 실행하여 작업 영역에서 클러스터, Notebook 및 작업을 삭제합니다. 삭제하라는 메시지가 표시되면 yes를 입력하고 Enter를 누릅니다.

    terraform destroy
    

    Terraform은 프로젝트에 지정된 리소스를 삭제합니다.