Ansible dynamic inventory - AWS EC2

Ansible aws_ec2 plugin 활용, AWS EC2 동적 Inventory 구성 Ansible plugin : aws_ec2 https://docs.ansible.com/ansible/2.9/plugins/inventory/aws_ec2.html{:target="_blank"} Get inventory hosts from Amazon Web Services EC2 Requirements python package : boto3, bo YAML 설정 파일 이름이 aws_ec2.(yml|yaml) 로 끝나야 함 $ ansible --version ansible 2.9.6 config file = /etc/ansible/ansible.cfg configured module search path = ['/home/cdecl/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /usr/lib/python3/dist-packages/ansible executable location = /usr/bin/ansible python version = 3.8.10 (default, Jun 2 2021, 10:49:15) [GCC 9.4.0] # install boto3, bo $ pip3 install boto3 기본설정 aws_ec2.yaml plugin : 프러그인 이름, 필수 regions : 지정하면 더 빠른 조회 plugin: aws_ec2 regions: - ap-northeast-2 # .aws/credendial 파일이 없으면 aws_access_key_id: AKIA3************** aws_secret_access_key: 1oxRajyBX********************** ~/.aws/credentials [default] aws_access_key_id = AKIA3************** aws_secret_access_key = 1oxRajyBX********************** Inventory 확인 기본 aws_ec2 그룹으로 생성 # json 형태로 ec2 node 정보 및 group 정보 리스트 $ ansible-inventory -i aws_ec2.yaml --list ... "all": { "children": [ "aws_ec2", "ungrouped" ] }, "aws_ec2": { "hosts": [ "ip-10-211-20-159.ap-northeast-2.compute.internal", "ip-10-211-20-229.ap-northeast-2.compute.internal", "ip-10-211-20-45.ap-northeast-2.compute.internal" ] } } # inventory 정보를 그래프 형태로 표시 $ ansible-inventory -i aws_ec2.yaml --graph @all: |--@aws_ec2: | |--ip-10-211-20-159.ap-northeast-2.compute.internal | |--ip-10-211-20-229.ap-northeast-2.compute.internal | |--ip-10-211-20-45.ap-northeast-2.compute.inte # ansible 명령으로 확인 $ ansible -i aws_ec2.yaml --list-hosts all hosts (3): ip-10-211-20-229.ap-northeast-2.compute.internal ip-10-211-20-159.ap-northeast-2.compute.internal ip-10-211-20-45.ap-northeast-2.compute.internal 필터 및 그룹화 예제 : https://docs.ansible.com/ansible/2.9/plugins/inventory/aws_ec2.html#examples{:target="_blank"} filters : 필터로 원하는 항목만 가져옴 AWS CLI 명령 describe-instances –filters 항목 참고 https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html#options{:target="_blank"} keyed_groups : Inventory 그룹화 항목 plugin: aws_ec2 regions: - ap-northeast-2 filters: # tag 정보가 AutoDelete:False 인 인스턴스 tag:AutoDelete: "False" # running 상태 인스턴스 instance-state-name: 'running' keyed_groups: # tag 를 기준으로 그룹화, "prefix_key_value" 형식의 그룹이름 - prefix: tag key: tags # tag 로 그룹화 $ ansible-inventory -i aws_ec2.yaml --graph @all: |--@aws_ec2: | |--ip-10-211-20-159.ap-northeast-2.compute.internal | |--ip-10-211-20-229.ap-northeast-2.compute.internal | |--ip-10-211-20-45.ap-northeast-2.compute.internal |--@tag_AutoDelete_False: | |--ip-10-211-20-159.ap-northeast-2.compute.internal | |--ip-10-211-20-229.ap-northeast-2.compute.internal | |--ip-10-211-20-45.ap-northeast-2.compute.internal ... |--@tag_Name_kube01: | |--ip-10-211-20-45.ap-northeast-2.compute.internal |--@tag_Name_kube02: | |--ip-10-211-20-159.ap-northeast-2.compute.internal |--@tag_Name_kube03: | |--ip-10-211-20-229.ap-northeast-2.compute.internal |--@ungrouped: # ansible 명령으로 확인 $ ansible -i aws_ec2.yaml tag_AutoDelete_False --list-hosts hosts (3): ip-10-211-20-229.ap-northeast-2.compute.internal ip-10-211-20-159.ap-northeast-2.compute.internal ip-10-211-20-45.ap-northeast-2.compute.internal $ ansible -i aws_ec2.yaml tag_Name_kube01 --list-hosts hosts (1): ip-10-211-20-45.ap-northeast-2.compute.internal Host 연결을 위한 inventory parameters 추가 multiple inventory로 정보 추가 https://docs.ansible.com/ansible/2.9/user_guide/intro_inventory.html#connecting-to-hosts-behavioral-inventory-parameters{:target="_blank"} # aws.host [win:children] tag_AutoDelete_False [win:vars] ansible_user=rundeck ansible_password=<passowrd> ansible_connection=winrm ansible_port=5985 $ ansible-inventory -i aws_ec2.yaml -i aws.host --vars --list { "_meta": { "hostvars": { "ip-10-211-20-159.ap-northeast-2.compute.internal": { "ami_launch_index": 1, "ansible_connection": "winrm", "ansible_password": "<passowrd>", "ansible_port": 5985, "ansible_user": "ansible", "architecture": "x86_64", ... ansible-inventory --list 옵션으로 hosts 파일 형식 구성 $ ansible-inventory -i aws_ec2.yaml --list | jq -r '._meta.hostvars[] | "\(.private_ip_address) \(.tags.Name) "' 10.211.20.159 kube02 10.211.20.229 kube03 10.211.20.45 kube01 Ansible EC2 Dynamic inventory minimum IAM policies https://stackoverflow.com/questions/30519470/ansible-ec2-dynamic-inventory-minimum-iam-policies{:target="_blank"} { "Version": "2012-10-17", "Statement": [ { "Sid": "Demo201505282045", "Effect": "Allow", "Action": [ "ec2:Describe*", "route53:ListHostedZones", "route53:ListResourceRecordSets" ], "Resource": "*" } ] }

