

Sono disponibili altri esempi AWS SDK nel repository [AWS Doc SDK](https://github.com/awsdocs/aws-doc-sdk-examples) Examples. GitHub 

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Scenari per l'utilizzo di Amazon EMR AWS SDKs
<a name="emr_code_examples_scenarios"></a>

I seguenti esempi di codice mostrano come implementare scenari comuni in Amazon EMR con. AWS SDKs Questi scenari illustrano come eseguire attività specifiche chiamando più funzioni all’interno di Amazon EMR o in combinazione con altri Servizi AWS. Ogni scenario include un collegamento al codice sorgente completo, dove è possibile trovare le istruzioni su come configurare ed eseguire il codice. 

Gli scenari sono relativi a un livello intermedio di esperienza per aiutarti a comprendere le azioni di servizio nel contesto.

**Topics**
+ [Creazione di un cluster Amazon EMR di breve durata ed esecuzione di un passaggio](emr_example_emr_Scenario_ShortLivedEmrCluster_section.md)
+ [Eseguire uno script di shell per installare librerie](emr_example_emr_Usage_InstallLibrariesWithSsm_section.md)

# Crea un cluster Amazon EMR di breve durata ed esegui una fase utilizzando un SDK AWS
<a name="emr_example_emr_Scenario_ShortLivedEmrCluster_section"></a>

Il seguente esempio di codice mostra come creare un cluster Amazon EMR di breve durata che esegue un passaggio e termina automaticamente dopo il suo completamento.

------
#### [ Python ]

**SDK per Python (Boto3)**  
 Crea un cluster Amazon EMR di breve durata che stimi il valore di pi greco utilizzando Apache Spark per eseguire in parallelo un numero elevato di calcoli. Il processo scrive l’output in log Amazon EMR e in un bucket Amazon Simple Storage Service (Amazon S3). Il cluster termina automaticamente dopo aver completato il processo.   
+ Crea un bucket Amazon S3 e carica uno script di processo.
+ Crea ruoli AWS Identity and Access Management (IAM).
+ Crea i gruppi di sicurezza di Amazon Elastic Compute Cloud (Amazon EC2).
+ Crea un cluster Amazon EMR di breve durata ed esegui un passaggio del processo.
 Questo esempio è visualizzato al meglio su GitHub. Per il codice sorgente completo e le istruzioni su come configurarlo ed eseguirlo, vedi l'esempio completo su [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr).   

**Servizi utilizzati in questo esempio**
+ Amazon EMR

------

# Esegui uno script di shell per installare librerie su istanze Amazon EMR utilizzando un SDK AWS
<a name="emr_example_emr_Usage_InstallLibrariesWithSsm_section"></a>

Il seguente esempio di codice mostra come AWS Systems Manager eseguire uno script di shell su istanze Amazon EMR che installa librerie aggiuntive. In questo modo, puoi automatizzare la gestione delle istanze anziché eseguire comandi manualmente tramite una connessione SSH.

------
#### [ Python ]

**SDK per Python (Boto3)**  
 C'è di più su. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel [Repository di esempi di codice AWS](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples). 

```
import argparse
import time
import boto3


def install_libraries_on_core_nodes(cluster_id, script_path, emr_client, ssm_client):
    """
    Copies and runs a shell script on the core nodes in the cluster.

    :param cluster_id: The ID of the cluster.
    :param script_path: The path to the script, typically an Amazon S3 object URL.
    :param emr_client: The Boto3 Amazon EMR client.
    :param ssm_client: The Boto3 AWS Systems Manager client.
    """
    core_nodes = emr_client.list_instances(
        ClusterId=cluster_id, InstanceGroupTypes=["CORE"]
    )["Instances"]
    core_instance_ids = [node["Ec2InstanceId"] for node in core_nodes]
    print(f"Found core instances: {core_instance_ids}.")

    commands = [
        # Copy the shell script from Amazon S3 to each node instance.
        f"aws s3 cp {script_path} /home/hadoop",
        # Run the shell script to install libraries on each node instance.
        "bash /home/hadoop/install_libraries.sh",
    ]
    for command in commands:
        print(f"Sending '{command}' to core instances...")
        command_id = ssm_client.send_command(
            InstanceIds=core_instance_ids,
            DocumentName="AWS-RunShellScript",
            Parameters={"commands": [command]},
            TimeoutSeconds=3600,
        )["Command"]["CommandId"]
        while True:
            # Verify the previous step succeeded before running the next step.
            cmd_result = ssm_client.list_commands(CommandId=command_id)["Commands"][0]
            if cmd_result["StatusDetails"] == "Success":
                print(f"Command succeeded.")
                break
            elif cmd_result["StatusDetails"] in ["Pending", "InProgress"]:
                print(f"Command status is {cmd_result['StatusDetails']}, waiting...")
                time.sleep(10)
            else:
                print(f"Command status is {cmd_result['StatusDetails']}, quitting.")
                raise RuntimeError(
                    f"Command {command} failed to run. "
                    f"Details: {cmd_result['StatusDetails']}"
                )


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("cluster_id", help="The ID of the cluster.")
    parser.add_argument("script_path", help="The path to the script in Amazon S3.")
    args = parser.parse_args()

    emr_client = boto3.client("emr")
    ssm_client = boto3.client("ssm")

    install_libraries_on_core_nodes(
        args.cluster_id, args.script_path, emr_client, ssm_client
    )


if __name__ == "__main__":
    main()
```
+  Per i dettagli sull'API, consulta [ListInstances AWS](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/ListInstances)*SDK for Python (Boto3) API Reference*. 

------