'elastic'에 해당되는 글 130건

  1. 2021.02.02 [Elastic] Elasticsearch Cluster 구성하기 based on IaC 1
  2. 2021.01.20 [Filebeat] registry 파일 내 offset 초기화.
  3. 2020.09.23 [Elasticsearch] 멀티노드 논리적 실행.
  4. 2020.09.10 [Kibana+Docker] Docker Compose 내 elasticsearch.hosts 설정
  5. 2020.09.10 [Elasticsearch] Dynamic Templates 간단 정리
  6. 2020.09.10 [Elasticsearch+Docker] 로컬 클러스터 구성 시 흔한 실수.
  7. 2020.09.03 [Elasticsearch] API Key (중복)
  8. 2020.08.31 [Elastic] IaC 기반의 Cluster 관리
  9. 2020.08.26 [Elastic] Elastic Agent 테스트.
  10. 2020.06.19 [Elasticsearch] X-pack Security API Key 사용 해 보기

[Elastic] Elasticsearch Cluster 구성하기 based on IaC

Elastic 2021. 2. 2. 12:04

https://github.com/HowookJeong/ecos-installer-web

배포 및 실행 가이드

Prerequisite)

  • bastion machine 은 ubuntu 를 사용 합니다.
  • bastion 및 ec2 instance 에 ssh tunnuling 을 위한 key pairs 생성을 합니다.
  • 로컬 장비에서 실행 하기 위해 계정의 access/secret key 생성을 합니다.

Step 1) Local 실행 환경 구성

$ aws configure --profile ecos 

Put region : ap-northeast-2
Put output : json
Put access key : xxxxxxxxxxxxxx
Put secret key : xxxxxxxxxxxxxx
Put key pairs file to ~/.ssh/

 

Step 2) Terraform & Ansible 환경 설정

$ vi docker-compose.yml

 environment:
 ...중략...
   - serverPort=${SERVER_PORT}
   - configWorkingPath=/tmp/home/mzc/app
   - configTerraformAwsBastionIp=${BASTION_IP}
   - configTerraformAwsSecurityGroup=sg-xxxxxxxxxxxxxxxx
   - configTerraformAwsAz=ap-northeast-2a
   - configTerraformAwsAmi=ami-061b0ee20654981ab
   - configTerraformAwsSubnet=subnet-xxxxxxxxxxxxxxxx
   - configTerraformAwsKeyName=ec2key-gw
   - configTerraformAwsPemFile=ec2key-gw.pem
   - configTerraformAwsPathElasticsearch=/tmp/home/mzc/app/terraform/_CLUSTERNAME_
   - configTerraformAwsPathKibana=/tmp/home/mzc/app/terraform/_CLUSTERNAME_/kibana
   - configTerraformAwsBackendBucket=megatoi-terraform-state
   - configTerraformAwsBackendKeyElasticsearch=_CLUSTERNAME_/terraform.tfstate
   - configTerraformAwsBackendKeyKibana=_CLUSTERNAME_/kibana/terraform.tfstate
 volumes:
 ...중략...
   - /Users/계정/.aws:/root/.aws
   - /Users/계정/.ssh:/root/.ssh

 

Step 3) 배포 된 docker image load

$ sudo docker load -i ecos-installer-web-0.0.1.tar

 

Step 4) 컨테이너 실행/중지

$ ENV=dev TAG=0.0.1 REDIRECT_HTTPS=true SERVER_PORT=8081 docker-compose up -d

$ ENV=dev TAG=0.0.1 REDIRECT_HTTPS=true SERVER_PORT=8081 docker-compose down

Local 개발 환경

  • $ cd .aws
  • $ aws configure --profile ecos
  • $ vi config

[profile ecos]

region = ap-northeast-2

output = json

  • $ vi credentials

[ecos]

aws_access_key_id = xxxxxxxxxxxxxxxxx

aws_secret_access_key = xxxxxxxxxxxxxxxxxx

Project Docker Compose 설정

...중략...
    volumes:
      - /Users/mzc02-henryjeong/.aws:/root/.aws
      - /Users/mzc02-henryjeong/.ssh:/root/.ssh
      - /Users/mzc02-henryjeong/Temp/logs:/home/mzc/logs
      - /var/run/docker.sock:/var/run/docker.sock
      - /Users/mzc02-henryjeong/Works/app/terraform:/home/mzc/backup/terraform
...중략...
  • aws 접속 및 ssh 터널링을 위해 관련 path 에 대한 mount 를 합니다.