July 16, 2022 · Byung Kyu KIM

Multipass, Ubuntu VM 설정

Canonical 재단에서 지원하는 단일 명령으로 Ubuntu VM 구성 할 수 있는 도구 Multipass https://multipass.run/{:target="_blank"} 최소한의 오버헤드를 위한 각 플랫폼 지원 Windows : Hyper-V macOS : QEMU, HyperKit Linux : LXD Multipass install https://multipass.run/install{:target="_blank"} 플랫폼 별 패키지 설치 방법 # windows $ choco install multipass # macOS $ brew install multipass Multipass 주요 명령 및 VM Instance 생성 주요 명령어 launch : Ubuntu instance 생성 및 시작 start, stop, restart : 시작 중지 delete : Ubuntu instance 삭제 purge : 삭제된 이미지 영구 삭제 shell : Instance 내부 shell 로 접속 list : 생성된 Instance 확인 info : Instance 정보 확인 $ multipass --help ... Available commands: alias Create an alias aliases List available aliases authenticate Authenticate client delete Delete instances exec Run a command on an instance find Display available images to create instances from get Get a configuration setting help Display help about a command info Display information about instances launch Create and start an Ubuntu instance list List all available instances mount Mount a local directory in the instance networks List available network interfaces purge Purge all deleted instances permanently recover Recover deleted instances restart Restart instances set Set a configuration setting shell Open a shell on a running instance start Start instances stop Stop running instances suspend Suspend running instances transfer Transfer files between the host and instances umount Unmount a directory from an instance unalias Remove an alias version Show version details Ubuntu VM Instance 생성 : 기본 생성 # node1 이름의 instance 생성 $ multipass launch -n node01 Launched: node01 # 기본 lts 이미지로 생성 : Ubuntu 20.04 LTS $ multipass list Name State IPv4 Image node01 Running 192.168.196.207 Ubuntu 20.04 LTS # instace 정보 $ multipass info node01 Name: node01 State: Running IPv4: 192.168.196.207 Release: Ubuntu 20.04.4 LTS Image hash: 75a04c7eed58 (Ubuntu 20.04 LTS) Load: 0.38 0.15 0.05 Disk usage: 1.4G out of 4.7G Memory usage: 162.4M out of 912.5M Mounts: -- 기본 설정으로 Instance 생성시, Disk 등의 리소스가 부족 할 수 있음 ...

