AWS EC2 / RDS 의 인스턴스 정보를 조회하는 boto3 코드

  • 태그값을 지정하여 원하는 태그를 추출 가능

 

import json
import boto3

def lambda_handler(event, context):
    # TODO implement
    ec2_asset()
    rds_asset()


######EC2#####################################################
def ec2_asset():
    ec2 = boto3.client('ec2')   
    #ec2_info = []
    
    describe_ec2_instance = ec2.describe_instances()
    print("################EC2 Instance Info####################")
    for reservation in describe_ec2_instance['Reservations']:
        for instance in reservation['Instances']:
            instance_id = instance['InstanceId']
            instance_type = instance['InstanceType']
            tagName = None
            tagComponent = None
            for instance_Tags in instance['Tags']:
                               
                if instance_Tags['Key'] == 'Name':
                    tagName = instance_Tags['Value']
                    
                
                if instance_Tags['Key'] == 'Component':
                    tagComponent = instance_Tags['Value']
            print(instance_id,"\t", instance_type,"\t", tagName,"\t", tagComponent)    

                

######RDS#####################################################
def rds_asset():
    rds = boto3.client('rds')
    print("################RDS Instance Info####################")
    describe_rds_instance = rds.describe_db_instances()
    for dbInstances in describe_rds_instance['DBInstances']:
        for instance in dbInstances['DBInstanceIdentifier']:
            instance_zone = dbInstances['AvailabilityZone']
            instance_type = dbInstances['DBInstanceClass']            
            instance_endpoint = dbInstances['Endpoint']['Address']
            instance_engine = dbInstances['Engine']
            instance_enginevesion = dbInstances['EngineVersion']
            
            tagName = None
            tagComponent = None
            for instance_Tags in dbInstances['TagList']:
                if instance_Tags['Key'] == 'Name':
                    tagName = instance_Tags['Value']
                if instance_Tags['Key'] == 'Component':
                    tagComponent = instance_Tags['Value']

        print(tagName ,"\t",tagComponent,"\t", instance_type,"\t", instance_zone, "\t",instance_engine,"\t",instance_enginevesion,"\t",instance_endpoint)

 

 

'AWS' 카테고리의 다른 글

AWS EC2 종료 Lambda with EventBridge  (0) 2023.11.28
AWS EKS LB Controller Install  (0) 2023.09.29
Route53 라우팅 정책  (0) 2023.08.05
AWS Route53 DNA Type  (0) 2023.07.22
AWS Gateway Endpoint  (0) 2023.07.21

Grafana를 사용 중 Grafana에 설정이 점점 많아져서 DB를 RDS로 옮겨야 할 필요성을 느꼈다.


Grafana는 grafana.ini 에 [database] 설정을 하지 않았을 경우 기본 DB 인 sqlite3을 사용하게 된다

데이터가 적을 때는 상관 없지만 많은 데이터소스, 대시보드, 알람등이 설정되다 보니 쿼리 속도가 늦어지고 pod restart 가 자주 발생 하게 되었다. pod의 cpu/ memory를 확인해 봤지만 설정해 놓은 limit까지 사용되지 않았고, DB 문제인 것으로 보여 AWS RDS mysql로 이관하기로 결졍 하였다.


준비사항 : sqlite3, mysql, RDS mysql - grafana database


개념 설명 : Grafana 에 Database를 설정하지 않으면 위에서 설명한 것과 같이 sqlite3을 사용하게 되고, /var/lib/grafana/grafana.db 안에 내용이 저장 되게 된다

  • Grafana 생성시 k8s pvc를 생성했으면 pvc 볼륨 안에 데이터가 저장된다(path는 동일)

grafana db

 


Migration Flow

  1. k8s grafana pod 안의 grafana.db 를 작업하기 편한 곳으로 이동
  2. mysql / sqlite3 명령어 설치
  3. git clone or shell script 복사
  4. grafana.db 덤프 생성
  5. RDS mysql 에 grafana DB 사용을 위한 초기 설정
  6. grafana pod 의 database를 RDS mysql과 연결
  7. 생성한 grafana 덤프를 RDS mysql 에 inport
  8. 결과 확인

