2022년 1월 3일 월요일

[ Elasticsearch ] index template


[ Index template ] 

보통 날짜별로 elasticsearch에 index를 생성하여 사용하는데

매번 데이터가 들어올 때 마다 mapping을 통해 field type을 지정하지 않기 위해

Index template를 사용한다.


생성 예시 

* 일별로 log-20220101, log-20220101 형식으로 인덱스 생성된다.

PUT _template/log_template
{

    "order": 0,
    "index_patterns": [
        "log-20*"
    ],
    "settings": {
        "index": {
            "number_of_shards": "1",
            "number_of_replicas": "1",
        }
    },
    "mappings": {
        "properties": {
            "user_id": {
                "type": "long"
            },
            "name": {
                "type": "text"
            },
            "sale": {
                "type": "long"
            },
            "sale_date": {
                "type": "date",
                "format": "yyyy-MM-dd"
            }
        }
    }
}


생성 template확인

GET _template/log_template


Field data types :

https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html

[ Elasticsearch ] Reindex


1. Temp index 생성

PUT users_temp


2. Temp index에 타입 Mapping

PUT users_temp/_mapping
{
  "properties": {
    "location": {
      "type": "geo_point"
    }
  }
}


3. Re-index를 Temp index에 실행
POST _reindex
{
  "source": {
    "index": "users"
  },
  "dest": {
    "index": "users_temp"
  }
}


4. User index 삭제
DELETE /users

5. 다시 User index 생성

PUT users

6. User index mapping

PUT users/_mapping
{
  "properties": {
    "location": {
      "type": "geo_point"
    }
  }
}


7. Re-index를 User index 실행

POST _reindex
{
  "source": {
    "index": "users_temp"
  },
  "dest": {
    "index": "users"
  }
}

 8. Temp index 삭제

DELETE /users_temp

2021년 12월 24일 금요일

[ Ansible ] ssh-key를 통한 비밀번호 없이 ssh접속


ssh/known_hosts 생성
ansible all -m ping -> yes로

# key생성
ssh-keygen -t rsa
ls -al .ssh/
    id_rsa
    id_rsa.pub
    known_hosts

# key 복사
ssh-copy-id dgk@172.1.1.11

# 원격 접속후 pub파일 잘 복사됬는지 확인
ssh dgk@172.1.1.11
ls -al .ssh/     authorized_keys

# 확인
ansible all -m ping


2021년 12월 21일 화요일

[ Ansible ] 설치 및 실행

/etc/sudoers 에 nopasswd 계정 추가 


앤서블 설치

$ yum install ansible -y


앤서블에서 사용 가능한 명령어 확인

$ ls /usr/bin/ansible*


노드들 주소 추가

$ vi /etc/ansible/hosts
(추가)
192.1.1.1
192.1.1.2
192.1.1.3


known_hosts_key 값 입력 받음

$ ansible all -m ping
(yes를 노드수만큼 입력)
....
Are you sure you want to continue connecting (yes/no)? yes


정상적으로 노드들에게 명령 전달 확인

$ ansible all -m ping -k
SSH password : (노드 비밀번호 입력)



앤서블 명령어 옵션

-m : 모듈선택 

  • 쉘모듈 : ansible all -m shell -a "df -h" -k 
  • yum모듈 : ansible all -m yum -a "name=httpd state=present" -k (삭제 : state=absent)

-k : 비밀번호 입력

  • --list-hosts : 적용 노드들 확인 ( ansible all -m ping -k --list-hosts )



앤서블 참조파일

/etc/ansible/ansible.cfg

/etc/ansible/hosts



플레이북

보통앤서블은 플레이북으로 노드들을 관리합니다.

nginx_install.yml 파일 작성

---
- name: Install nginx on linux
  hosts: nginx
  gather_facts : no

  tasks : 
    - name: install epel-release
      yum: name=epel-release state=latest
    - name: install nginx web server
      yum: name=nginx state=present
    - name: start nginx web server
      service: name=nginx state=started

플레이북 실행

$ ansible-playbook nginx_install.yml -k





앤서블 기본 개념 참조글 :

https://blog.naver.com/alice_k106/221333208746

