

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

# EMR Notebooks에 대한 프로그래밍 명령 샘플
<a name="emr-managed-notebooks-headless"></a>

## 개요
<a name="emr-managed-notebooks-headless-overview"></a>

스크립트 또는 명령줄에서 실행 API를 사용하여 EMR Notebooks를 실행할 수 있습니다. AWS 콘솔 외부에서 EMR 노트북 실행을 시작, 중지, 나열 및 설명할 때 EMR 노트북을 프로그래밍 방식으로 제어할 수 있습니다. 파라미터화된 노트북 셀이 있는 노트북에 다양한 파라미터 값을 전달할 수 있습니다. 이렇게 하면 새 파라미터 값 세트마다 노트북 사본을 만들 필요가 없습니다. 자세한 내용은 [Amazon EMR API 작업](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)을 참조하세요.

Amazon CloudWatch 이벤트 및 AWS Lambda를 사용하여 EMR 노트북 실행을 예약하거나 배치 처리할 수 있습니다. 자세한 내용은 [ Amazon CloudWatch Events AWS Lambda 에서 사용을](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents.html) 참조하세요.

**참고**  
EMR Notebooks는 콘솔에서 EMR Studio Workspace로 사용 가능합니다. 콘솔의 **워크스페이스 생성** 버튼을 사용하면 새 노트북을 생성할 수 있습니다. EMR Notebooks 사용자는 Workspace에 액세스하거나 Workspace를 생성하려면 추가 IAM 역할 권한이 필요합니다. 자세한 내용은 [Amazon EMR Notebooks가 콘솔에서 Amazon EMR Studio 워크스페이스 역할](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 및 [Amazon EMR 콘솔](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)을 참조하세요.

## 프로그래밍 실행을 위한 역할 권한
<a name="emr-managed-notebooks-headless-permissions"></a>

EMR Notebooks에서 프로그래밍 방식 실행을 사용하려면 다음 정책으로 사용자 권한을 구성해야 합니다.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowExecutionActions",
      "Effect": "Allow",
      "Action": [
        "elasticmapreduce:StartNotebookExecution",
        "elasticmapreduce:DescribeNotebookExecution",
        "elasticmapreduce:ListNotebookExecutions"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Sid": "AllowPassingServiceRole",
      "Effect": "Allow",
      "Action": [
        "iam:PassRole"
      ],
      "Resource": [
        "arn:aws:iam::123456789012:role/EMR_Notebooks_DefaultRole"
      ]
    }
  ]
}
```

------

EMR Notebooks 클러스터에서 프로그래밍 방식으로 EMR Notebooks를 실행할 때는 다음과 같은 추가 권한을 추가해야 합니다.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowRetrievingManagedEndpointCredentials",
      "Effect": "Allow",
      "Action": [
        "emr-containers:GetManagedEndpointSessionCredentials"
      ],
      "Resource": [
        "arn:aws:emr-containers:*:123456789012:/virtualclusters/virtual-cluster-id/endpoints/managed-endpoint-id"
      ],
      "Condition": {
        "StringEquals": {
          "emr-containers:ExecutionRoleArn": [
            "arn:aws:iam::123456789012:role/emr-on-eks-execution-role"
          ]
        }
      }
    },
    {
      "Sid": "AllowDescribingManagedEndpoint",
      "Effect": "Allow",
      "Action": [
        "emr-containers:DescribeManagedEndpoint"
      ],
      "Resource": [
        "arn:aws:emr-containers:*:123456789012:/virtualclusters/virtual-cluster-id/endpoints/managed-endpoint-id"
      ]
    }
  ]
}
```

------

## 프로그래밍 방식 실행의 제한 사항
<a name="emr-managed-notebooks-headless-limit"></a>
+ 계정 AWS 리전 당 최대 100개의 동시 실행이 지원됩니다.
+ 30일 넘게 실행되면 실행이 종료됩니다.
+ Amazon EMR Serverless 대화형 애플리케이션에서는 노트북의 프로그래밍 방식 실행을 지원하지 않습니다.

## 프로그래밍 방식의 EMR 노트북 실행 예제
<a name="emr-managed-notebooks-headless-examples"></a>