상세 작업 설명

 

1. grafana.db 를 작업하기 편한 곳으로 이동

  • 필자의 경우 k8s 로 grafana를 사용 중이므로 k8s contrill vm에서 작업하였음
  • grafana pod의 db를 kubectl cp 명령어를 사용하여 VM으로 이동

2. mysql / sqlite3 설치

  • grafana.db 에서 덤프 생성을 위해서는 sqlite3 필요
  • RDS mysql에 import 하기 위해서는 mysql 명령어 필요
sudo apt-get install mysql-client
sudo apt-get install sqlite3

 

3. git clone or shell script 

  • grafana 덤프 생성을 위한 스크립트로 git에서 다운 / copy 가능
  • url : https://github.com/grafana/database-migrator
  • git clone을 해도 되고, 해당 git 안에 있는 sqlitedump.sh / escape.awk 만 복사해도 사용 가능
  • 생성 후 chmod 755로 실행 권한 부여
 

GitHub - grafana/database-migrator: Code to export grafana.db (sqlite) to MySQL-compatible SQL file, to assist in migration of G

Code to export grafana.db (sqlite) to MySQL-compatible SQL file, to assist in migration of Grafana data to MySQL-compatible DB. - GitHub - grafana/database-migrator: Code to export grafana.db (sqli...

github.com

4. grafana.db 덤프 생성

./sqlitedump.sh ./grafana.db > ./grafana.sql

★이 과정에서 에러가 발생하는 경우가 있는데 grafana.sql 이름을 변경해서 db_dumb.sql 등 다른 이름으로 시도 추천
무슨 차이인지는 모르겠으나 grafana.sql 로했을때 error 가 종종 발생함

5. RDS mysql에 grafana DB 사용을 위한 초기 설정

  • grafana 이름으로 database 생성
  • grafana database를 사용할 grafana 계정 생성
  • grafana 계정에 권한 부여

 

DB 접속 방법

mysql -u {username} -P {port} -h {endpoint/host 주소} -p

ex)
mysql -u abdc -P 3306 -h database001.ap-northeast-2.rds.amazonaws.com -p

 

접속 후 DB 설정

CREATE DATABASE grafana ;
CREATE USER 'grafana'@'%' IDENTIFIED BY 'grafana';
GRANT ALL PRIVILEGES ON grafana.* TO 'grafana'@'%';
FLUSH PRIVILEGES;

 

6. grafana pod의 database를 RDS mysql과 연결

  • grafana에서 RDS mysql - grafana database를 사용하기 위한 기본 틀을 잡는 과정
  • k8s comfigmap에서 grafana를 수정하면 됨

  • config 수정은 grafana pod를 삭제해야 적용되므로, grafana pod 삭제 후 log 확인
  • pod 가 정상적으로 running 되는지 확인 후 k logs {podname}으로 HTTP Listen까지 정상적으로 나왔는지 확인

 

7. 생성한 grafana 덤프를 RDS mysql에 import

  • mysql 명령어를 이용하여 생성해 놓았던 grafana.sql을 import 하면 됨

★ import 시 에러가 발생한다면 해당 에러메시지를 보고 구문을 수정하면 됨

★ grafana.sql 에서 몇 번째 줄에 syntax error인데 다른 줄과 비교해서 이상한 부분을 제거하고 다시 import 하면 됨

 

 

참고문서 : https://github.com/grafana/database-migrator

                 https://iceburn.medium.com/grafana-database-migration-from-sqlite3-to-mysql-301b6a01e249

 

Grafana — Database migration from Sqlite3 to MySQL

Shouldn’t it be Sqlite3?

iceburn.medium.com

 

GitHub - grafana/database-migrator: Code to export grafana.db (sqlite) to MySQL-compatible SQL file, to assist in migration of G

Code to export grafana.db (sqlite) to MySQL-compatible SQL file, to assist in migration of Grafana data to MySQL-compatible DB. - GitHub - grafana/database-migrator: Code to export grafana.db (sqli...

github.com

 

+ Recent posts