https://engineering.linecorp.com/ko/blog/ansible-awx-for-provisioning-1/


앤서블 공식사이트 : 

https://docs.ansible.com/ansible_community.html


남들이 짠 앤서블 플레이북 코드 : 

https://galaxy.ansible.com/crivetimihai/development

2021년 12월 16일 목요일

[ Elasticsearch ] Opendistro Kibana 유저 확인, 추가, 삭제


kibana역시 다른 BI툴과 같이 해당 유저의 Id/Password, Role을 정의할 수 있다.

path: /usr/share/elasticsearch/plugins/opendistro_security/securityconfig

  • 로그인 유저 설정파일 : internal_users.yml  
  • 역할 설정파일 : roles.yml
  • 역할 맵핑 설정파일 : roles_mapping.yml 
  • tenants관련 설정파일 : tenants.yml  


[ user 추가 ]


유저확인

1. curl명령어로 유저 확인

$ curl -GET https://localhost:9200/_opendistro/_security/api/internalusers/ -u 'admin:admin' --insecure


2. 유저 정보가 저장되어있는 설정파일 internal_users.yml 확인

$ sudo vi /usr/share/elasticsearch/plugins/opendistro_security/securityconfig/internal_users.yml




3. kibana web ui에서 api 실행




유저 추가

internal_users.yml 파일을 열어 해당 텍스트 추가

testuser:

  hash: "$2VKsMNflmcL0zF84pdyc0dsdf$sdfsdf$sdfsdf"

  reserved: false

  hidden: false

  backend_roles:

  - "admin"

  description: "test user"


"hash" 값은 일반 텍스트 패스워드를 hash로 변경한 값 넣는다. 

sudo /usr/share/elasticsearch/plugins/opendistro_security/tools/hash.sh -p mypwd


변경 사항을 securityadmin.sh 스크립트를 통해 kibana의 security plugin에 적용한다.

sudo /usr/share/elasticsearch/plugins/opendistro_security/tools/securityadmin.sh \

-cacert /etc/elasticsearch/root-ca.pem \

-cert /etc/elasticsearch/kirk.pem \

-key /etc/elasticsearch/kirk-key.pem \

-cd /usr/share/elasticsearch/plugins/opendistro_security/securityconfig/


새로 추가된 계정으로 로그인 확인



curl api 참조 :

https://opendistro.github.io/for-elasticsearch-docs/docs/security/access-control/api/


security 관련 설정 yml파일 참조 :

https://opendistro.github.io/for-elasticsearch-docs/docs/security/configuration/yaml/#internal_usersyml


securityadmin.sh 옵션 참조 : 

https://opendistro.github.io/for-elasticsearch-docs/docs/security/configuration/security-admin/ 

2021년 12월 15일 수요일

[ Elasticsearch ] Opendistro 와 Kibana 설치

Elasticsearch의 무료버전인 Opendistro 설치과정


[ opendistro 설치 ]

가이드를 보고 설치한다.

https://opendistro.github.io/for-elasticsearch-docs/docs/install/


single node 설정

elasticsearch.yml 수정

# 네크워크 접근 대역설정

network.host: 0.0.0.0

# 싱글노드 타입

discovery.type: single-node

# 주석으로 막혀져 있어야한다

# cluster.initial_master_nodes: ["node-1", "node-2"]


추가 설정 (optional)

기본 config 파일은 etc/elasticsearch/elasticsearch.yml 파일이다.

bootstrap.memory_lock: true 주석을 풀어준다.

jvm에서 elasticsearch가 사용하는 메모리를 고정한다. 설치된 서버의 시스템에

너무 많은 메모리를 차지하지 않도록 전체 시스템 메모리의 50%가 넘지 않도록 한다.


jvm관련 설정 파일은 /etc/elasticsearch/jvm.options 파일이다.

elasticsearch 사용량에 따라 java heap size 설정을 바꿀 수 있다.

initial size와 maximum size는 같게 설정한다.

Ex] -Xms4g




[ kibana 설치 ]

똑같이 가이드를 따라 설치한다.

https://opendistro.github.io/for-elasticsearch-docs/docs/kibana/

