Azure Databricks 12.0版本获取集群信息的替代方案咨询
Azure Databricks 12.0+ 获取集群信息的替代方案及完整集群信息获取方法
一、替代旧tags()方法的方案
升级至Databricks Runtime 12.0+后,原dbutils.notebook.entry_point.getDbutils().notebook().getContext().tags()因安全限制无法使用,可通过以下方式获取常用上下文/集群信息:
直接通过Context对象获取核心字段
# 获取集群ID cluster_id = dbutils.notebook.entry_point.getDbutils().notebook().getContext().clusterId().get() # 获取集群名称 cluster_name = dbutils.notebook.entry_point.getDbutils().notebook().getContext().clusterName().get() # 获取当前登录用户 current_user = dbutils.notebook.entry_point.getDbutils().notebook().getContext().userName().get() # 获取工作区URL workspace_url = dbutils.notebook.entry_point.getDbutils().notebook().getContext().browserHostName().get()
通过Spark配置获取集群标签类信息
Spark配置中包含大量集群相关的标签数据,可通过spark.conf直接读取:
# 获取集群Spark版本 spark_version = spark.conf.get("spark.databricks.clusterUsageTags.sparkVersion") # 获取集群节点类型 node_type = spark.conf.get("spark.databricks.clusterUsageTags.nodeTypeId") # 获取集群名称(另一种方式) cluster_name_alt = spark.conf.get("spark.databricks.clusterUsageTags.clusterName") # 获取集群所属工作区ID workspace_id = spark.conf.get("spark.databricks.clusterUsageTags.workspaceId")
二、获取完整集群信息的方法
方法1:在Notebook中调用Databricks REST API
通过Clusters Get接口获取集群的完整配置、状态、节点信息等,示例代码:
import requests import json # 从上下文自动获取必要参数 workspace_host = dbutils.notebook.entry_point.getDbutils().notebook().getContext().browserHostName().get() target_cluster_id = dbutils.notebook.entry_point.getDbutils().notebook().getContext().clusterId().get() # 替换为你的个人访问令牌(PAT) pat_token = "your-personal-access-token" # 构建API请求 headers = { "Authorization": f"Bearer {pat_token}", "Content-Type": "application/json" } api_url = f"https://{workspace_host}/api/2.0/clusters/get" request_params = {"cluster_id": target_cluster_id} # 发送请求并解析结果 response = requests.get(api_url, headers=headers, params=request_params) full_cluster_info = json.loads(response.text) # 格式化输出完整信息 print(json.dumps(full_cluster_info, indent=2))
注意:需确保PAT拥有
clusters:read权限,且集群网络可访问工作区API端点。
方法2:使用Databricks CLI
若在本地终端或集群终端操作,可通过CLI直接获取:
# 替换为目标集群ID databricks clusters get --cluster-id <your-cluster-id>
前提是已完成CLI配置(通过
databricks configure设置工作区URL和PAT)。
内容的提问来源于stack exchange,提问作者Venkatesh
相关产品推荐
相关产品推荐

