HDInsight SDK per PythonHDInsight SDK for Python
PanoramicaOverview
HDInsight SDK per Python fornisce classi e metodi che consentono di gestire i cluster HDInsight.The HDInsight SDK for Python provides classes and methods that allow you to manage your HDInsight clusters. Include operazioni per creare, eliminare, aggiornare, elencare, ridimensionare, eseguire azioni di script, monitorare, ottenere le proprietà dei cluster di HDInsight e altro ancora.It includes operations to create, delete, update, list, resize, execute script actions, monitor, get properties of HDInsight clusters, and more.
PrerequisitiPrerequisites
- Un account Azure.An Azure account. Se non è disponibile, ottenere una versione di valutazione gratuita.If you don't have one, get a free trial.
- PythonPython
- pippip
Installazione dell'SDKSDK Installation
HDInsight SDK per Python è disponibile nell'indice di pacchetti Python e può essere installato eseguendo questo comando:The HDInsight SDK for Python can be found in the Python Package Index and can be installed by running:
pip install azure-mgmt-hdinsight
AuthenticationAuthentication
L'SDK deve essere prima autenticato con la sottoscrizione di Azure.The SDK first needs to be authenticated with your Azure subscription. Seguire questo esempio per creare un'entità servizio e usarla per l'autenticazione.Follow the example below to create a service principal and use it to authenticate. Al termine si avrà un'istanza di un HDInsightManagementClient
che contiene molti metodi, descritti nelle sezioni seguenti, che possono essere usati per operazioni di gestione.After this is done, you will have an instance of an HDInsightManagementClient
, which contains many methods (outlined in below sections) that can be used to perform management operations.
Nota
Oltre all'esempio seguente esistono altre modalità di autenticazione che possono essere più adatte alle proprie esigenze.There are other ways to authenticate besides the below example that could potentially be better suited for your needs. Tutti i metodi sono descritti di seguito: Eseguire l'autenticazione con le librerie di gestione di Azure per PythonAll methods are outlined here: Authenticate with the Azure Management Libraries for Python
Esempio di autenticazione con un'entità servizioAuthentication Example Using a Service Principal
Per prima cosa, accedere ad Azure Cloud Shell.First, login to Azure Cloud Shell. Verificare che si stia attualmente usando la sottoscrizione in cui si vuole creare l'entità servizio.Verify you are currently using the subscription in which you want the service principal created.
az account show
Le informazioni sulla sottoscrizione vengono visualizzate in formato JSON.Your subscription information is displayed as JSON.
{
"environmentName": "AzureCloud",
"id": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"isDefault": true,
"name": "XXXXXXX",
"state": "Enabled",
"tenantId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"user": {
"cloudShellID": true,
"name": "XXX@XXX.XXX",
"type": "user"
}
}
Se non si è eseguito l'accesso alla sottoscrizione corretta, selezionare quella corretta eseguendo:If you're not logged into the correct subscription, select the correct one by running:
az account set -s <name or ID of subscription>
Importante
Se il provider di risorse HDInsight non è già stato registrato con un altro metodo, ad esempio creando un cluster HDInsight tramite il portale di Azure, è necessario eseguire questa operazione una volta prima di poter eseguire l'autenticazione.If you have not already registered the HDInsight Resource Provider by another method (such as by creating an HDInsight Cluster through the Azure Portal), you need to do this once before you can authenticate. La registrazione può essere eseguita da Azure Cloud Shell eseguendo questo comando:This can be done from the Azure Cloud Shell by running the following command:
az provider register --namespace Microsoft.HDInsight
Scegliere quindi un nome per l'entità servizio e crearla con il comando seguente:Next, choose a name for your service principal and create it with the following command:
az ad sp create-for-rbac --name <Service Principal Name> --sdk-auth
Verranno visualizzate le informazioni relative all'entità servizio in formato JSON.The service principal information is displayed as JSON.
{
"clientId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"clientSecret": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"subscriptionId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"tenantId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}
Copiare il frammento di codice Python seguente e compilare TENANT_ID
, CLIENT_ID
, CLIENT_SECRET
e SUBSCRIPTION_ID
con le stringhe JSON restituite dopo l'esecuzione del comando per creare l'entità servizio.Copy the below Python snippet and fill in TENANT_ID
, CLIENT_ID
, CLIENT_SECRET
, and SUBSCRIPTION_ID
with the strings from the JSON that was returned after running the command to create the service principal.
from azure.mgmt.hdinsight import HDInsightManagementClient
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.hdinsight.models import *
# Tenant ID for your Azure Subscription
TENANT_ID = ''
# Your Service Principal App Client ID
CLIENT_ID = ''
# Your Service Principal Client Secret
CLIENT_SECRET = ''
# Your Azure Subscription ID
SUBSCRIPTION_ID = ''
credentials = ServicePrincipalCredentials(
client_id = CLIENT_ID,
secret = CLIENT_SECRET,
tenant = TENANT_ID
)
client = HDInsightManagementClient(credentials, SUBSCRIPTION_ID)
Gestione dei clusterCluster Management
Nota
Questa sezione presuppone che l'utente abbia già eseguito l'autenticazione e abbia creato un'istanza HDInsightManagementClient
che ha poi archiviato in una variabile chiamata client
.This section assumes you have already authenticated and constructed an HDInsightManagementClient
instance and store it in a variable called client
. Le istruzioni per l'autenticazione e l'ottenimento di un HDInsightManagementClient
sono disponibili nella sezione Autenticazione precedente.Instructions for authenticating and obtaining an HDInsightManagementClient
can be found in the Authentication section above.
Creare un clusterCreate a Cluster
Un nuovo cluster può essere creato chiamando client.clusters.create()
.A new cluster can be created by calling client.clusters.create()
.
EsempiSamples
Sono disponibili esempi di codice per la creazione di diversi tipi comuni di cluster HDInsight: Esempi di HDInsight per Python.Code samples for creating several common types of HDInsight clusters are available: HDInsight Python Samples.
EsempioExample
Questo esempio illustra come creare un cluster Spark con 2 nodi head e 1 nodo del ruolo di lavoro.This example demonstrates how to create a Spark cluster with 2 head nodes and 1 worker node.
Nota
È prima necessario creare un gruppo di risorse e un account di archiviazione, come spiegato di seguito.You first need to create a Resource Group and Storage Account, as explained below. Se sono già stati creati, è possibile ignorare questi passaggi.If you have already created these, you can skip these steps.
Creazione di un gruppo di risorseCreating a Resource Group
È possibile creare un gruppo di risorse con Azure Cloud Shell eseguendoYou can create a resource group using the Azure Cloud Shell by running
az group create -l <Region Name (i.e. eastus)> --n <Resource Group Name>
Creazione di un account di archiviazioneCreating a Storage Account
È possibile creare un account di archiviazione con Azure Cloud Shell eseguendo:You can create a storage account using the Azure Cloud Shell by running:
az storage account create -n <Storage Account Name> -g <Existing Resource Group Name> -l <Region Name (i.e. eastus)> --sku <SKU i.e. Standard_LRS>
Eseguire ora questo comando per ottenere la chiave per l'account di archiviazione. Questa chiave sarà necessaria per creare un cluster:Now run the following command to get the key for your storage account (you will need this to create a cluster):
az storage account keys list -n <Storage Account Name>
Il frammento di codice Python seguente crea un cluster Spark con 2 nodi head e 1 nodo del ruolo di lavoro.The below Python snippet creates a Spark cluster with 2 head nodes and 1 worker node. Inserire le variabili vuote come spiegato nei commenti. È possibile modificare altri parametri in base alle proprie esigenze.Fill in the blank variables as explained in the comments and feel free to change other parameters to suit your specific needs.
# The name for the cluster you are creating
cluster_name = ""
# The name of your existing Resource Group
resource_group_name = ""
# Choose a username
username = ""
# Choose a password
password = ""
# Replace <> with the name of your storage account
storage_account = "<>.blob.core.windows.net"
# Storage account key you obtained above
storage_account_key = ""
# Choose a region
location = ""
container = "default"
params = ClusterCreateProperties(
cluster_version="3.6",
os_type=OSType.linux,
tier=Tier.standard,
cluster_definition=ClusterDefinition(
kind="spark",
configurations={
"gateway": {
"restAuthCredential.enabled_credential": "True",
"restAuthCredential.username": username,
"restAuthCredential.password": password
}
}
),
compute_profile=ComputeProfile(
roles=[
Role(
name="headnode",
target_instance_count=2,
hardware_profile=HardwareProfile(vm_size="Large"),
os_profile=OsProfile(
linux_operating_system_profile=LinuxOperatingSystemProfile(
username=username,
password=password
)
)
),
Role(
name="workernode",
target_instance_count=1,
hardware_profile=HardwareProfile(vm_size="Large"),
os_profile=OsProfile(
linux_operating_system_profile=LinuxOperatingSystemProfile(
username=username,
password=password
)
)
)
]
),
storage_profile=StorageProfile(
storageaccounts=[StorageAccount(
name=storage_account,
key=storage_account_key,
container=container,
is_default=True
)]
)
)
client.clusters.create(
cluster_name=cluster_name,
resource_group_name=resource_group_name,
parameters=ClusterCreateParametersExtended(
location=location,
tags={},
properties=params
))
Ottenere i dettagli del clusterGet Cluster Details
Per ottenere le proprietà di un dato cluster:To get properties for a given cluster:
client.clusters.get("<Resource Group Name>", "<Cluster Name>")
EsempioExample
È possibile usare get
per verificare che il cluster sia stato creato correttamente.You can use get
to confirm that you have successfully created your cluster.
my_cluster = client.clusters.get("<Resource Group Name>", "<Cluster Name>")
print(my_cluster)
L'output sarà simile al seguente:The output should look like:
{'additional_properties': {}, 'id': '/subscriptions/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/resourceGroups/<Resource Group Name>/providers/Microsoft.HDInsight/clusters/<Cluster Name>', 'name': '<Cluster Name>', 'type': 'Microsoft.HDInsight/clusters', 'location': '<Location>', 'tags': {}, 'etag': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', 'properties': <azure.mgmt.hdinsight.models.cluster_get_properties_py3.ClusterGetProperties object at 0x0000013766D68048>}
Elencare clusterList Clusters
Elencare i cluster nella sottoscrizioneList Clusters Under The Subscription
client.clusters.list()
Elencare i cluster per gruppo di risorseList Clusters By Resource Group
client.clusters.list_by_resource_group("<Resource Group Name>")
Nota
Sia list()
che list_by_resource_group()
restituiscono un oggetto ClusterPaged
.Both list()
and list_by_resource_group()
return a ClusterPaged
object. La chiamata di advance_page()
restituisce un elenco di cluster nella pagina e determina l'avanzamento dell'oggetto ClusterPaged
alla pagina successiva.Calling advance_page()
returns a list of clusters on that page and advances the ClusterPaged
object to the next page. Questa operazione può essere ripetuta fino alla generazione di un'eccezione StopIteration
, che indica che non sono presenti altre pagine.This can be repeated until a StopIteration
exception is raised, indicating that there are no more pages.
EsempioExample
L'esempio seguente mostra le proprietà di tutti i cluster per la sottoscrizione corrente:The following example prints the properties of all clusters for the current subscription:
clusters_paged = client.clusters.list()
while True:
try:
for cluster in clusters_paged.advance_page():
print(cluster)
except StopIteration:
break
Eliminare un clusterDelete a Cluster
Per eliminare un cluster:To delete a cluster:
client.clusters.delete("<Resource Group Name>", "<Cluster Name>")
Aggiornare i tag del clusterUpdate Cluster Tags
È possibile aggiornare i tag di un dato cluster nel modo seguente:You can update the tags of a given cluster like so:
client.clusters.update("<Resource Group Name>", "<Cluster Name>", tags={<Dictionary of Tags>})
EsempioExample
client.clusters.update("<Resource Group Name>", "<Cluster Name>", tags={"tag1Name" : "tag1Value", "tag2Name" : "tag2Value"})
Ridimensionare un clusterResize Cluster
È possibile ridimensionare il numero di nodi di ruolo di lavoro di un dato cluster specificando una nuova dimensione nel modo seguente:You can resize a given cluster's number of worker nodes by specifying a new size like so:
client.clusters.resize("<Resource Group Name>", "<Cluster Name>", target_instance_count=<Num of Worker Nodes>)
Monitoraggio del clusterCluster Monitoring
HDInsight Management SDK può essere usato anche per gestire il monitoraggio dei cluster tramite Operations Management Suite (OMS).The HDInsight Management SDK can also be used to manage monitoring on your clusters via the Operations Management Suite (OMS).
Abilitare il monitoraggio di OMSEnable OMS Monitoring
Nota
Per abilitare il monitoraggio di OMS è necessaria un'area di lavoro Log Analytics esistente.To enable OMS Monitoring, you must have an existing Log Analytics workspace. Se non è già stata creata una, è possibile ottenere informazioni su come farlo qui: Creare un'area di lavoro Log Analytics nel portale di Azure.If you have not already created one, you can learn how to do that here: Create a Log Analytics workspace in the Azure portal.
Per abilitare il monitoraggio di OMS nel cluster:To enable OMS Monitoring on your cluster:
client.extension.enable_monitoring("<Resource Group Name>", "<Cluster Name>", workspace_id="<Workspace Id>")
Visualizzare lo stato del monitoraggio di OMSView Status Of OMS Monitoring
Per ottenere lo stato di OMS nel cluster:To get the status of OMS on your cluster:
client.extension.get_monitoring_status("<Resource Group Name", "Cluster Name")
Disabilitare il monitoraggio di OMSDisable OMS Monitoring
Per disabilitare OMS nel cluster:To disable OMS on your cluster:
client.extension.disable_monitoring("<Resource Group Name>", "<Cluster Name>")
Azioni scriptScript Actions
HDInsight offre un metodo di configurazione denominato "azioni script" che richiama script personalizzati per il cluster.HDInsight provides a configuration method called script actions that invokes custom scripts to customize the cluster.
Nota
Altre informazioni su come usare le azioni dello script sono disponibili qui: Personalizzare i cluster HDInsight basati su Linux tramite azioni scriptMore information on how to use script actions can be found here: Customize Linux-based HDInsight clusters using script actions
Eseguire azioni scriptExecute Script Actions
Per eseguire azioni script in un cluster specifico:To execute script actions on a given cluster:
script_action1 = RuntimeScriptAction(name="<Script Name>", uri="<URL To Script>", roles=[<List of Roles>]) #valid roles are "headnode", "workernode", "zookeepernode", and "edgenode"
client.clusters.execute_script_actions("<Resource Group Name>", "<Cluster Name>", <persist_on_success (bool)>, script_actions=[script_action1]) #add more RuntimeScriptActions to the list to execute multiple scripts
Eliminare un'azione scriptDelete Script Action
Per eliminare una determinata azione script persistente in un dato cluster:To delete a specified persisted script action on a given cluster:
client.script_actions.delete("<Resource Group Name>", "<Cluster Name", "<Script Name>")
Elencare le azioni script persistentiList Persisted Script Actions
Nota
list()
e list_persisted_scripts()
restituiscono un oggetto RuntimeScriptActionDetailPaged
.list()
and list_persisted_scripts()
return a RuntimeScriptActionDetailPaged
object. La chiamata di advance_page()
restituisce un elenco di RuntimeScriptActionDetail
nella pagina e determina l'avanzamento dell'oggetto RuntimeScriptActionDetailPaged
alla pagina successiva.Calling advance_page()
returns a list of RuntimeScriptActionDetail
on that page and advances the RuntimeScriptActionDetailPaged
object to the next page. Questa operazione può essere ripetuta fino alla generazione di un'eccezione StopIteration
, che indica che non sono presenti altre pagine.This can be repeated until a StopIteration
exception is raised, indicating that there are no more pages. Vedere l'esempio seguente.See the example below.
Per elencare tutte le azioni script persistenti per il cluster specificato:To list all persisted script actions for the specified cluster:
client.script_actions.list_persisted_scripts("<Resource Group Name>", "<Cluster Name>")
EsempioExample
scripts_paged = client.script_actions.list_persisted_scripts(resource_group_name, cluster_name)
while True:
try:
for script in scripts_paged.advance_page():
print(script)
except StopIteration:
break
Elencare la cronologia di esecuzione di tutti gli scriptList All Scripts' Execution History
Per elencare la cronologia di esecuzione di tutti gli script per il cluster specificato:To list all scripts' execution history for the specified cluster:
client.script_execution_history.list("<Resource Group Name>", "<Cluster Name>")
EsempioExample
Questo esempio visualizza tutti i dettagli di tutte le precedenti esecuzioni di script.This example prints all the details for all past script executions.
script_executions_paged = client.script_execution_history.list("<Resource Group Name>", "<Cluster Name>")
while True:
try:
for script in script_executions_paged.advance_page():
print(script)
except StopIteration:
break