기본 config 파일은 etc/kibana/kibana.yml에 있다.

해당 파일에

server.port: 5601

server.host: "0.0.0.0"

을 추가한다.


http://yourhostip:5601 에 접속 후 kibana.yml에 default로 설정된 계정정보로

로그인을 하면 kibana ui를 사용할 수 있다.


2021년 12월 9일 목요일

[ Shell Script ] Mulit AWS Instance 생성 후 코드 실행


[ 시나리오 ]

Master EC2에서 Shell Script로 
10개의 EC2를 생성해 S3를 이용한 'A' 라는 작업을 실행. 
작업실행 후 10개의 EC2 종료




[ 실행예제 ]

1. EC2 생성

2. S3를 가져와 A작업을 하는 _run.sh 코드작성
#!/bin/bash

if [ $# -ne 2 ]; then
 echo "Usage: $0 yyyyMMdd filename"
 exit -1
fi

DATE=$1
FILE=$2

AWS_REGION=s3.ap-northeast-2.amazonaws.com
AWS_ACCESS_KEY_ID=AKAKAKAAKAAAAA
AWS_SECRET_ACCESS_KEY=080sdfsdf(((D0sdf/3333

S3_INPUT_PATH="s3://bucket/input/${DATE}/${FILE}"
S3_OUTPUT_PATH="s3://bucket/input/${DATE}/"
LOCAL_INPUT_PATH="./data/input"
LOCAL_OUTPUT_PATH="./data/output"

echo "[INFO] CP INPUT From S3 To Local"
aws s3 cp ${S3_INPUT_PATH} "${LOCAL_INPUT_PATH}/"

echo "[INFO] Run A process"

...
A작업 실행코드
...

echo "[INFO] CP OUTPUT From Local To S3"
aws s3 cp "${LOCAL_OUTPUT_PATH}/output_${FILE}.csv" ${S3_OUTPUT_PATH}

echo "[INFO] FINISH JOB & SHUTDOWN"
shutdown

3. AMI 이미지 생성 후 EC2 종료

4. Master EC2가 Aws환경설정이 안되어있다면
#!/bin/sh

# curl을 사용하여 aws cli 패키지다운로드
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip

# 설치 진행
sudo ./aws/install -i /usr/local/aws-cli -b /usr/local/bin

# 버전확인
aws --version

5. Master EC2에서 run_instance.sh 코드 작성
#!/bin/sh

# 변수값 정의
DATE=$1
IMAGE_ID=ami-00000000id
INSTANCE_TYPE=t3.small
SUBNET_ID=subnet-77777aa
SECURITY_GROUP_ID=sg-0ffffffff00000
KEY_NAME=your_aws_key
AWS_ACCESS_KEY_ID=AKAKAKAKAKAKAKAAK
AWS_SECRET_ACCESS_KEY=88OOOO888OOOOO

START_NUMBER="00000"
FINISH_NUMBER="00009"
    
/usr/local/bin/aws configure set aws_access_key_id "$AWS_ACCESS_KEY_ID"
/usr/local/bin/aws configure set aws_secret_access_key "$AWS_SECRET_ACCESS_KEY"
/usr/local/bin/aws configure set default.region "ap-northeast-2"
run_instance(){
    S3_FILE=part-$1
    /usr/local/bin/aws ec2 run-instances --image-id ${IMAGE_ID}  --count 1 --instance-type ${INSTANCE_TYPE} \
    --subnet-id ${SUBNET_ID} --security-group-ids ${SECURITY_GROUP_ID} --instance-initiated-shutdown-behavior terminate \
    --key-name ${KEY_NAME} --user-data \
    "
    #!/bin/bash
    cd /home/centos/exec
    sh _run.sh ${DATE} ${S3_FILE}
    " > /dev/null
}

echo "[INFO] START JOB : ${DATE}"
for CURR_NUMBER in $(seq -f "%05g" $START_NUMBER $FINISH_NUMBER) 
    do
        run_instance ${CURR_NUMBER}
    done
fi
    
echo "[INFO] FINISH JOB"
exit 0


5. run_instance.sh 실행 후, EC2 10개가 생겼다가 _run.sh실행 후 종료, S3적제