Build Step

  • $ ./gradlew clean build bootJar -Pprofile=dev -x test
  • $ docker build --build-arg BASTION_IP=xxx.xxx.xxx.xxx --tag ecos-installer-web:0.0.1 .
  • OR $ ENV=dev TAG=0.0.1 REDIRECT_HTTPS=true SERVER_PORT=8081 docker-compose build
  • $ ENV=dev TAG=0.0.1 REDIRECT_HTTPS=true SERVER_PORT=8081 docker-compose up
  • $ ENV=dev TAG=0.0.1 REDIRECT_HTTPS=true SERVER_PORT=8081 docker-compose down
  • $ docker image ls
  • $ docker rmi -f 7f52709a6615
  • $ docker exec -it ecos-installer-web /bin/sh
  • $ sudo docker save -o ecos-installer-web-0.0.1.tar ecos-installer-web:0.0.1
  • $ sudo docker load -i ecos-installer-web-0.0.1.tar

Terraform path 와 Elasticsearch Cluster 명명 규칙

  • Terraform File Path : /tmp/home/mzc/app/terraform/${CLUSTERNAME}/${TIMESTAMP}
  • Backend Key : ${CLUSTERNAME}/${TIMESTAMP}/terraform.tfstate
  • 신규 생성 시
    • Step 1) Terraform File Path : /tmp/home/mzc/app/terraform/elasticsearch
    • Step 1) Backend Key : elasticsearch/terraform.tfstate
  • 추가 시
    • Step 1) Terraform File Path : /tmp/home/mzc/app/terraform/elasticsearch/1598860075233
    • Step 1) Backend Key : elasticsearch/1598860075233/terraform.tfstate
    • Step 2) Backend Key : elasticsearch/1598860075233/terraform.tfstate
    • 기존 클러스터에 Join 시키기 위해 master ip 정보를 구해야 함

생성 및 설정

  • aws account access/secret key 생성
  • aws configure 설정
  • bastion 서버 생성
  • vpc 내 정보 설정
    • security group
    • subnet
    • az
    • ec2 네트워크 및 보안에서 키 페어 생성 및 등록 (keyName, keyPem)
    • ami
  • terraform 정보 설정
    • terraform working path 설정
    • terraform backend 설정
  • aws cluster instance 설정
    • node topology 설정 (node 유형)
    • instance type 설정 (cpu, mem, network 성능)
    • instance size 설정 (node 규모)
    • disk volume size 설정 (elasticsearch storage)
  • elasticsearch cluster 설정
    • cluster name 설정
    • 설치를 위한 elasticsearch version 지정
    • port 설정 (http, tcp)
    • path.data/logs 설정
  • ansible 설정
    • working path 설정
    • bastion ip 설정

Service Flow

  • TerraformService

    • terraform
      • createTerraformS3Backend
      • readTerraformTemplateForElasticsearch
      • writeTerraformTemplateForElasticsearch
      • runTerraformTemplateForElasticsearch
      • backupTerraformTemplateStateForElasticsearch (if it is not s3 backend)
  • ElasticsearchService

    • docker
      • createDockerComposeConfiguration
    • ansible
      • createAnsibleInventories
      • createAnsibleRoles

runAnsiblePlaybook

:

[Filebeat] registry 파일 내 offset 초기화.

Elastic/Beats 2021. 1. 20. 15:14

filebeat 의 registry 관련 설정 정보는 아래 공식 문서를 참고하세요.

www.elastic.co/guide/en/beats/filebeat/current/configuration-general-options.html

 

문서 설명에도 있지만, 

 

- 기본 경로는 아래와 같습니다.

The default is ${path.data}/registry

 

Registry 의 구조체를 확인해 보면 아래와 같은데요.

type Registry struct {
	Path          string        `config:"path"`
	Permissions   os.FileMode   `config:"file_permissions"`
	FlushTimeout  time.Duration `config:"flush"`
	CleanInterval time.Duration `config:"cleanup_interval"`
	MigrateFile   string        `config:"migrate_file"`
}

설정에서 path 를 잡아 주지 않으면, 코드 상으로는  "filebeat.py"

default_registry_path = 'registry/filebeat'

위 경로 아래 meta.json 과 log.json 두 개의 파일이 생기고 파일들에 대한 offset 관리가 이루어 집니다.

 

Logstash input file 의 sincedb 와 같이 offset  정보를 reset 하기 위해서는 

- log.json 에서 offset 설정을 다시 해주거나

- 걍 registry 삭제 하고 재 시작 하시면 됩니다.

 

tail_files 설정도 있고 해당 log file 삭제를 하는 것도 있고, 용도와 목적에 맞게 시도해 보시면 될 것 같습니다.

 

:

[Elasticsearch] 멀티노드 논리적 실행.

Elastic/Elasticsearch 2020. 9. 23. 16:53

elasticsearch-version.tar.gz 을 받아서 압축 해제 한 후에 단일 인스턴스에서 여러개의 노드를 실행 시켜 클러스터 구성을 하기 위한 방법 입니다.

 

Case 1)

$ ES_PATH_CONF=config bin/elasticsearch -Epath.data=data1 -Epath.logs=logs1 -d -p 1.pid

$ ES_PATH_CONF=config bin/elasticsearch -Epath.data=data2 -Epath.logs=logs2 -d -p 2.pid