July 4, 2022 · Byung Kyu KIM

Neovim, vim-plug 설정

Neovim 설치 및 vim-plug 설정으로 개발, 운영 환경 구성 Neovim https://github.com/neovim/neovim{:target="_blank"} Vim-fork focused on extensibility and usability Neovim install 플랫폼 별 패키지 설치 방법 # macos $ brew install nvim # windows $ choco install neovim # linux (ubuntu) $ sudo apt install neovim # linux (centos) $ sudo yum install neovim vim-plug install Neovim 에 Plugin 지원을 위한 확장 툴 : vim 도 지원 https://github.com/junegunn/vim-plug{:target="_blank"} vim의 Vumdle과 같은 Minimalist Vim Plugin Manager ...

June 27, 2022 · Byung Kyu KIM

Traefik Proxy

Docker 기반 서비스 자동 감지 및 요청을 처리하는 Reverse proxy Traefik Proxy https://doc.traefik.io/traefik/{:target="_blank"} docker.sock 을 통해 Rule 기반 서비스를 찾고 요청을 처리함 Docker 이외에 Kubernetes, Docker Swarm, AWS, Mesos, Marathon 등을 지원 Quick Start https://doc.traefik.io/traefik/getting-started/quick-start/{:target="_blank"} docker-compose.yml reverse-proxy : traefik reverse proxy 서비스 Docker Out of Docker (DooD) 같은 형태로 서비스 감지 서비스와 같은 Docker network 내에 있어야 호출이 가능 whoami : Client 호출정보를 보여주는 간단한 서비스 labels 을 통해 whoami 서비스 Rule 등록 Host 기반 Rule 적용 : "traefik.http.routers.whoami.rule=Host(whoami.localhost)" traefik.http.routers.<router_name>.rule= Docker Routers 규칙{:target="_blank"} Rule 종류{:target="_blank"} 서비스에 Port 가 노출 되어야 함 : Expose port (or Publish port) version: '3' services: reverse-proxy: # The official v2 Traefik docker image image: traefik:v2.6 # Enables the web UI and tells Traefik to listen to docker command: --api.insecure=true --providers.docker ports: # The HTTP port - "80:80" # The Web UI (enabled by --api.insecure=true) - "8080:8080" volumes: # So that Traefik can listen to the Docker events - /var/run/docker.sock:/var/run/docker.sock whoami: # A container that exposes an API to show its IP address image: traefik/whoami labels: - "traefik.http.routers.whoami.rule=Host(`whoami.localhost`)" # reverse-proxy 서비스 시작 $ docker-compose up -d reverse-proxy # whoami 서비스 시작 $ docker-compose up -d whoami $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e457ff5e01cb traefik/whoami "/whoami" 59 minutes ago Up 59 minutes 80/tcp traefik_whoami_1 Dashboard Router 확인 ...

March 5, 2022 · Byung Kyu KIM

Git Repository 복제, Branch 동기화 관리

