如何通过代码自动获取Amazon SageMaker实例的实例类型?
获取Amazon SageMaker实例类型的方法
方法1:在SageMaker实例内部直接获取
SageMaker实例本质是EC2实例的一种,可通过EC2实例元数据服务直接获取实例类型,这个方法仅能在运行中的SageMaker实例内部执行:import requests def get_sagemaker_instance_type(): try: # 访问本地元数据服务 response = requests.get('http://169.254.169.254/latest/meta-data/instance-type', timeout=2) return response.text except requests.exceptions.RequestException: return "无法获取实例类型(当前环境非SageMaker实例内部)" instance_type = get_sagemaker_instance_type() print(instance_type)方法2:通过boto3查询SageMaker资源信息
如果脚本在外部环境运行,需先明确目标SageMaker资源(如笔记本实例、训练作业、终端节点)的名称,再通过boto3客户端查询对应实例类型:import boto3 # 查询笔记本实例的实例类型 def get_notebook_instance_type(notebook_name): sagemaker_client = boto3.client('sagemaker') response = sagemaker_client.describe_notebook_instance(NotebookInstanceName=notebook_name) return response['InstanceType'] # 替换为你的笔记本实例名称 target_notebook = "your-notebook-name" instance_type = get_notebook_instance_type(target_notebook) print(instance_type)针对训练作业,可使用
describe_training_job方法;针对终端节点,可使用describe_endpoint_config方法,均能从返回结果中提取InstanceType字段。
内容的提问来源于stack exchange,提问作者sam.hay
相关产品推荐
相关产品推荐