$ ES_PATH_CONF=config bin/elasticsearch -Epath.data=data3 -Epath.logs=logs3 -d -p 3.pid

 

Case 2)

$ ES_PATH_CONF=config1 bin/elasticsearch -Epath.data=data1 -Epath.logs=logs1 -d -p 1.pid

$ ES_PATH_CONF=config2 bin/elasticsearch -Epath.data=data2 -Epath.logs=logs2 -d -p 2.pid

$ ES_PATH_CONF=config3 bin/elasticsearch -Epath.data=data3 -Epath.logs=logs3 -d -p 3.pid

 

별다른건 하나도 없으며, 활용하는 방법에 대한 차이 정도로 보면 될 것 같습니다.

:

[Kibana+Docker] Docker Compose 내 elasticsearch.hosts 설정

Elastic/Kibana 2020. 9. 10. 16:56

기본적으로 config/kibana.yml 에서는 array 로 설정을 하게 되어 있습니다.

Kibana : Multi-Elasticsearch 로 등록이 가능 하다는 것인데요.

 

Kibana 를 Docker 로 구성 할 경우 일반적인 yaml 문법의 array 등록 방식으로 작성을 하게 되면 에러가 발생을 합니다.

그래서 아래와 같이 작성을 하셔야 합니다.

 

[Code Example]

version: "3.7"
services:
  dockerr-kibana:
    image: docker.elastic.co/kibana/kibana:7.9.1
    container_name: docker-kibana
    environment:
      ELASTICSEARCH_HOSTS: '["http://host.docker.internal:9200","http://host.docker.internal:9201","http://host.docker.internal:9202"]'
    ports:
      - 5601:5601
    expose:
      - 5601
    restart: always
    network_mode: bridge

 

[Error Code]

version: "3.7"
services:
  dockerr-kibana:
    image: docker.elastic.co/kibana/kibana:7.9.1
    container_name: docker-kibana
    environment:
      ELASTICSEARCH_HOSTS: 
        - "http://host.docker.internal:9200"
        - "http://host.docker.internal:9201"
        - "http://host.docker.internal:9202"
    ports:
      - 5601:5601
    expose:
      - 5601
    restart: always
    network_mode: bridge

[Error Message]

$ docker-compose up
ERROR: The Compose file './docker-compose.yml' is invalid because:
services.dockerr-kibana.environment.ELASTICSEARCH_HOSTS contains ["http://host.docker.internal:9200", "http://host.docker.internal:9201", "http://host.docker.internal:9202"], 
which is an invalid type, it should be a string, number, or a null

 

:

[Elasticsearch] Dynamic Templates 간단 정리

Elastic/Elasticsearch 2020. 9. 10. 12:18

Elasticsearch Reference 를 그대로 의역한 수준 이라고 보시면 될것 같습니다.

 

[참고문서]

www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-templates.html

www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-field-mapping.html

 

match_mapping_type)
JSON 파서를 통해서 data type 을 detection 합니다.
long, double 의 경우 integer 와 float 에 대한 정확한 detection 이 어렵기 때문에 항상 long 과 double 로 detection 하게 됩니다.

detection type 은 아래와 같습니다.
- boolean
- date
- double
- long
- object
- string

[Code Snippet from Elastic]
- long type 으로 matching 된 것을 모두 integer 로 설정 하는 것과
- string type 으로 matching 된 것을 모두 text 와 fields 설정을 이용해서 keyword 로 설정 하는 것입니다.