Git Repository 복제 및 Branch 관리 가이드 Git Repository 복제 Remote → Local 복제 Git 저장소를 복제하는 방법에는 여러 가지가 있으며, 각각의 방식에 따라 다른 특징이 있습니다. --mirror 복제의 특징 git clone --mirror: Remote repository의 모든 참조(refs)를 포함하여 Local에 저장 기본 clone과 달리 작업 디렉토리 없이 저장소의 메타데이터 전체를 복제 주로 저장소 백업이나 완전한 미러링에 사용 # mirror 복제 $ git clone --mirror https://github.com/cdecl/test $ tree -d . └── test.git ├── branches ├── hooks ├── info ├── objects │ ├── info │ └── pack └── refs ├── heads └── tags 💡 추가 정보: ...

February 23, 2022 · Byung Kyu KIM

ReaR (Relax & Recover) Basic

ReaR(Relax & Recover), Linux 재해 복구 도구 ReaR https://relax-and-recover.org/{:target="_blank"} Manual Page : https://github.com/rear/rear/blob/master/doc/rear.8.adoc{:target="_blank"} OS의 부팅 가능한 복구 시스템 구성, 시스템 파일 백업 및 복구 지원 Simple Example NFS 백업 서버 구성 ReaR 백업 및 복구 테스트 centos7, Hyper-v 환경 테스트 https://access.redhat.com/solutions/2115051{:target="_blank"} Backup용 NFS 서버 구성 백업서버 NFS 구성 # nfs-utils 설치 $ sudo yum install nfs-utils # 디렉토리 생성 $ sudo mkdir -p /storage/rear # nfs 서버 설정 $ cat /etc/exports /storage *(rw,sync,no_root_squash) # nfs-server start # sudo systemctl enable nfs-server $ sudo systemctl start nfs-server 대상 서버 구성 RaaR 설치 및 구성 # nfs clients $ sudo yum install nfs-utils # ReaR 설치 sudo yum install nfs-utils # 필요에 따라 아래 모듈 설치 # rear -d -v mkbackup 시 해당 모듈이 없다고 나오면 # WARNING: /usr/lib/grub/x86_64-efi/moddep.lst not found, grub2-mkimage will likely fail. # Please install the grub2-efi-x64-modules package to fix this. $ sudo yum install grub2-efi-x64-modules RaaR 설정 https://github.com/rear/rear/blob/master/doc/user-guide/03-configuration.adoc{:target="_blank"} /etc/rear/local.conf OUTPUT : Rescue media, BOOT용 이미지 ISO : ISO BOOT 이미지 생성 BACKUP, BACKUP_URL : Backup/Restore strategy, 시스템파일 및 백업 데이터 종류 및 위치 지정 NETFS : Use Relax-and-Recover internal backup with tar or rsync (or similar) BACKUP_URL 경로 및 HostName 폴더에 생성 BACKUP_PROG_EXCLUDE : 백업 제외 경로 지정 # /etc/rear/local.conf OUTPUT=ISO OUTPUT_URL=nfs://192.168.137.100/storage/rear BACKUP=NETFS BACKUP_URL=nfs://192.168.137.100/storage/rear # BACKUP_TYPE=incremental # FULLBACKUPDAY=Sun # BACKUP_PROG_EXCLUDE=('/syslogs/logs/*' '/var/log/*') Backup 실행 mkbackup : create rescue media and backup system mkbackuponly : backup system without creating rescue media mkrescue : create rescue media only ## verbose mode # -d : debug mode 의 경우 /tmp 밑에 파일을 지우지 않음 $ sudo rear -v mkbackup Backup 데이터 확인 # Backup 서버 $ hostname -I 192.168.137.100 # hostname 디렉토리별로 백업 $ tree /storage /storage └── rear ├── node1 │ ├── README │ ├── VERSION │ ├── backup.log │ ├── backup.tar.gz │ ├── rear-node1.iso │ └── rear-node1.log └── node2 ├── README ├── VERSION ├── backup.log ├── backup.tar.gz ├── rear-node2.iso └── rear-node2.log 복구 실행 백업된 rescue media (iso)로 부팅을 한 후, 복구 모드로 실행 ...

February 7, 2022 · Byung Kyu KIM

Kustomize Basic

