

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

# Amazon S3에서 스트리밍 데이터 로드
<a name="integrations-s3-lambda"></a>

Lambda를 사용하여 Amazon S3에서 OpenSearch Service 도메인으로 데이터를 전송할 수 있습니다. S3 버킷에 도착한 새 데이터는 Lambda로 이벤트 알림을 트리거한 다음 사용자 지정 코드를 실행해 인덱싱합니다.

이러한 방식의 데이터 스트리밍은 대단히 유연합니다. [객체 메타데이터를 인덱싱](https://aws.amazon.com/blogs/database/indexing-metadata-in-amazon-elasticsearch-service-using-aws-lambda-and-python/)할 수도 있고, 객체가 일반 텍스트라면 객체 본문의 일부 요소를 구문 분석하고 인덱싱할 수도 있습니다. 이 단원에는 정규식을 이용해 로그 파일을 구문 분석하고 매치를 인덱싱하는 단순한 Python 샘플 코드가 나와 있습니다.

## 사전 조건
<a name="integrations-s3-lambda-prereq"></a>

계속하려면 먼저 다음 리소스를 확보해야 합니다.


****  

| 사전 조건 | 설명 | 
| --- | --- | 
| Amazon S3 버킷 | 자세한 내용은 Amazon Simple Storage Service 사용 설명서에서 [첫 S3 버킷 생성](https://docs.aws.amazon.com/AmazonS3/latest/userguide/CreatingABucket.html)을 참조하세요. 버킷은 OpenSearch Service 도메인과 같은 리전에 있어야 합니다. | 
| OpenSearch Service 도메인 | Lambda 함수로 처리한 후의 데이터 대상 주소입니다. 자세한 내용은 [OpenSearch Service 도메인 생성](createupdatedomains.md#createdomains) 섹션을 참조하세요. | 

## Lambda 배포 패키지 생성
<a name="integrations-s3-lambda-deployment-package"></a>

배포 패키지는 코드와 종속 프로그램이 포함된 ZIP 또는 JAR 파일로 구성됩니다. 이 단원에는 Python 샘플 코드가 나와 있습니다. 다른 프로그래밍 언어는 *AWS Lambda 개발자 안내서*의 [Lambda 배포 패키지](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html)를 참조하세요.

1. 디렉터리를 생성합니다. 이 샘플에서는 `s3-to-opensearch` 이름을 사용합니다.

1. `sample.py`라는 디렉터리에서 파일을 생성합니다.

   ```
   import boto3
   import re
   import requests
   from requests_aws4auth import AWS4Auth
   
   region = '' # e.g. us-west-1
   service = 'es'
   credentials = boto3.Session().get_credentials()
   awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)
   
   host = '' # the OpenSearch Service domain, e.g. https://search-mydomain.us-west-1.es.amazonaws.com
   index = 'lambda-s3-index'
   datatype = '_doc'
   url = host + '/' + index + '/' + datatype
   
   headers = { "Content-Type": "application/json" }
   
   s3 = boto3.client('s3')
   
   # Regular expressions used to parse some simple log lines
   ip_pattern = re.compile('(\d+\.\d+\.\d+\.\d+)')
   time_pattern = re.compile('\[(\d+\/\w\w\w\/\d\d\d\d:\d\d:\d\d:\d\d\s-\d\d\d\d)\]')
   message_pattern = re.compile('\"(.+)\"')
   
   # Lambda execution starts here
   def handler(event, context):
       for record in event['Records']:
   
           # Get the bucket name and key for the new file
           bucket = record['s3']['bucket']['name']
           key = record['s3']['object']['key']
   
           # Get, read, and split the file into lines
           obj = s3.get_object(Bucket=bucket, Key=key)
           body = obj['Body'].read()
           lines = body.splitlines()
   
           # Match the regular expressions to each line and index the JSON
           for line in lines:
               line = line.decode("utf-8")
               ip = ip_pattern.search(line).group(1)
               timestamp = time_pattern.search(line).group(1)
               message = message_pattern.search(line).group(1)
   
               document = { "ip": ip, "timestamp": timestamp, "message": message }
               r = requests.post(url, auth=awsauth, json=document, headers=headers)
   ```

   `region`과 `host`의 변수를 편집합니다.

1. 아직 설치하지 않았다면 [pip를 설치](https://pip.pypa.io/en/stable/installation/)한 다음, 새 `package` 디렉터리에 종속 항목을 설치합니다.

   ```
   cd s3-to-opensearch
   
   pip install --target ./package requests
   pip install --target ./package requests_aws4auth
   ```

   모든 Lambda 실행 환경에는 [Boto3](https://aws.amazon.com/sdk-for-python/)가 설치되어 있으므로 배포 패키지에 이를 포함할 필요가 없습니다.

1. 애플리케이션 코드와 종속 항목을 패키지화합니다.

   ```
   cd package
   zip -r ../lambda.zip .
   
   cd ..
   zip -g lambda.zip sample.py
   ```

## Lambda 함수 생성
<a name="integrations-s3-lambda-create"></a>

배포 패키지를 만든 뒤에는 Lambda 함수를 생성할 수 있습니다. 함수를 생성할 때는 이름, 런타임(예: Python 3.8)과 IAM 역할을 선택해야 합니다. IAM 역할은 함수에 대한 권한을 정의합니다. 자세한 지침은 *AWS Lambda 개발자 안내서*의 [콘솔로 Lambda 함수 생성](https://docs.aws.amazon.com/lambda/latest/dg/get-started-create-function.html)을 참조하세요.

이 예제에서는 콘솔을 사용하는 것으로 가정합니다. 다음 스크린샷처럼 Python 3.9와 S3 읽기 권한 및 OpenSearch Service 쓰기 권한이 있는 역할을 선택합니다.

![\[Lambda 함수 구성 샘플\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/lambda-function.png)


함수를 생성했으면 이제 트리거를 추가해야 합니다. 이 예제에서는 로그 파일이 S3 버킷에 도착할 때마다 코드를 실행하려 합니다.

1. **트리거 추가(Add trigger)**를 선택하고 **S3**를 선택합니다.

1. 버킷을 선택합니다.

1. **이벤트 유형(Event type)**에서 **PUT**을 선택합니다.

1. **접두사(Prefix)**에는 `logs/`를 입력합니다.

1. **접미사(Suffix)**에는 `.log`를 입력합니다.

1. 재귀 호출 경고를 확인하고 **추가(Add)**를 선택합니다.

마지막으로, 배포 패키지를 업로드할 수 있습니다.

1. **업로드 원본(Upload from)**과 **.zip 파일(.zip file)**을 선택한 다음, 지시에 따라 배포 패키지를 업로드합니다.

1. 업로드가 완료되면 **런타임 설정(Runtime settings)**을 변경하고 **핸들러(Handler)**를 `sample.handler`로 변경합니다. 이 설정은 트리거 후 실행해야 하는 파일(`sample.py`)과 메서드(`handler`)를 Lambda에게 알려 줍니다.

이제 사용자는 완벽한 리소스 모음, 즉 로그 파일용 버킷, 로그 파일이 버킷에 추가될 때마다 실행되는 함수, 구문 분석과 인덱싱을 수행하는 코드, 검색과 시각화를 위한 OpenSearch Service 도메인을 모두 확보하게 됩니다.

## Lambda 함수 테스트
<a name="integrations-s3-lambda-configure"></a>

함수를 만들었으면 이제 Amazon S3 버킷에 파일을 업로드해 함수를 테스트할 수 있습니다. 다음 샘플 로그 행을 이용해 `sample.log`라는 파일을 만듭니다.

```
12.345.678.90 - [10/Oct/2000:13:55:36 -0700] "PUT /some-file.jpg"
12.345.678.91 - [10/Oct/2000:14:56:14 -0700] "GET /some-file.jpg"
```

파일을 S3 버킷의 `logs` 폴더에 업로드합니다. 지침을 보려면 *Amazon Simple Storage Service 사용 설명서*에서 [버킷에 객체 업로드](https://docs.aws.amazon.com/AmazonS3/latest/userguide/PuttingAnObjectInABucket.html)를 참조하세요.

그런 다음 OpenSearch Service 콘솔 또는 OpenSearch Dashboards를 사용하여 `lambda-s3-index` 인덱스에 두 개의 문서가 있음을 확인합니다. 표준 검색 요청을 할 수도 있습니다.

```
GET https://domain-name/lambda-s3-index/_search?pretty
{
  "hits" : {
    "total" : 2,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "lambda-s3-index",
        "_type" : "_doc",
        "_id" : "vTYXaWIBJWV_TTkEuSDg",
        "_score" : 1.0,
        "_source" : {
          "ip" : "12.345.678.91",
          "message" : "GET /some-file.jpg",
          "timestamp" : "10/Oct/2000:14:56:14 -0700"
        }
      },
      {
        "_index" : "lambda-s3-index",
        "_type" : "_doc",
        "_id" : "vjYmaWIBJWV_TTkEuCAB",
        "_score" : 1.0,
        "_source" : {
          "ip" : "12.345.678.90",
          "message" : "PUT /some-file.jpg",
          "timestamp" : "10/Oct/2000:13:55:36 -0700"
        }
      }
    ]
  }
}
```