PUT my-index-000001
{
  "mappings": {
    "dynamic_templates": [
      {
        "integers": {
          "match_mapping_type": "long",
          "mapping": {
            "type": "integer"
          }
        }
      },
      {
        "strings": {
          "match_mapping_type": "string",
          "mapping": {
            "type": "text",
            "fields": {
              "raw": {
                "type":  "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    ]
  }
}


match and unmatch)
이 설정은 field명에 대한 패턴 매칭을 이용해서 data type 을 detection 합니다.
unmatch 패턴은 제외 시키기 위한 설정 이라고 생각 하면 됩니다.

[Code Snippet from Elastic]
- data type 이 string 으로 매칭 된 경우 필드명을 통해 최종 설정을 하는 것입니다.
- 필드명을 통해서 data type 을 설정 하는 것입니다.

PUT my-index-000001
{
  "mappings": {
    "dynamic_templates": [
      {
        "longs_as_strings": {
          "match_mapping_type": "string",
          "match":   "long_*",
          "unmatch": "*_text",
          "mapping": {
            "type": "long"
          }
        }
      }
    ]
  }
}


match_pattern)
이 설정은 위에서 "match":   "long_*" 과 같은 wildcard 패턴을 java 정규식으로 사용하기 위한 설정입니다.

[Code Snippet from Elastic]

  "match_pattern": "regex",
  "match": "^profit_\d+$"


path_match and path_unmatch)
이 설정은 nested 나 object field 에 대한 match, unmatch 와 동일한 설정 입니다.

% Nested field type
The nested type is a specialised version of the object data type 
that allows arrays of objects to be indexed in a way 
that they can be queried independently of each other.

{name} and {dynamic_type}
이 설정은 field명을 {name} 으로 사용하고 matching 된 data type 을 {dynamic_type} 으로 사용하는 설정입니다.

[Code Snippet from Elastic]
- analyzer 로 english analyer 를 사용 하겠다는 의미 입니다. {name} == "english"
- {dynamic_type} == long 으로 매칭이 되었고 doc_values 를 사용하지 않겠다는 의미 입니다.

PUT my-index-000001
{
  "mappings": {
    "dynamic_templates": [
      {
        "named_analyzers": {
          "match_mapping_type": "string",
          "match": "*",
          "mapping": {
            "type": "text",
            "analyzer": "{name}"
          }
        }
      },
      {
        "no_doc_values": {
          "match_mapping_type":"*",
          "mapping": {
            "type": "{dynamic_type}",
            "doc_values": false
          }
        }
      }
    ]
  }
}

PUT my-index-000001/_doc/1
{
  "english": "Some English text", 
  "count":   5 
}

지금까지 보셨다면 위 설정은 Index 에 직접 설정 한다는 것을 아실 수 있습니다.

하지만 Elasticsearch 에서는 별도 Index Template 이라는 것을 제공 하고 있습니다.

 

[참고문서]

www.elastic.co/guide/en/elasticsearch/reference/7.9/index-templates.html

www.elastic.co/guide/en/elasticsearch/reference/7.9/indices-templates-v1.html

www.elastic.co/guide/en/elasticsearch/reference/7.9/indices-component-template.html

 

이 index template 설정은 최신 버전으로 넘어 오면서 두 가지 타입이 존재 합니다.

- _template 에 설정

PUT /_template/<index-template>

 

- _component_template 에 설정
PUT /_component_template/<component-template>

 

이 설정이 dynamic template 과의 차이는 index 에 직접 하느냐 cluster 에 하느냐의 차이 입니다.

더불어 dynamic template 은 mapping 에 대한 내용이지만 index template 은 setting, mapping 등 모두 포함 하고 있습니다.

중요한 내용이니 꼭 인지 하시기 바랍니다.
더불어 주의 하셔야 하는 점은 이런 템플릿 설정은 인덱스가 생성 되는 시점에 적용이 되는 것이기 때문에,

이미 생성된 인덱스에는 영향을 끼치지 못한다는 것도 알아 두셔야 합니다.

 

[Code Example]

- 아래 template 과 dynamic mapping 을 함께 설정한 예제 입니다.

- 기존 예제만 함쳐 놓은 것이기 때문에 구성에 맞게 고쳐서 사용 하시면 됩니다.

PUT /_template/template_1
{
  "index_patterns" : ["te*"],
  "order" : 0,
  "settings" : {
    "number_of_shards" : 1
  },
  "mappings" : {
    "_source" : { "enabled" : false },
    "dynamic_templates": [
      {
        "integers": {
          "match_mapping_type": "long",
          "mapping": {
            "type": "integer"
          }
        }
      },
      {
        "strings": {
          "match_mapping_type": "string",
          "mapping": {
            "type": "text",
            "fields": {
              "raw": {
                "type":  "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    ]
  }
}

 

:

[Elasticsearch+Docker] 로컬 클러스터 구성 시 흔한 실수.

Elastic/Elasticsearch 2020. 9. 10. 08:54

Elasticsearch 가 각 노드들과 discovery 를 하기 위해서는 Transport 통신이 이루어져야 합니다.

문서에 정확하게 나와 있으나 놓치기 쉬운 부분이라 기록해 봅니다.

 

[참고문서]

https://www.elastic.co/guide/en/elasticsearch/reference/current/discovery-settings.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-bootstrap-cluster.html
https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-settings.html

 

[Content Snippet]

[discovery.seed_hosts]

Provides a list of the addresses of the master-eligible nodes in the cluster.

1. transport.profiles.default.port
2. transport.port
If neither of these is set then the default port is 9300.

[Example Configuration]

[Node 1 - docker-compose.yml]
version: '3.7'

services:
  docker-es:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1
    container_name: e1
    environment:
      - cluster.name=e3k1
      - node.name=e1
...중략...
      - discovery.seed_hosts=host.docker.internal:9300,host.docker.internal:9301,host.docker.internal:9302
      - cluster.initial_master_nodes=e1,e2,e3
...중략...

[Node 2 - docker-compose.yml]
version: '3.7'

services:
  docker-es:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1
    container_name: e2
    environment:
      - cluster.name=e3k1
      - node.name=e2
...중략...
      - discovery.seed_hosts=host.docker.internal:9300,host.docker.internal:9301,host.docker.internal:9302
      - cluster.initial_master_nodes=e1,e2,e3
...중략...

[Node 3 - docker-compose.yml]
version: '3.7'

services:
  docker-es:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.9.1
    container_name: e3
    environment:
      - cluster.name=e3k1
      - node.name=e3
...중략...
      - discovery.seed_hosts=host.docker.internal:9300,host.docker.internal:9301,host.docker.internal:9302
      - cluster.initial_master_nodes=e1,e2,e3
...중략...

 

위에 작성된 설정 예제는 로컬에서 3개의 Elasticsearch 컨테이너를 실행 시켜서 클러스터링 시키는 예제 입니다.

이 방법 말고도 하나의 docker-compose.yml 에 구성을 하셔도 됩니다. (단, 설정이 조금 달라 집니다.)

 

주의 점은,

위에 언급된 내용처럼 Transport 통신을 한다는 것을 잊으면 안된다는 것입니다.

:

[Elasticsearch] API Key (중복)

Elastic/Elasticsearch 2020. 9. 3. 10:16

이전에 작성한 글과 중복 내용이 있습니다.

 

이전 글)

jjeong.tistory.com/1487

 

Elasticsearch + Kibana 사용 시 basic security 설정을 enable 하게 되면 Restful API 사용을 위한 API Key 를 생성 해서 사용을 해야 합니다.

 

Kibana devtools 를 이용해서 할 경우 인증이 되어 있어서 /_security/api_key 사용이 가능 하지만 Postman 과 같은 걸 이용할 경우 id:pwd 를 넣어 줘야 합니다.

[Case 1]
http://elastic:elasticpassword@localhost:9200/_security/api_key

[Case 2]
curl -XPUT -u elastic:elasticpassword "http://localhost:9200/_security/api_key" -d
{
  "name": "team-index-command",
  "expiration": "10m", 
  "role_descriptors": { 
    "role-team-index-command": {
      "cluster": ["all"],
      "index": [
        {
          "names": ["*"],
          "privileges": ["all"]
        }
      ]
    }
  }
}

 

API Key 구조)

- /_security/api_key 를 이용해서 생성을 하면 아래와 같은 값이 나옵니다.

[Request]
POST /_security/api_key
{
  "name": "team-index-command",
  "expiration": "10m", 
  "role_descriptors": { 
    "role-team-index-command": {
      "cluster": ["all"],
      "index": [
        {
          "names": ["*"],
          "privileges": ["all"]
        }
      ]
    }
  }
}

[Response]
{
  "id" : "87cuynIBjKAXtnkobGgo",
  "name" : "team-index-command",
  "expiration" : 1592529999478,
  "api_key" : "OlVGT_Q8RGq1C_ASHW7pGg"
}

- API Key 는 id:api_key 조합으로 base64 encoding 된 값입니다.

base64_encode("87cuynIBjKAXtnkobGgo"+":"+"OlVGT_Q8RGq1C_ASHW7pGg")

 

API Key 를 이용한 Restful API 호출)

$ curl 
  -H "Authorization: ApiKey VGVVOXluSUJHUUdMaHpvcUxDVWo6aUtfSmlEMmdSMy1FUUFpdENCYzF1QQ==" 
  http://localhost:9200/_cluster/health

 

:

[Elastic] IaC 기반의 Cluster 관리

Elastic 2020. 8. 31. 12:40

Elastic Stack 은 서비스나 데이터를 다루는 모든 기업에서 사용을 하고 있는 매우 훌륭한 오픈소스 입니다.

 

기본적으로 

  • Elasticsearch
  • Kibana
  • Logstash
  • Beats

이 4가지 Stack 을 이야기 하고 있으며,

잘 활용 하실 경우 현존 하는 많은 상용 도구들을 모두 재낄 수 있습니다.

 

단, 기술 내재화와 역량을 확보 하겠다는 의지가 있을 경우에 한해서 입니다.

 

제가 지금까지 다니던 회사는 주로 서비스 회사 였기 때문에,

특정 도메인에 필요로 하는 기능 개발과 스타트업 특성에 따른 빠른 개발을 할 수 밖에 없었습니다.

올해 회사를 옮기면서 그 동안 만나 봤던 분들의 어려움을 해결 할 수 있는 방법은 없을까 하고 고민 하다,

Elastic Stack 에 대한 설치 자동화 프로그램을 만들어 보기로 했습니다.

 

그 결과로 우선 1차 버전을 이야기 해볼까 합니다.

 

Elasticsearch 는 누구나 쉽게 사용이 가능 합니다.

검색 (IR) 에 대한 지식이나 전문성이 없어도 Elasticsearch 를 도구적으로 설치 하고 사용 하는 데는 별 문제가 없습니다.

그래서 빠른 PoC 작업을 할 수도 있는 것 같습니다.

 

하지만 클러스터를 구성 하고 이를 운영 하면서 인프라 관점으로 접근 하다 보면 어려움이 생기게 됩니다.

  • 사용하고자 하는 부서는 많고,
  • 그렇다고 단일 클러스터로 구성해서 사용하라고 제공해 줄 수도 없고,
  • 인프라 생성 요청도 해야 하고,
  • 설정 및 설치도 해야 하고,
  • 문제가 생기면 위 과정을 다시 반복 해야 하고,
  • 클러스터 최적화는 또 어떻게 해야 하고,

등등....

 

요청자와 생성자의 편의를 제공 할 수 있으면 어떨까 싶었습니다.

 

제가 만들어 본 Application 은 아래 Stack 을 이용해서 개발이 되었습니다.

  • Spring Framework
  • Terraform
  • Ansible
  • Docker
  • AWS (EC2, S3)
  • Elasticsearch

AWS 기반으로 먼저 개발을 진행을 했고 추후 Azure 나 GCP 로도 확장을 할 예정입니다.

 

기본 동작 방식은 아래와 같습니다.

1.  Application Container

  - 인프라 구성을 위한 정보를 설정 하고 설치 파일을 생성 합니다.

    - Terraform 관련 파일을 생성 합니다. (setup.tf)

  - 생성 될 인스턴스에 설치 할 정보를 설정하고 설치 파일을 생성 합니다. 

    - Ansible 관련 파일을 생성 합니다. (playbook, inventories, roles)

  - 클러스터 구성을 위한 정보를 설정 하고 설치 파일을 생성 합니다.

    - Docker Compose 관련 파일을 생성 합니다. (docker-compose.yml)

2. Terraform Backend - S3

  - Terraform 을 이용해서 생성한 인스턴스의 정보는 s3 backend 에 저장이 됩니다.

3. Bastion

  - 설치 시 보안 관리를 위해 bastion 서버로 ssh tunneling 하여 설치 합니다.

 

화면 구성은 아래와 같습니다.

 

그림 1) Terraform 설정 정보와 Elasticsearch Cluster Node Topology 설정 및 실행 화면

그림 2) Ansible 을 이용한 Node 환경 구성 설정 및 실행 화면

그림 3) Elasticsearch Cluster 실행 화면

그림 4) 생성 된 Cluster 에 대한 목록 및 관리 화면

그림 5) 개별 클러스터의 Node 에 대한 관리 화면

 

만들어진 Application 은 도커 기반으로 개발이 되어 있기 때문에 어떤 환경에서든 실행이 가능 합니다.
가장 기초적인 부분에서 부터 출발한 것으로 

  • 클러스터 구성 및 설치는 어떻게 해야 하는가?
  • 클러스터 구성 시 최적화는 되어 있는가?
  • 클러스터를 쉽게 생성 하고 삭제 할 수 있는가?
  • 이미 생성된 클러스터에 노드 추가는 어떻게 해야 하는가?
  • 개별 노드들에 대한 시작과 중지를 할 수 있는가?

등등...

 

보시는 바와 같이 클러스터의 생성에서 부터 시작과 중지에 대한 기초 부터 접근을 했습니다.

 

Elasticsearch 는 크게 3 가지 유형으로 사용을 하게 됩니다.

  • 검색
  • 저장(색인)
  • 분석

 

위 3 가지 유형을 가지고 Business Domain 별 사용을 하게 되는 것입니다.

  • e-Commerce 상품 검색
  • SIEM
  • Log 및 Data 분석 시스템

등등 ...

 

이걸 좀 더 고도화 한다고 하면 아래와 같은 서비스들을 쉽게 만들수도 있습니다.

  • AWS Elasticsearch Service
  • Elastic Cloud - Elasticsearch

회사에서 어떤 전략으로 접근 할 지 아직은 잘 모르겠습니다.

이미 IaC 기반으로 잘 제공 되고 있는 MSP (Elastic, AWS) 가 있는데, 우리가 이것 까지 해야 할까?

 

이 문제는 뒤로 하고,

Elasticsearch 를 사용하거나 사용하고자 하는 스타트업이 있다면,

누구라도 쉽게 최적화된 클러스터를 생성하고 인프라를 관리 할 수 있도록 제공하면 좋겠다는게 지금 저의 생각 입니다.

 

오픈소스로 공개를 해도 되고, 컨테이너 이미지를 docker registry 에 등록을 해도 되고 몇 가지 방법이 있겠지만,

정말 이런게 필요한지 부터 고민을 더 해봐야 할 것 같습니다.

 

아무도 필요로 하지 않는데 계속 투자를 해야 할지도 고민이라서요. ^^;

 

ECOS(Elastic Cloud Open Stack) Installer 의 기능을 간략하게 요약해 드리면,

  1. Elasticsearch Cluster 구성을 위한 GUI 환경을 제공 합니다.
  2. Terraform 기반의 리소스 생성을 제공 합니다.
  3. Ansible 기반의 설치 및 운영 환경을 제공 합니다.
  4. Docker 기반의 Cluster 환경 구성 및 관리 기능을 제공 합니다.
  5. Elasticsearch 설정을 잘 몰라도 됩니다. (이왕이면 알면 좋습니다.)
  6. Cluster 환경을 최적화 해서 구성해 줍니다.
  7. Terraform, Ansible, Docker 등에 대해서 잘 몰라도 됩니다. (이왕이면 알면 좋습니다.)
  8. 리소스를 쉽게 제공하고 회수 할 수 있습니다.
  9. Cluster 내 Node 추가 기능을 제공 합니다.

ECOS Installer 는 우선

  • MZC( Megazone Cloud) 고객사 중
  • 기술 내재화를 고민 하고 계신 고객사

를 찾아서 설치 및 기술 이전을 해보려 합니다.

 

피드백을 받아 가면서 업그레이드를 해보도록 하겠습니다.

 

감사합니다.

:

[Elastic] Elastic Agent 테스트.

Elastic 2020. 8. 26. 15:10

[참고문서]

https://www.elastic.co/downloads/elastic-agent

https://www.elastic.co/guide/en/ingest-management/current/index.html

 

Elastic Agent 를 사용해 보려고 합니다.

최근에 릴리즈 된 Elastic Stack 7.9.0 으로 진행 했습니다.

 

진행 간에 순서대로 실행한 내용을 그냥 올려 둡니다.

$ bin/elasticsearch -d -p pid
$ bin/elasticsearch-setup-passwords interactive
에러 발생)
{
  "error" : {
    "root_cause" : [
      {
        "type" : "exception",
        "reason" : "Security must be explicitly enabled when using a [basic] license. Enable security by setting [xpack.security.enabled] to [true] in the elasticsearch.yml file and restart the node."
      }
    ],
    "type" : "exception",
    "reason" : "Security must be explicitly enabled when using a [basic] license. Enable security by setting [xpack.security.enabled] to [true] in the elasticsearch.yml file and restart the node."
  },
  "status" : 500
}