다음 섹션에서는 AWS CLI Boto3 SDK(Python) 및 Ruby를 사용한 프로그래밍 방식의 EMR 노트북 실행의 몇 가지 예를 제공합니다.
+ [EMR Studio의 노트북 CLI 명령 샘플](emr-managed-notebooks-headless-cli.md)
+ [EMR Notebook에 대한 Python 샘플](emr-managed-notebooks-headless-python.md)
+ [EMR Notebook에 대한 Ruby 샘플](emr-managed-notebooks-headless-ruby.md)

Apache Airflow 또는 Apache Airflow용 Amazon 관리형 워크플로(MWAA)와 같은 오케스트레이션 도구를 사용하여 예약된 워크플로의 일부로 파라미터화된 노트북을 실행할 수 있습니다. 자세한 내용은 *AWS 빅 데이터 블로그*에서 [Orchestrating analytics jobs on EMR Notebooks using MWAA](https://aws.amazon.com/blogs/big-data/orchestrating-analytics-jobs-on-amazon-emr-notebooks-using-amazon-mwaa/)를 참조하세요.

# EMR Studio의 노트북 CLI 명령 샘플
<a name="emr-managed-notebooks-headless-cli"></a>

이 주제에서는 EMR Notebook에 대한 CLI 명령 샘플을 보여줍니다. 이 예제에서는 EMR Notebooks 콘솔의 데모 노트북을 사용합니다. 노트북을 찾으려면 홈 디렉터리에 상대적인 파일 경로를 사용합니다. 이 예제에서는 두 개의 노트북 파일(`demo_pyspark.ipynb` 및 `my_folder/python3.ipynb`)을 실행할 수 있습니다.

**참고**  
EMR Notebooks는 콘솔에서 EMR Studio Workspace로 사용 가능합니다. 콘솔의 **워크스페이스 생성** 버튼을 사용하면 새 노트북을 생성할 수 있습니다. EMR Notebooks 사용자는 Workspace에 액세스하거나 Workspace를 생성하려면 추가 IAM 역할 권한이 필요합니다. 자세한 내용은 [Amazon EMR Notebooks가 콘솔에서 Amazon EMR Studio 워크스페이스 역할](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 및 [Amazon EMR 콘솔](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)을 참조하세요.

`demo_pyspark.ipynb` 파일의 상대 경로는 아래와 같이 `demo_pyspark.ipynb`입니다.

![\[Jupyter notebook interface showing a file explorer and code editor with PySpark content.\]](http://docs.aws.amazon.com/ko_kr/emr/latest/ManagementGuide/images/notebook_exe_folder_structure_1.png)


`python3.ipynb`의 상대 경로는 아래와 같이 `my_folder/python3.ipynb`입니다.

![\[File explorer showing python3.ipynb in my_folder, and Jupyter notebook interface with code.\]](http://docs.aws.amazon.com/ko_kr/emr/latest/ManagementGuide/images/notebook_exe_folder_structure_2.png)


Amazon EMR API `NotebookExecution` 작업에 대한 자세한 내용은 [Amazon EMR API 작업](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)을 참조하세요.

## 노트북 실행
<a name="emr-managed-notebooks-api-actions"></a>

다음 예제에서 볼 수 있듯이 AWS CLI 를 사용하여 `start-notebook-execution` 작업과 함께 노트북을 실행할 수 있습니다.

**Example - Amazon EMR(Amazon EC2에서 실행) 클러스터를 사용하는 EMR Studio Workspace에서 EMR 노트북 실행**  

```
aws emr --region us-east-1 \
start-notebook-execution \
--editor-id e-ABCDEFG123456 \
--notebook-params '{"input_param":"my-value", "good_superhero":["superman", "batman"]}' \
--relative-path test.ipynb \
--notebook-execution-name my-execution \
--execution-engine '{"Id" : "j-1234ABCD123"}' \
--service-role EMR_Notebooks_DefaultRole 
 
{
    "NotebookExecutionId": "ex-ABCDEFGHIJ1234ABCD"
}
```

**Example - EMR Notebooks 클러스터를 사용하여 EMR Studio Workspace에서 EMR 노트북 실행**  

```
aws emr start-notebook-execution \
    --region us-east-1 \
    --service-role EMR_Notebooks_DefaultRole \
    --environment-variables '{"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.executor.instances=1", "KERNEL_LAUNCH_TIMEOUT": "350"}' \
    --output-notebook-format HTML \
    --execution-engine Id=arn:aws:emr-containers:us-west-2:account-id:/virtualclusters/ABCDEFG/endpoints/ABCDEF,Type=EMR_ON_EKS,ExecutionRoleArn=arn:aws:iam::account-id:role/execution-role \
    --editor-id e-ABCDEFG \
    --relative-path EMRonEKS-spark_python.ipynb
```

**Example - Amazon S3 위치를 지정하는 EMR 노트북 실행**  

```
aws emr start-notebook-execution \
    --region us-east-1 \
    --notebook-execution-name my-execution-on-emr-on-eks-cluster \
    --service-role EMR_Notebooks_DefaultRole \
    --environment-variables '{"KERNEL_EXTRA_SPARK_OPTS": "--conf spark.executor.instances=1", "KERNEL_LAUNCH_TIMEOUT": "350"}' \
    --output-notebook-format HTML \
    --execution-engine Id=arn:aws:emr-containers:us-west-2:account-id:/virtualclusters/ABCDEF/endpoints/ABCDEF,Type=EMR_ON_EKS,ExecutionRoleArn=arn:aws:iam::account-id:role/execution-role \
    --notebook-s3-location '{"Bucket": "amzn-s3-demo-bucket","Key": "s3-prefix-to-notebook-location/EMRonEKS-spark_python.ipynb"}' \
    --output-notebook-s3-location '{"Bucket": "amzn-s3-demo-bucket","Key": "s3-prefix-for-storing-output-notebook"}'
```

## 노트북 출력
<a name="emr-managed-notebooks-headless-cli-output"></a>

 다음은 샘플 노트북의 출력입니다. 셀 3에는 새로 삽입된 파라미터 값이 표시됩니다.

![\[Jupyter notebook cells showing Python code and output for parameter injection and manipulation.\]](http://docs.aws.amazon.com/ko_kr/emr/latest/ManagementGuide/images/HelloWorld_notebook.png)


## 노트북 설명
<a name="emr-managed-notebooks-headless-cli-describe"></a>

`describe-notebook-execution` 작업을 사용하여 특정 노트북 실행에 대한 정보에 액세스할 수 있습니다.

```
aws emr --region us-east-1 \
describe-notebook-execution --notebook-execution-id ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE
 
{
    "NotebookExecution": {
        "NotebookExecutionId": "ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
        "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
        "ExecutionEngine": {
            "Id": "j-2QMOV6JAX1TS2",
            "Type": "EMR",
            "MasterInstanceSecurityGroupId": "sg-05ce12e58cd4f715e"
        },
        "NotebookExecutionName": "my-execution",
        "NotebookParams": "{\"input_param\":\"my-value\", \"good_superhero\":[\"superman\", \"batman\"]}",
        "Status": "FINISHED",
        "StartTime": 1593490857.009,
        "Arn": "arn:aws:elasticmapreduce:us-east-1:123456789012:notebook-execution/ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
        "LastStateChangeReason": "Execution is finished for cluster j-2QMOV6JAX1TS2.",
        "NotebookInstanceSecurityGroupId": "sg-0683b0a39966d4a6a",
        "Tags": []
    }
}
```

## 노트북 중지
<a name="emr-managed-notebooks-headless-cli-stop"></a>

노트북에서 중지하려는 실행이 실행 중인 경우 `stop-notebook-execution` 명령을 사용하여 중지할 수 있습니다.

```
# stop a running execution
aws emr --region us-east-1 \
stop-notebook-execution --notebook-execution-id ex-IZWZX78UVPAATC8LHJR129B1RBN4T
 
 
# describe it
aws emr --region us-east-1 \
describe-notebook-execution --notebook-execution-id ex-IZWZX78UVPAATC8LHJR129B1RBN4T
 
{
    "NotebookExecution": {
        "NotebookExecutionId": "ex-IZWZX78UVPAATC8LHJR129B1RBN4T",
        "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
        "ExecutionEngine": {
            "Id": "j-2QMOV6JAX1TS2",
            "Type": "EMR"
        },
        "NotebookExecutionName": "my-execution",
        "NotebookParams": "{\"input_param\":\"my-value\", \"good_superhero\":[\"superman\", \"batman\"]}",
        "Status": "STOPPED",
        "StartTime": 1593490876.241,
        "Arn": "arn:aws:elasticmapreduce:us-east-1:123456789012:editor-execution/ex-IZWZX78UVPAATC8LHJR129B1RBN4T",
        "LastStateChangeReason": "Execution is stopped for cluster j-2QMOV6JAX1TS2. Internal error",
        "Tags": []
    }
}
```

## 시작 시간을 기준으로 노트북의 실행 나열
<a name="emr-managed-notebooks-headless-cli-list"></a>

`--from` 파라미터를 `list-notebook-executions`로 전달하여 시작 시간별로 노트북의 실행을 나열할 수 있습니다.

```
# filter by start time 
aws emr --region us-east-1 \ 
list-notebook-executions --from 1593400000.000
 
{
    "NotebookExecutions": [
        {
            "NotebookExecutionId": "ex-IZWZX78UVPAATC8LHJR129B1RBN4T",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "STOPPED",
            "StartTime": 1593490876.241
        },
        {
            "NotebookExecutionId": "ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "RUNNING",
            "StartTime": 1593490857.009
        },
        {
            "NotebookExecutionId": "ex-IZWZYRS0M14L5V95WZ9OQ399SKMNW",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "STOPPED",
            "StartTime": 1593490292.995
        },
        {
            "NotebookExecutionId": "ex-IZX009ZK83IVY5E33VH8MDMELVK8K",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FINISHED",
            "StartTime": 1593489834.765
        },
        {
            "NotebookExecutionId": "ex-IZWZXOZF88JWDF9J09GJ91R57VI0N",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FAILED",
            "StartTime": 1593488934.688
        }
    ]
}
```

## 시작 시간 및 상태를 기준으로 노트북의 실행 나열
<a name="emr-managed-notebooks-headless-cli-list"></a>

`list-notebook-executions` 명령은 `--status` 파라미터를 사용하여 결과를 필터링할 수도 있습니다.

```
# filter by start time and status 
aws emr --region us-east-1 \                 
list-notebook-executions --from 1593400000.000 --status FINISHED
{
    "NotebookExecutions": [
        {
            "NotebookExecutionId": "ex-IZWZZVR9DKQ9WQ7VZWXJZR29UGHTE",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FINISHED",
            "StartTime": 1593490857.009
        },
        {
            "NotebookExecutionId": "ex-IZX009ZK83IVY5E33VH8MDMELVK8K",
            "EditorId": "e-BKTM2DIHXBEDRU44ANWRKIU8N",
            "NotebookExecutionName": "my-execution",
            "Status": "FINISHED",
            "StartTime": 1593489834.765
        }
    ]
}
```

# EMR Notebook에 대한 Python 샘플
<a name="emr-managed-notebooks-headless-python"></a>

이 주제에는 샘플 명령 파일이 포함되어 있습니다. 코드 예제는 `demo.py`라고 하는 SDK for Python(Boto3) 파일입니다. 노트북 실행 API를 보여줍니다.

**참고**  
EMR Notebooks는 콘솔에서 EMR Studio Workspace로 사용 가능합니다. 콘솔의 **워크스페이스 생성** 버튼을 사용하면 새 노트북을 생성할 수 있습니다. EMR Notebooks 사용자는 Workspace에 액세스하거나 Workspace를 생성하려면 추가 IAM 역할 권한이 필요합니다. 자세한 내용은 [Amazon EMR Notebooks가 콘솔에서 Amazon EMR Studio 워크스페이스 역할](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 및 [Amazon EMR 콘솔](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)을 참조하세요.

Amazon EMR API `NotebookExecution` 작업에 대한 자세한 내용은 [Amazon EMR API 작업](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)을 참조하세요.

```
import boto3,time

emr = boto3.client(
    'emr',
    region_name='us-west-1'
)     
     
start_resp = emr.start_notebook_execution(
    EditorId='e-40AC8ZO6EGGCPJ4DLO48KGGGI',
    RelativePath='boto3_demo.ipynb',
    ExecutionEngine={'Id':'j-1HYZS6JQKV11Q'},
    ServiceRole='EMR_Notebooks_DefaultRole'
)

execution_id = start_resp["NotebookExecutionId"]
print(execution_id)
print("\n")
     
describe_response = emr.describe_notebook_execution(NotebookExecutionId=execution_id)
     
print(describe_response)
print("\n")
     
list_response = emr.list_notebook_executions()
print("Existing notebook executions:\n")
for execution in list_response['NotebookExecutions']:
    print(execution)
    print("\n")  
     
print("Sleeping for 5 sec...")
time.sleep(5)
     
print("Stop execution " + execution_id)
emr.stop_notebook_execution(NotebookExecutionId=execution_id)
describe_response = emr.describe_notebook_execution(NotebookExecutionId=execution_id)
print(describe_response)
print("\n")
```

다음은 `demo.py` 실행의 출력입니다.

```
ex-IZX56YJDW1D29Q1PHR32WABU2SAPK
     
{'NotebookExecution': {'NotebookExecutionId': 'ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'ExecutionEngine': {'Id': 'j-1HYZS6JQKV11Q', 'Type': 'EMR'}, 'NotebookExecutionName': '', 'Status': 'STARTING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 49, 19, 418000, tzinfo=tzlocal()), 'Arn': 'arn:aws:elasticmapreduce:us-west-1:123456789012:notebook-execution/ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'LastStateChangeReason': 'Execution is starting for cluster j-1HYZS6JQKV11Q.', 'Tags': []}, 'ResponseMetadata': {'RequestId': '70f12c5f-1dda-45b7-adf6-964987d373b7', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '70f12c5f-1dda-45b7-adf6-964987d373b7', 'content-type': 'application/x-amz-json-1.1', 'content-length': '448', 'date': 'Wed, 19 Aug 2020 00:49:22 GMT'}, 'RetryAttempts': 0}}
     
Existing notebook executions:
     
{'NotebookExecutionId': 'ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'STARTING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 49, 19, 418000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5ABS5PR1E5AHMFYEMX3JJIORRB', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'RUNNING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 48, 36, 373000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5GLVXIU1HNI8BWVW057F6MF4VE', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 45, 14, 646000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 46, 26, 543000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5CV8YDUO8JAIWMXN2VH32RUIT1', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 43, 5, 807000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 44, 31, 632000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX5AS0PPW55CEDEURZ9NSOWSUJZ6', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 42, 29, 265000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 43, 48, 320000, tzinfo=tzlocal())}
     
     
{'NotebookExecutionId': 'ex-IZX57YF5Q53BKWLR4I5QZ14HJ7DRS', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'NotebookExecutionName': '', 'Status': 'FINISHED', 'StartTime': datetime.datetime(2020, 8, 19, 0, 38, 37, 81000, tzinfo=tzlocal()), 'EndTime': datetime.datetime(2020, 8, 19, 0, 40, 39, 646000, tzinfo=tzlocal())}
     
Sleeping for 5 sec...
Stop execution ex-IZX56YJDW1D29Q1PHR32WABU2SAPK
{'NotebookExecution': {'NotebookExecutionId': 'ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'EditorId': 'e-40AC8ZO6EGGCPJ4DLO48KGGGI', 'ExecutionEngine': {'Id': 'j-1HYZS6JQKV11Q', 'Type': 'EMR'}, 'NotebookExecutionName': '', 'Status': 'STOPPING', 'StartTime': datetime.datetime(2020, 8, 19, 0, 49, 19, 418000, tzinfo=tzlocal()), 'Arn': 'arn:aws:elasticmapreduce:us-west-1:123456789012:notebook-execution/ex-IZX56YJDW1D29Q1PHR32WABU2SAPK', 'LastStateChangeReason': 'Execution is being stopped for cluster j-1HYZS6JQKV11Q.', 'Tags': []}, 'ResponseMetadata': {'RequestId': '2a77ef73-c1c6-467c-a1d1-7204ab2f6a53', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '2a77ef73-c1c6-467c-a1d1-7204ab2f6a53', 'content-type': 'application/x-amz-json-1.1', 'content-length': '453', 'date': 'Wed, 19 Aug 2020 00:49:30 GMT'}, 'RetryAttempts': 0}}
```

# EMR Notebook에 대한 Ruby 샘플
<a name="emr-managed-notebooks-headless-ruby"></a>

이 주제에는 노트북 기능을 보여주는 Ruby 샘플이 포함되어 있습니다.

**참고**  
EMR Notebooks는 콘솔에서 EMR Studio Workspace로 사용 가능합니다. 콘솔의 **워크스페이스 생성** 버튼을 사용하면 새 노트북을 생성할 수 있습니다. EMR Notebooks 사용자는 Workspace에 액세스하거나 Workspace를 생성하려면 추가 IAM 역할 권한이 필요합니다. 자세한 내용은 [Amazon EMR Notebooks가 콘솔에서 Amazon EMR Studio 워크스페이스 역할](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-notebooks-migration.html) 및 [Amazon EMR 콘솔](https://docs.aws.amazon.com/emr/latest/ManagementGuide/whats-new-in-console.html)을 참조하세요.

다음 Ruby 코드 샘플에서는 노트북 실행 API 사용을 보여줍니다.

```
# prepare an Amazon EMR client

emr = Aws::EMR::Client.new(
  region: 'us-east-1',
  access_key_id: 'AKIA...JKPKA',
  secret_access_key: 'rLMeu...vU0OLrAC1',
)
```

## 노트북 실행 시작 및 실행 ID 가져오기
<a name="emr-managed-notebooks-headless-ruby-startretrieve"></a>

이 예제에서 Amazon S3 편집기 및 EMR 노트북은 `s3://amzn-s3-demo-bucket/notebooks/e-EA8VGAA429FEQTC8HC9ZHWISK/test.ipynb`입니다.

Amazon EMR API `NotebookExecution` 작업에 대한 자세한 내용은 [Amazon EMR API 작업](https://docs.aws.amazon.com/emr/latest/APIReference/API_Operations.html)을 참조하세요.

```
start_response = emr.start_notebook_execution({
    editor_id: "e-EA8VGAA429FEQTC8HC9ZHWISK",
    relative_path: "test.ipynb",
    
    execution_engine: {id: "j-3U82I95AMALGE"},
    
    service_role: "EMR_Notebooks_DefaultRole",
})


notebook_execution_id = start_resp.notebook_execution_id
```

## 노트북 실행 설명 및 세부 정보 인쇄
<a name="emr-managed-notebooks-headless-ruby-describeprint"></a>

```
describe_resp = emr.describe_notebook_execution({
    notebook_execution_id: notebook_execution_id
})
puts describe_resp.notebook_execution
```

위 명령의 출력은 다음과 같습니다.

```
{
:notebook_execution_id=>"ex-IZX3VTVZWVWPP27KUB90BZ7V9IEDG", 
:editor_id=>"e-EA8VGAA429FEQTC8HC9ZHWISK",
:execution_engine=>{:id=>"j-3U82I95AMALGE", :type=>"EMR", :master_instance_security_group_id=>nil}, 
:notebook_execution_name=>"", 
:notebook_params=>nil, 
:status=>"STARTING", 
:start_time=>2020-07-23 15:07:07 -0700, 
:end_time=>nil, 
:arn=>"arn:aws:elasticmapreduce:us-east-1:123456789012:notebook-execution/ex-IZX3VTVZWVWPP27KUB90BZ7V9IEDG", 
:output_notebook_uri=>nil, 
:last_state_change_reason=>"Execution is starting for cluster j-3U82I95AMALGE.", :notebook_instance_security_group_id=>nil, 
:tags=>[]
}
```

## 노트북 필터
<a name="emr-managed-notebooks-headless-ruby-filters"></a>

```
"EditorId": "e-XXXX",           [Optional]
"From" : "1593400000.000",    [Optional]
"To" :
```

### 노트북 실행 중지
<a name="emr-managed-notebooks-headless-ruby-stop"></a>

```
stop_resp = emr.stop_notebook_execution({
    notebook_execution_id: notebook_execution_id
})
```