kubernetes manifest 리소스 관리 도구 Kustomize https://kubernetes.io/ko/docs/tasks/manage-kubernetes-objects/kustomization/{:target="_blank"} kubernetes manifest (yaml) 파일을 Template 형태로 관리 Patch(Merge) 및 배포 해주는 툴 kubernetes 1.14 이후, kubectl 명령어로 kustomization 지원 Simple Example $ tree . . ├── deployment.yaml ├── kustomization.yaml └── version.yaml kustomization.yaml Manifest 파일의 기본 구조 및 리소스, 패치 파일을 기술하는 파일 resources: - deployment.yaml patchesStrategicMerge: - version.yaml resources : 리소스 파일 리스트 resources 이외에 configMapGenerator, secretGenerator 기능도 있음 https://kubernetes.io/ko/docs/tasks/manage-kubernetes-objects/kustomization/#kustomize-%EA%B8%B0%EB%8A%A5-%EB%A6%AC%EC%8A%A4%ED%8A%B8{:target="_blank"} patchesStrategicMerge : resources의 Patch 파일 Patch : yaml file merge ...

December 15, 2021 · Byung Kyu KIM

C++ Lambda 표현식

C++14, C++17, C++20 버전별 Lambda 표현 정리 The Evolutions of Lambdas in C++14, C++17 and C++20 https://www.fluentcpp.com/2021/12/13/the-evolutions-of-lambdas-in-c14-c17-and-c20/{:target="_blank"} 해당 글을 참고하여 예제 자체 작성 C++14 Default parameters #include <iostream> using namespace std; int main() { auto fn = [](int a, int b = 0) { return a + b; }; cout << fn(1) << endl; // 1 cout << fn(1, 2) << endl; // 3 } Template parameters #include <iostream> #include <string> #include <vector> using namespace std; int main() { auto fn = [](auto && c) { return c.size(); }; vector<int> v = {1, 2, 3}; cout << fn(v) << endl; // 3 string s = "12345"; cout << fn(s) << endl; // 5 } Generalised capture #include <iostream> #include <string> using namespace std; int main() { string str = "string"; auto fn = [s = str + "_capture"s](string body) { cout << s << " : " << body << endl; }; fn("test"); // string_capture : test } Returning a lambda from a function #include <iostream> using namespace std; auto getAdd(int n) { return [n](int an) { return n + an; }; } int main() { auto fn = getAdd(10); cout << fn(20) << endl; } C++17 Constexpr #include <iostream> using namespace std; int main() { constexpr auto fn = [](int n){ return n + 10; }; static_assert(fn(10) == 20); // ok static_assert(fn(20) == 20); // error: static assertion failed } Capturing a copy of *this this 참조에 캡쳐가 아닌, *this 복사본 캡쳐 #include <iostream> #include <memory> #include <tuple> using namespace std; class item { public: item(int n = 0) : _value(n) {} auto test() { _value += 1; // copy capture auto fn1 = [*this] { return _value; }; auto fn2 = [self = *this] { return self._value; }; // ref capture auto fn3 = [this] { return _value; }; _value += 1; fn1(); // 11 fn2(); // 11 fn3(); // 12 return make_tuple(fn1, fn2, fn3); } private: int _value; }; int main() { auto it = make_shared<item>(10); auto tp = it->test(); it.reset(); cout << get<0>(tp)() << endl; cout << get<1>(tp)() << endl; cout << get<2>(tp)() << endl; // ref memory error } C++20 Template syntax for lambdas #include <iostream> #include <vector> using namespace std; int main() { auto fn = []<typename T>(vector<T> &v) { return v.size(); }; vector<int> v = {1, 2, 3, 4, 5}; cout << fn(v) << endl; } Lambda capture of parameter pack #include <iostream> #include <string> using namespace std; template <typename... Args> auto getAddFunc(Args&&... args){ // by ref [&...args = std::forward<Args>(args)] // by value return [...args = std::forward<Args>(args)] (auto && init) { return init + (args + ...); }; } int main() { auto fn = getAddFunc(1, 2, 3); cout << fn(10) << endl; // 16 auto fns = getAddFunc("this "s, "is "s, "sample"s); cout << fns("note: "s) << endl; // note: this is sample }