xpack security 설정)
$ vi config/elasticsearch.yml
xpack.security.enabled: true
xpack.security.authc.api_key.enabled: true

재실행)
$ bin/elasticsearch-setup-passwords interactive
$ bin/elasticsearch-setup-passwords interactive
Initiating the setup of passwords for reserved users elastic,apm_system,kibana,kibana_system,logstash_system,beats_system,remote_monitoring_user.
You will be prompted to enter passwords as the process progresses.
Please confirm that you would like to continue [y/N] y


Enter password for [elastic]: elastic
Reenter password for [elastic]: elastic
Enter password for [apm_system]: elastic
Reenter password for [apm_system]: elastic
Enter password for [kibana_system]: elastic
Reenter password for [kibana_system]: elastic
Enter password for [logstash_system]: elastic
Reenter password for [logstash_system]: elastic
Enter password for [beats_system]: elastic
Reenter password for [beats_system]: elastic
Enter password for [remote_monitoring_user]: elastic
Reenter password for [remote_monitoring_user]: elastic
Changed password for user [apm_system]
Changed password for user [kibana_system]
Changed password for user [kibana]
Changed password for user [logstash_system]
Changed password for user [beats_system]
Changed password for user [remote_monitoring_user]
Changed password for user [elastic]

Kibana 설정)
$ vi config/kibana.yml
46 elasticsearch.username: "kibana_system"
47 elasticsearch.password: "elastic"

