본문 바로가기
개발일기/DB-MySql

AWS Elasticsearch Service S3만들어서 수동 스냅샷(snapshot) 저장소(repository) 설정 하는 방법

by 프로그래머콩 2019. 7. 6.

 

 


* 준비물 : 

Elasticsearch service, 
S3,
python,
Elasticsearch Service 라우터군에 연결된 ec2( 같은 리전, 같은 보안체계, 서브넷 일치하는 ec2)




1. elasticsearch 스냅샷(백업 데이터)이 저장될 S3 열기.
(S3 버킷의 이름은 testbucket 으로 )

 

2. IAM에 가서 역할 만들기

역할 만들기 클릭



EC2클릭

 

그다음 스텝 그냥 next누르고

역할 이름 적당히 지어서 create



3. IAM 정책 만들기


정책 만들기 클릭 후 JSON 탭 누른 뒤

아래 내용 입력, Create

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:ListBucket"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::testbucket"
            ]
        },
        {
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:DeleteObject",
                "iam:PassRole"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::testbucket/*"
            ]
        }
    ]
}




4. IAM 정책과 역할 연결

아까만든 역할 클릭



정책 연결 클릭

만든 정책 이름 검색해서 연결하기.

 



 

 

5. 스냅샷 저장소 생성 준비

AWS Elasticsearch Service의 스냅샷 저장소 생성은 curl명령어로 할 수 없음.

그래서 AWS에서는 python을 이용하는 방법을 알려준다.


같은 리전, 같은 보안체계, 같은 망에 존재하는 ec2에 python을 설치하고 
거기에 python파일을 하나 만들것임

(python  설치되어 있다 가정하고 진행)

S3연결할 때 사용되는 python라이브러리'boto3' 와  'requests-aws4auth'설치 

$ pip3 install boto3
$ pip3 install requests-aws4auth # ubuntu는 
$ sudo apt install python3-boto3 
$ sudo apt install python3-requests-aws4auth

 

6. register-repo.py  파이썬 파일 만들고 아래 내용 작성 및 실행

import boto3
import requests
from requests_aws4auth import AWS4Auth

host = '' # include https:// and trailing /
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)

# REGISTER REPOSITORY

path = '_snapshot/my-snapshot-repo' # the Elasticsearch API endpoint
url = host + path

payload = {
  "type": "s3",
  "settings": {
    "bucket": "s3-bucket-name",
    "region": "",
    "role_arn": "arn:aws:iam::123456789012:role/TheServiceRole"
  }
}

headers = {"Content-Type": "application/json"}

r = requests.put(url, auth=awsauth, json=payload, headers=headers)

print(r.status_code)
print(r.text)

# # TAKE SNAPSHOT
# 
# path = '_snapshot/my-snapshot-repo/my-snapshot'
# url = host + path
# 
# r = requests.put(url, auth=awsauth)
# 
# print(r.text)
# 
# # DELETE INDEX
# 
# path = 'my-index'
# url = host + path
# 
# r = requests.delete(url, auth=awsauth)
# 
# print(r.text)
# 
# # RESTORE SNAPSHOT (ALL INDICES)
# 
# path = '_snapshot/my-snapshot-repo/my-snapshot/_restore'
# url = host + path
# 
# r = requests.post(url, auth=awsauth)
# 
# print(r.text)
# 
# # RESTORE SNAPSHOT (ONE INDEX)
# 
# path = '_snapshot/my-snapshot-repo/my-snapshot/_restore'
# url = host + path
# 
# payload = {"indices": "my-index"}
# 
# headers = {"Content-Type": "application/json"}
# 
# r = requests.post(url, auth=awsauth, json=payload, headers=headers)
# 
# print(r.text)

5-(2). 만약 requests-aws4auth가 패키지 설치가 안되는 경우

boto 설치

$ pip3 install boto

 


$ vi register-repo.py

아래 내용 입력 후 저장, 실행

from boto.connection import AWSAuthConnection
 
class ESConnection(AWSAuthConnection):
 
    def __init__(self, region, **kwargs):
        super(ESConnection, self).__init__(**kwargs)
        self._set_auth_region_name(region)
        self._set_auth_service_name("es")
 
    def _required_auth_capability(self):
        return ['hmac-v4']
 
if __name__ == "__main__":
 
    client = ESConnection(
            region='(aws에서 구분하는 region 작성, 서울은 ap-northeast-2)',
            host='(elasticsearch-domain-endpoint 작성)',
            aws_access_key_id='(aws access key 작성)',
            aws_secret_access_key='(aws access key에 따른 secret key 작성)', is_secure=False)
 
    print ('Registering Snapshot Repository')
    resp = client.make_request(method='PUT',
            path='/_snapshot/index-backups',
            data='{"type": "s3","settings": { "bucket": "(버킷이름)","region": "ap-northeast-2","role_arn": "(IAM 'testbucketRole에서 ARN 복붙)"}}')
    body = resp.read()
    print (body)

 



$ python3 register-repo.py



실행했을 때 아래와 같은 오류메세지가 나타나면, 권한이 없다는 말이므로 권한생성부분 다시 살펴봐야 함.
{"Message":"User: arn:aws:iam::123456789012:user/MyUserAccount is not authorized to perform: iam:PassRole on resource: arn:aws:iam::123456789012:role/TheServiceRole"}

 

 

 

6. 스냅샷 생성, 복원, 삭제 그리고 외부 스냅샷 추가

elasticsearch 스냅샷 관련 명령어정리

 

수동으로 스냅샷을 생성
$ curl -XPUT 'elasticsearch-domain-endpoint/_snapshot/repository/snapshot-name'

참고 )
스냅샷 생성에 필요한 시간은 Amazon ES 도메인의 크기에 따라 다르다.
스냅샷 작업이 길게 실행되면 일반적으로 다음과 같은 오류가 발생한다.
"504 GATEWAY_TIMEOUT. " 
elasticsearch에 저장하는 데이터가 보통 대용량이기 때문에 자주나타나는 에러다
무시하고 작업이 성공적으로 완료될 때까지 기다리면 된다.

불안하다면  다음 명령을 사용하여 도메인의 모든 스냅샷 상태를 확인할 수 있다
$ curl -XGET 'elasticsearch-domain-endpoint/_snapshot/repository/_all?pretty'

스냅샷을 생성할 때 사용 가능한 옵션에 대한 더 자세한 내용은 Elasticsearch 설명서의 스냅샷 및 복원 단원 참조.


모든 스냅샷 리포지토리를 보기
$ curl -XGET 'elasticsearch-domain-endpoint/_snapshot?pretty'

리포지토리를 식별한 후, 다음 명령을 실행하여 모든 스냅샷 보기
$ curl -XGET 'elasticsearch-domain-endpoint/_snapshot/repository/_all?pretty'



다음 예제는 특정 도메인에 대한 기존 인덱스를 모두 삭제하는 방법
$ curl -XDELETE 'elasticsearch-domain-endpoint/_all'

특정 인덱스만 삭제
$ curl -XDELETE 'elasticsearch-domain-endpoint/index-name'

스냅샷을 복원
$ curl -XPOST 'elasticsearch-domain-endpoint/_snapshot/repository/snapshot/_restore'

 

6-(2) 외부스냅샷 파일 옮기기

- 같은 리전, 같은 보안체계, 같은 망에 존재하는 ec2에서 진행.

- 먼저 스냅샷이 저장되는 S3에 '외부 스냅샷' 저장하기

- ec2 접속해서 커맨드에 명령어 작성

 

# 난 깔끔하게 올리기 위해 기존에 있던 index를 삭제하고 진행함

$curl -XPOST /_snapshot/my_backup/snapshot_1/_restore
{
  "indices": "index_1,wp,index_2",
  "ignore_unavailable": true,
  "include_global_state": true,
  "rename_pattern": "index_(.+)",
  "rename_replacement": "restored_index_$1"
}