Python(Boto3)SDK용 Amazon EMR 예제 - AWS SDK 코드 예제

AWS 문서 예제 리포지토리에서 더 많은 SDK GitHub AWS SDK 예제를 사용할 수 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Python(Boto3)SDK용 Amazon EMR 예제

다음 코드 예제에서는 Amazon 에서 를 사용하여 작업을 수행하고 일반적인 시나리오 AWS SDK for Python (Boto3) 를 구현하는 방법을 보여줍니다EMR.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.

작업

다음 코드 예시에서는 AddJobFlowSteps을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

Spark 단계를 추가합니다. 이 단계는 추가되는 즉시 클러스터에서 실행됩니다.

def add_step(cluster_id, name, script_uri, script_args, emr_client): """ Adds a job step to the specified cluster. This example adds a Spark step, which is run by the cluster as soon as it is added. :param cluster_id: The ID of the cluster. :param name: The name of the step. :param script_uri: The URI where the Python script is stored. :param script_args: Arguments to pass to the Python script. :param emr_client: The Boto3 EMR client object. :return: The ID of the newly added step. """ try: response = emr_client.add_job_flow_steps( JobFlowId=cluster_id, Steps=[ { "Name": name, "ActionOnFailure": "CONTINUE", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--deploy-mode", "cluster", script_uri, *script_args, ], }, } ], ) step_id = response["StepIds"][0] logger.info("Started step with ID %s", step_id) except ClientError: logger.exception("Couldn't start step %s with URI %s.", name, script_uri) raise else: return step_id

Amazon EMR File System(EMRFS) 명령을 클러스터의 작업 단계로 실행합니다. 연결을 통해 EMRFS 명령을 수동으로 실행하는 대신 클러스터에서 명령을 자동화하는 데 사용할 수 있습니다SSH.

import boto3 from botocore.exceptions import ClientError def add_emrfs_step(command, bucket_url, cluster_id, emr_client): """ Add an EMRFS command as a job flow step to an existing cluster. :param command: The EMRFS command to run. :param bucket_url: The URL of a bucket that contains tracking metadata. :param cluster_id: The ID of the cluster to update. :param emr_client: The Boto3 Amazon EMR client object. :return: The ID of the added job flow step. Status can be tracked by calling the emr_client.describe_step() function. """ job_flow_step = { "Name": "Example EMRFS Command Step", "ActionOnFailure": "CONTINUE", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": ["/usr/bin/emrfs", command, bucket_url], }, } try: response = emr_client.add_job_flow_steps( JobFlowId=cluster_id, Steps=[job_flow_step] ) step_id = response["StepIds"][0] print(f"Added step {step_id} to cluster {cluster_id}.") except ClientError: print(f"Couldn't add a step to cluster {cluster_id}.") raise else: return step_id def usage_demo(): emr_client = boto3.client("emr") # Assumes the first waiting cluster has EMRFS enabled and has created metadata # with the default name of 'EmrFSMetadata'. cluster = emr_client.list_clusters(ClusterStates=["WAITING"])["Clusters"][0] add_emrfs_step( "sync", "s3://elasticmapreduce/samples/cloudfront", cluster["Id"], emr_client ) if __name__ == "__main__": usage_demo()
  • API 자세한 내용은 AddJobFlowStepsAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

다음 코드 예시에서는 DescribeCluster을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

def describe_cluster(cluster_id, emr_client): """ Gets detailed information about a cluster. :param cluster_id: The ID of the cluster to describe. :param emr_client: The Boto3 EMR client object. :return: The retrieved cluster information. """ try: response = emr_client.describe_cluster(ClusterId=cluster_id) cluster = response["Cluster"] logger.info("Got data for cluster %s.", cluster["Name"]) except ClientError: logger.exception("Couldn't get data for cluster %s.", cluster_id) raise else: return cluster
  • API 자세한 내용은 DescribeClusterAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

다음 코드 예시에서는 DescribeStep을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

def describe_step(cluster_id, step_id, emr_client): """ Gets detailed information about the specified step, including the current state of the step. :param cluster_id: The ID of the cluster. :param step_id: The ID of the step. :param emr_client: The Boto3 EMR client object. :return: The retrieved information about the specified step. """ try: response = emr_client.describe_step(ClusterId=cluster_id, StepId=step_id) step = response["Step"] logger.info("Got data for step %s.", step_id) except ClientError: logger.exception("Couldn't get data for step %s.", step_id) raise else: return step
  • API 자세한 내용은 DescribeStepAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

다음 코드 예시에서는 ListSteps을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

def list_steps(cluster_id, emr_client): """ Gets a list of steps for the specified cluster. In this example, all steps are returned, including completed and failed steps. :param cluster_id: The ID of the cluster. :param emr_client: The Boto3 EMR client object. :return: The list of steps for the specified cluster. """ try: response = emr_client.list_steps(ClusterId=cluster_id) steps = response["Steps"] logger.info("Got %s steps for cluster %s.", len(steps), cluster_id) except ClientError: logger.exception("Couldn't get steps for cluster %s.", cluster_id) raise else: return steps
  • API 자세한 내용은 ListStepsAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

다음 코드 예시에서는 RunJobFlow을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

def run_job_flow( name, log_uri, keep_alive, applications, job_flow_role, service_role, security_groups, steps, emr_client, ): """ Runs a job flow with the specified steps. A job flow creates a cluster of instances and adds steps to be run on the cluster. Steps added to the cluster are run as soon as the cluster is ready. This example uses the 'emr-5.30.1' release. A list of recent releases can be found here: https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-release-components.html. :param name: The name of the cluster. :param log_uri: The URI where logs are stored. This can be an Amazon S3 bucket URL, such as 's3://my-log-bucket'. :param keep_alive: When True, the cluster is put into a Waiting state after all steps are run. When False, the cluster terminates itself when the step queue is empty. :param applications: The applications to install on each instance in the cluster, such as Hive or Spark. :param job_flow_role: The IAM role assumed by the cluster. :param service_role: The IAM role assumed by the service. :param security_groups: The security groups to assign to the cluster instances. Amazon EMR adds all needed rules to these groups, so they can be empty if you require only the default rules. :param steps: The job flow steps to add to the cluster. These are run in order when the cluster is ready. :param emr_client: The Boto3 EMR client object. :return: The ID of the newly created cluster. """ try: response = emr_client.run_job_flow( Name=name, LogUri=log_uri, ReleaseLabel="emr-5.30.1", Instances={ "MasterInstanceType": "m5.xlarge", "SlaveInstanceType": "m5.xlarge", "InstanceCount": 3, "KeepJobFlowAliveWhenNoSteps": keep_alive, "EmrManagedMasterSecurityGroup": security_groups["manager"].id, "EmrManagedSlaveSecurityGroup": security_groups["worker"].id, }, Steps=[ { "Name": step["name"], "ActionOnFailure": "CONTINUE", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--deploy-mode", "cluster", step["script_uri"], *step["script_args"], ], }, } for step in steps ], Applications=[{"Name": app} for app in applications], JobFlowRole=job_flow_role.name, ServiceRole=service_role.name, EbsRootVolumeSize=10, VisibleToAllUsers=True, ) cluster_id = response["JobFlowId"] logger.info("Created cluster %s.", cluster_id) except ClientError: logger.exception("Couldn't create cluster.") raise else: return cluster_id
  • API 자세한 내용은 RunJobFlowAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

다음 코드 예시에서는 TerminateJobFlows을 사용하는 방법을 보여 줍니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

def terminate_cluster(cluster_id, emr_client): """ Terminates a cluster. This terminates all instances in the cluster and cannot be undone. Any data not saved elsewhere, such as in an Amazon S3 bucket, is lost. :param cluster_id: The ID of the cluster to terminate. :param emr_client: The Boto3 EMR client object. """ try: emr_client.terminate_job_flows(JobFlowIds=[cluster_id]) logger.info("Terminated cluster %s.", cluster_id) except ClientError: logger.exception("Couldn't terminate cluster %s.", cluster_id) raise
  • API 자세한 내용은 TerminateJobFlowsAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.

시나리오

다음 코드 예제는 단계를 실행하고 단계가 완료된 후 자동으로 종료되는 수명이 짧은 Amazon EMR 클러스터를 생성하는 방법을 보여줍니다.

SDK Python용(Boto3)

Apache Spark를 사용하여 많은 계산을 병렬화하여 pi 값을 추정하는 수명이 짧은 Amazon EMR 클러스터를 생성합니다. 작업은 Amazon EMR 로그와 Amazon Simple Storage Service(Amazon S3) 버킷에 출력을 기록합니다. 클러스터는 작업을 완료한 후 자체적으로 종료됩니다.

  • Amazon S3 버킷을 생성하고 작업 스크립트를 업로드합니다.

  • AWS Identity and Access Management (IAM) 역할을 생성합니다.

  • Amazon Elastic Compute Cloud(AmazonEC2) 보안 그룹을 생성합니다.

  • 수명이 짧은 클러스터를 생성하고 단일 작업 단계를 실행합니다.

이 예제는 에서 가장 잘 볼 수 있습니다 GitHub. 전체 소스 코드와 설정 및 실행 방법에 대한 지침은 의 전체 예제를 참조하세요GitHub.

이 예시에서 사용되는 서비스
  • Amazon EMR

다음 코드 예제는 를 AWS Systems Manager 사용하여 추가 라이브러리를 설치하는 Amazon EMR 인스턴스에서 쉘 스크립트를 실행하는 방법을 보여줍니다. 이렇게 하면 SSH 연결을 통해 명령을 수동으로 실행하는 대신 인스턴스 관리를 자동화할 수 있습니다.

SDK Python용(Boto3)
참고

에 대한 자세한 내용은 를 참조하세요 GitHub. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

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()
  • API 자세한 내용은 ListInstancesAWS SDK Python(Boto3) API 참조 섹션을 참조하세요.