$ bin/kibana

Kibana 접속)
http://localhost:5601
  ID/PWD
  elastic/elastic

Kibana IngestManager 접속)
http://localhost:5601/app/ingestManager#/

Agent 사용을 위한 Kibana 추가 설정)
xpack.ingestManager.fleet.tlsCheckDisabled: true
xpack.encryptedSavedObjects.encryptionKey: a123456789012345678901234567890b

이후 단계는 아래 문서 대로 따라 합니다.)
https://www.elastic.co/guide/en/ingest-management/current/ingest-management-getting-started.html
./elastic-agent enroll http://localhost:5601 cEpibEtIUUI2akhoRVR0LWdwZVg6blhHNGdMeURUbVNPQUE0RS1GOFduUQ==
./elastic-agent run

$  ./elastic-agent enroll http://localhost:5601 cEpibEtIUUI2akhoRVR0LWdwZVg6blhHNGdMeURUbVNPQUE0RS1GOFduUQ==
The Elastic Agent is currently in BETA and should not be used in production
This will replace your current settings. Do you want to continue? [Y/n]: y
Error: connection to Kibana is insecure, strongly recommended to use a secure connection (override with --insecure)

$ ./elastic-agent enroll http://localhost:5601 cEpibEtIUUI2akhoRVR0LWdwZVg6blhHNGdMeURUbVNPQUE0RS1GOFduUQ== --insecure
The Elastic Agent is currently in BETA and should not be used in production
This will replace your current settings. Do you want to continue? [Y/n]:y
2020-08-26T14:06:01.782+0900  DEBUG kibana/client.go:170  Request method: POST, path: /api/ingest_manager/fleet/agents/enroll
Successfully enrolled the Agent.