December 14, 2021 · Byung Kyu KIM

MinIO Windows Service 등록

MinIO Windows Service 등록 MinIO Service 등록 WinSW https://github.com/winsw/winsw{:target="_blank"} Windows 실행 파일을 서비스로 래핑해주는 툴 .NET Framework / Core 기반 Windows 플랫폼에서 실행 MinIO Service https://github.com/minio/minio-service/tree/master/windows{:target="_blank"} WinSW 최신 Release 다운로드 및 XML 설정 파일 작성 # choco install curl # 다운로드 $ curl -LO https://github.com/winsw/winsw/releases/download/v2.11.0/WinSW-x64.exe # rename $ move WinSW-x64.exe minio-service.exe minio-service.xml <service> <id>MinIO</id> <name>MinIO</name> <description>MinIO is a high performance object storage server</description> <executable>minio.exe</executable> <env name="MINIO_ROOT_USER" value="minio"/> <env name="MINIO_ROOT_PASSWORD" value="minio1234"/> <arguments>server d:\minio\data --console-address ":9001"</arguments> <logmode>rotate</logmode> </service> 서비스 등록 Administrator 권한으로 실행 minio 실행 파일 PATH 등록 or 같은 디렉토리에 위치 # service install $ minio-service.exe install 2021-12-09 15:57:24,987 INFO - Installing service 'MinIO (MinIO)'... 2021-12-09 15:57:25,085 INFO - Service 'MinIO (MinIO)' was installed successfully. # service status $ minio-service.exe status Stopped # service start $ minio-service.exe start 2021-12-09 16:05:59,133 INFO - Starting service 'MinIO (MinIO)'... 2021-12-09 16:06:00,322 INFO - Service 'MinIO (MinIO)' started successfully.

December 10, 2021 · Byung Kyu KIM

Rclone Basic

Go 언어로 만든 크로스 플랫폼 클라우드 스토리지 특화 백업 및 동기화 프로그램 Rclone https://rclone.org/{:target="_blank"} file, sftp 부터 Amazon S3, MinIO 와 같은 Object Storage, Cloud Storage 등의 많은 Providers 를 지원 Install 플랫폼 바이너리 다운로드 or 패키지 매니저 활용 https://rclone.org/downloads/{:target="_blank"} Rclone config Providers 설정 기반, config 파일을 통해 설정 Rclone config 기본 파일 위치 확인 # linux config 파일 위치 확인 $ rclone config file Configuration file is stored at: /home/<HOME>/.config/rclone/rclone.conf # windows $ rclone config file Configuration file is stored at: C:\Users\<HOME>\AppData\Roaming\rclone\rclone.conf Rclone config 추가 config 파일을 직접 수정 하거나 Interactive 화면을 통해 진행 $ rclone config No remotes found - make a new one n) New remote s) Set configuration password q) Quit config n/s/q> ... Rclone config 내용 확인 $ rclone config show Rclone Provider config Amazon S3 [mys3] type = s3 provider = AWS env_auth = true region = ap-northeast-2 location_constraint = ap-northeast-2 [mys3] type = s3 provider = AWS env_auth = true region = ap-northeast-2 location_constraint = ap-northeast-2 access_key_id = AKIAXXXXXXXXXXXXXXXX secret_access_key = 1oxxxxxxxxxxxxxxxxxxxxxxxxx MinIO [myminio] type = s3 provider = Minio env_auth = false access_key_id = KEYxxxxxxxxx secret_access_key = PWDxxxxxxxxx endpoint = http://minio-server SFTP 공개키 인증을 위해 key_file 지정하지 않으면 ssh_agent를 통해 접근시도 ...

December 9, 2021 · Byung Kyu KIM