$ ./elastic-agent run

Kibana IngestManager 확인)
http://localhost:5601/app/ingestManager#/

Elasticsearch + Kibana + ElasticAgent + Elastic Common Schema 구성이며, 기존에 beats 를 이용해서 log/data shipper 기능을 구현 하던걸 agent 하나로 대체 할 수 있을 것 같습니다.

더불어서 ECS 기반의 Kibana 에서 Dashboard 와 Visualize 에 대해서도 Preset 을 제공 하니 잘 활용하면 아주 멋질 것으로 기대 합니다.

:

[Elasticsearch] X-pack Security API Key 사용 해 보기

Elastic/Elasticsearch 2020. 6. 19. 11:07

Elastic Stack 이 좋은 이유는 기본 Basic license 까지 사용이 가능 하다는 것입니다.

사실 이것 말고도 엄청 많죠 ㅎㅎ 

 

https://www.elastic.co/subscriptions

 

딱 API keys management 까지 사용이 됩니다. ㅎㅎㅎ

 

먼저 사용하기에 앞서서 Elasticsearch 와 Kibana 에 x-pack 사용을 위한 설정을 하셔야 합니다.

 

[Elasticsearch]

- elasticsearch.yml

xpack.monitoring.enabled: true
xpack.ml.enabled: true
xpack.security.enabled: true

xpack.security.authc.api_key.enabled: true
xpack.security.authc.api_key.hashing.algorithm: "pbkdf2"
xpack.security.authc.api_key.cache.ttl: "1d"
xpack.security.authc.api_key.cache.max_keys: 10000
xpack.security.authc.api_key.cache.hash_algo: "ssha256"

위 설정은 기본이기 때문에 환경에 맞게 최적화 하셔야 합니다.

https://www.elastic.co/guide/en/elasticsearch/reference/7.8/security-settings.html#api-key-service-settings

 

[Kibana]

- kibana.yml

xpack:
  security:
    enabled: true
    encryptionKey: "9c42bff2e04f9b937966bda03e6b5828"
    session:
      idleTimeout: 600000
    audit:
      enabled: true

 

이렇게 설정 한 후 id/password 설정을 하시면 됩니다.

 

# bin/elasticsearch-setup-passwords interactive
Initiating the setup of passwords for reserved users elastic,apm_system,kibana,logstash_system,beats_system,remote_monitoring_user.
You will be prompted to enter passwords as the process progresses.
Please confirm that you would like to continue [y/N]y

Enter password for [elastic]:
Reenter password for [elastic]:
Enter password for [apm_system]:
Reenter password for [apm_system]:
Enter password for [kibana]:
Reenter password for [kibana]:
Enter password for [logstash_system]:
Reenter password for [logstash_system]:
Enter password for [beats_system]:
Reenter password for [beats_system]:
Enter password for [remote_monitoring_user]:
Reenter password for [remote_monitoring_user]:
Changed password for user [apm_system]
Changed password for user [kibana]
Changed password for user [logstash_system]
Changed password for user [beats_system]

Changed password for user [remote_monitoring_user]
Changed password for user [elastic]

 

이렇게 설정이 끝나면 kibana 에 접속해서 API key 를 생성 하시면 됩니다.

아래 문서는 생성 시 도움이 되는 문서 입니다.

 

www.elastic.co/guide/en/elasticsearch/reference/current/security-privileges.html

www.elastic.co/guide/en/elasticsearch/reference/7.7/security-api-put-role.htmlwww.elastic.co/guide/en/elasticsearch/reference/7.7/defining-roles.htmlwww.elastic.co/guide/en/elasticsearch/reference/7.7/security-api-create-api-key.html

 

Kibana Console 에서 아래와 같이 생성이 가능 합니다.

POST /_security/api_key
{
  "name": "team-index-command",
  "expiration": "10m", 
  "role_descriptors": { 
    "role-team-index-command": {
      "cluster": ["all"],
      "index": [
        {
          "names": ["*"],
          "privileges": ["all"]
        }
      ]
    }
  }
}

{
  "id" : "87cuynIBjKAXtnkobGgo",
  "name" : "team-index-command",
  "expiration" : 1592529999478,
  "api_key" : "OlVGT_Q8RGq1C_ASHW7pGg"
}

생성 이후 사용을 위해서는 

 

- ApiKey 는 id:api_key 를 base64 인코딩 합니다.

base64_encode("87cuynIBjKAXtnkobGgo"+":"+"OlVGT_Q8RGq1C_ASHW7pGg")
==> VGVVOXluSUJHUUdMaHpvcUxDVWo6aUtfSmlEMmdSMy1FUUFpdENCYzF1QQ==
curl -H 
  "Authorization: ApiKey VGVVOXluSUJHUUdMaHpvcUxDVWo6aUtfSmlEMmdSMy1FUUFpdENCYzF1QQ==" 
  http://localhost:9200/_cluster/health

이제 용도와 목적에 맞춰서 API key 를 만들고 사용 하시면 되겠습니다.

 

: