ArgoCD는 RBAC을 활용하여 사용자의 계정 및 권한을 설정한다.

 

공식 가이드 : https://argo-cd.readthedocs.io/en/stable/operator-manual/rbac/

 

RBAC Configuration - Argo CD - Declarative GitOps CD for Kubernetes

RBAC Configuration The RBAC feature enables restriction of access to Argo CD resources. Argo CD does not have its own user management system and has only one built-in user admin. The admin user is a superuser and it has unrestricted access to the system. R

argo-cd.readthedocs.io

 

Admin 권한을 가지는 admin 계정이 이미 존재하는 경우, 다른 권한을 가진 계정 생성 방법에 대해 알아보겠다.

 

현재 계정 목록 조회

먼저 현재 계정 목록을 조회 하기 위하여 아래와 같이 admin 계정으로 로그인한다.

$ argocd login <hostname> --username admin --grpc-web-root-path --password <admin-password>

계정 목록을 조회한다.

$ argocd account list

 

새로운 계정 추가

admin이 아닌 새로운 계정을 추가한다.

argocd 설치시 함께 설치되는 configmap 중 argocd-cm 에서 추가할 수 있다.

현재의 argocd-cm configmap 설정을 아래와 같이 yaml 형태로 저장한다.

$ kubectl get configmap argocd-cm -n argocd -o yaml > argocd-cm.yml

저장한 argocd-cm configmap 에 신규 계정을 추가한다.

data:
  accounts.<new-username>: apiKey, login

신규 계정 추가 후 변경된 configmap을 클러스터에 반영한다.

$ kubectl apply -f argocd-cm.yml

추가된 user의 비밀번호를 변경한다. 이때, current-password로 앞에서 로그인 하였던 admin password를 입력한다.

$ argocd account update-password --account <new-username> --current-password <admin-password> --new-password <new-password> --grpc-web

추가된 계정을 확인한다.

$ argocd account list

 

계정의 권한 변경

신규 추가되는 계정은 기본적으로 read-only 권한을 가지게 된다.

argocd에서는 제공하는 정책이 있는데, admin과 read-only 정책이다.

좀더 세부화된 권한을 설정해보겠다.

configmap중 argocd-rbac에서 권한 설정이 가능하다. 아래와 같이 argocd-rbac.yml 파일을 저장한다.

$ kubectl get configmap argocd-rbac-cm -n argocd -o yaml > argocd-rbac.yml

 

적용하려는 권한(role)과 정책(poilicy)을 추가한다.

data:
  policy.csv: |
    p, role:app-admin, applications, *, */*, allow
    p, role:app-admin, clusters, get, *, allow
    p, role:app-admin, repositories, get, *, allow
    g, <new-user>, role:app-admin
  policy.default: role:''
  • app-admin이라는 role에 application의 모든 권한을 모든 project에 대해 부여한다.
  • app-admin이라는 role에  cluster의 get 권한을 모든 클러스터에 대해 부여한다.
  • app-admin이라는 role에 repository의 get 권한을 모든 repository에 대해 부여한다.
  • g, <new-user>, role:app-admin → <new-user>에 app-admin 권한을 적용한다.
  • policy.default: role:' ' :  default 권한인 read-only 를 적용하지 않는다.

변경된 rbac을 적용한다.

$ kubectl apply -f argcd-rbac.yml

 

적용가능한 권한(builtin-policy)은 아래 링크에서 확인 가능하다.

https://github.com/argoproj/argo-cd/blob/master/assets/builtin-policy.csv

'cloudnative' 카테고리의 다른 글

Terraform 기본  (0) 2023.01.03

prometheus agent를 사용하려면, 수집하려는 클러스터에 각각 prometheus를 agent 모드로 설치하고

별도의 클러스터에 prometheus 를 server 모드로 설치한다.

이때 grafana 도 함께 설치하여 수집한 지표를 대시보드로 구성하여 모니터링 한다.

이 예제는 AWS EKS 기반으로 작성하였다.

 

먼저 promethues server와 grafana를 설치한다.

1. promethues server 설치

프로메테우스는 아래의 헬름차트 중 선택하여 구성할 수 있다.

- prometheus operator : https://github.com/prometheus-operator/prometheus-operator

  • operator 가 설정되어 있는 헬름차트
  • Kubernetes 사용자 지정 리소스 를 사용하여 Prometheus, Alertmanager 및 관련 모니터링 구성 요소의 배포 및 구성을 단순화

- kube-prometheus : https://github.com/prometheus-operator/kube-prometheus

  • Prometheus 및 Prometheus Operator를 기반으로 하는 전체 클러스터 모니터링 스택에 대한 예제 구성을 제공
  •  여러 Prometheus 및 Alertmanager 인스턴스의 배포, 노드 메트릭 수집을 위한 node_exporter와 같은 메트릭 내보내기, Prometheus를 다양한 메트릭 엔드포인트에 연결하는 스크랩 대상 구성, 클러스터의 잠재적인 문제 알림을 위한 예제 경고 규칙이 포함

- community helm chart : https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack

  • kube-prometheus와 유사한 기능 세트를 제공
  • Prometheus 커뮤니티에서 관리

community helm chart를 사용하여 prometheus 서버와 grafana를 구성한다.

#get helm ropository info
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

환경에 맞도록 value.yaml 파일을 작성한다.

https://github.com/prometheus-community/helm-charts/blob/main/charts/prometheus/values.yaml

파일을 참고하여 설정에 맞도록 value.yaml 을 작성한다.

 

SSL이 미적용된 AWS ALB를 사용하도록 설정하였다.

remote-write-receiver 를 활성화 하여 agent에서 접속할 수 있도록 한다.

server:
    ingress:
        enabled: true
        annotations:
            kubernetes.io/ingress.class: "alb"
            alb.ingress.kubernetes.io/load-balancer-name: #ALB name           
            alb.ingress.kubernetes.io/scheme: "internal"
            alb.ingress.kubernetes.io/target-type: "ip"
            alb.ingress.kubernetes.io/security-groups: #SecurityGroupId                        
            alb.ingress.kubernetes.io/success-codes: "200"
            alb.ingress.kubernetes.io/healthcheck-path: "/-/healthy"
        hosts:
            - #host name
    persistentVolume:
        enabled: true
        storageClass: "gp2"
    extraArgs:
        enable-feature: remote-write-receiver

alertmanager:
    enabled: false

value.yaml  작성 완료 후 헬름 차트를 설치한다.

helm install [RELEASE_NAME] prometheus-community/prometheus -f values.yaml

이때  [RELEASE_NAME]  은 적당한 이름으로 변경한다.

 

2. grafana 설치

그라파나 커뮤니티에서 관리하는 헬름차트로 그라파나를 설치한다.

helm repo add grafana https://grafana.github.io/helm-charts
helm repo update

마찬가지로 환경에 맞게 value.yaml 을 작성한다.

참고 : https://github.com/grafana/helm-charts/blob/main/charts/grafana/values.yaml

 

ingress로 SSL이 미적용된 ALB를 구성한다.

ingress:
    enabled: true
    annotations:
        kubernetes.io/ingress.class: "alb"
        alb.ingress.kubernetes.io/load-balancer-name: #ALB NAME 작성
        alb.ingress.kubernetes.io/scheme: "internet-facing"
        alb.ingress.kubernetes.io/target-type: "ip"
        alb.ingress.kubernetes.io/security-groups: #SercurityGroupId 작성         
        # alb.ingress.kubernetes.io/backend-protocol: HTTP
        alb.ingress.kubernetes.io/success-codes: "200"
        alb.ingress.kubernetes.io/healthcheck-path: "/api/health"
    hosts:
        - #Hostname 작성

persistence:
    enabled: true
    storageClassName: gp2

adminUser: #ADMIN USER NAME
adminPassword: #ADMIN PASSWORD

헬름차트를 설치한다.

helm install my-release grafana/grafana -f value.yaml

 

3. prometheus agent 설치(수집하기 위한 클러스터에 설치)

프로메테우스 서버와 마찬가지로 헬름차트를 먼저 구성한다.

#get helm ropository info
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

agent 설정에 맞게 value.yaml을 수정한다.

참고 : https://github.com/prometheus-community/helm-charts/blob/main/charts/prometheus/values.yaml

 

agent 모드 설정을 위해 --enable-feature=agent 설정과 prometheus.yml 파일의 rule_files 내용을 삭제한다.

remoteWrite의 url에 프로메테우스 서버 url을 작성하여 지표가 수집될 수 있도록 한다.

server:
  enabled: true
  defaultFlagsOverride:
  - --enable-feature=agent
  - --config.file=/etc/config/prometheus.yml
  configPath: /etc/config/prometheus.yml   
  persistentVolume:
    enabled: true
    storageClass: "gp2" 
  remoteWrite:
  - url: https://#prometehus_server_host/api/v1/write    

serverFiles:
  prometheus.yml:
    rule_files:

prometheus-pushgateway:
  enabled: false

alertmanager:
  enabled: false

grafana:
  enabled: false

defaultRules:
  create: false

작성한 value 파일로 헬름차트를 설치한다.

helm install [RELEASE_NAME] prometheus-community/prometheus -f values.yaml

 

4. Grafana 확인

모든 클러스터에 prometeus agent 설정 후 그라파나에 접속한다.

 

Configuration - Data Source에서 프로메테우스를 데이터 소스로 추가한다.

그라파나 대시보드 구성 참고 : https://aws-diary.tistory.com/121

모든 클러스터의 파드를 namespace 별로 하나의 대시보드에서 확인 가능하다.

 

 

prometheus agent의 HA 구성

prometheus agent의 고가용성(HA)를 확보하기 위하여 value.yaml을 아래와 같이 수정한다.

1대 이상의 POD를 띄우기 위해서는 deploy 대신 statefulset 을 사용하도록 되어 있다.

server:
 ...(중략)
  replicaCount: 2
  statefulSet:    
    enabled: true
 ...(중략)

구성 완료 후 적용해 보면 prometheus agent가 이전과는 달리 sts로 뜨고, 두대가 뜨는걸 확인할 수 있다.

prometheus server 를 사용할때 처럼 shard를 설정하거나 하지않아도 쉽게 HA 구성이 가능하다.

 

좀더 다양한 옵션을 보고 싶다면, 아래 operator 헬름차트를 참고하는게 좋을 것 같다.

https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/designs/prometheus-agent.md

 

'k8s' 카테고리의 다른 글

multi cluster환경 모니터링(prometheus, grafana)  (0) 2023.01.12
CKA 취득 후기 및 공부 방법  (0) 2023.01.03

kubernetes 운영을 하다보면 클러스터가 여러개인 환경을 운영하게 된다.

이러한 multi-cluster 환경에서 하나의 대시보드를 통해 모든 지표를 확인할 수 있는 방법은 여러가지가 있다.

 

prometheus에서 멀티 클러스터 모니터링을 지원하는 방법은 다음과 같다.

 

1. Prometheus federation

- https://prometheus.io/docs/prometheus/latest/federation/

- prometheus에서 도입한 첫번째 집계 기능이다.

- 각각의 서비스 클러스터에 prometheus(child)를 설치하고 /federate 엔드포인트에서 지표들을 수집/병합하기 위한 prometheus(parent)를 별도의 클러스터에 설치하여 지표를 수집한다.

- 수집해야 하는 자식 prometheus의 수가 증가하게 되면, 성능문제가 발생할 수 있으므로 주의하여 사용한다.

 

 

2. Thanos 

- https://thanos.io/

- 프로메테우스의 가용성, 확장성 등의 문제를 보완하기 위해 나온 오픈소스

- 특징

  • Global Query View : Prometheus Server 및 Cluster에서 Prometheus Metric Query를 활성화하여 Prometheus 설정을 확장
  • Unlimited Retention : 원하는 Scale이 가능한 Object Storage System을 통해 Metirc을 무제한으로 저장 가능
  • Prometheus Compatible(프로메테우스 호환) :  Prometheus와 거의 완벽하게 호환되는 API 제공
  • DownSampling & Compaction : Object Storage에 저장되어 있는 Data를 DownSampling하여 집계된 Data Query의 성능을 높이고, Data 압축/삭제를 통해 저장공간을 관리

 

그림 참고 :&nbsp;https://accordions.co.kr/it_trend/prometheus-%EB%B0%8F-thanos%EB%A1%9C-%EB%8C%80%EA%B7%9C%EB%AA%A8-%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C-%ED%99%98%EA%B2%BD-%EB%AA%A8%EB%8B%88%ED%84%B0%EB%A7%81/

- Thanos Sidecar : 서비스 클러스터에 thanos를 sidecar로 포함한 프로메테우스 서버 배포. query의 요청 처리

- Thanos Query : thanos sidecar와 연결하여 promQL을 처리. 메트릭을 쿼리하여 메트릭을 집계하고 중복을 제거함. 

- Thanos Ruler : Thanos에 의해 연동된 모든 프로메테우스의 룰을 정의하고 처리.

- Thanos Compactor : 수집된 데이터를 기준에 따라 장기 보관용 데이터로 변환

 

3. Prometheus Agent 모드(Prometheus Remote Write)

 

- Remote Write : Prometheus에서 수집한 모든 지표 또는 일부 지표를 원격 위치로 전달(스트리밍)

  • Cortex, Thanos, OpenTelemetry 및 Amazon, Google, Grafana, Logz.io 등과 같은 클라우드 서비스는 모두 원격 쓰기를 통한 데이터 수집을 지원하게 됨
  • 안정적이고 효율적인 Remote Write 구현 : 안정적이고 확장 가능한 WAL(write-ahead-log) 구현.  내부 대기열, 샤딩, 스마트 백오프 등을 추가

- Prometheus Agent 모드

  • 프로메테우스 v2.32.0 버전 이상에서 사용 가능
  • 프로메테우스 서버에 내장되어 --enable-feature=agent 플래그 설정 변경으로 사용가능
  • 에이전트 모드는 원격 쓰기 사용 사례에 대해 Prometheus를 최적화
  • 쿼리, 경고 및 로컬 스토리지를 비활성화하고 이를 사용자 정의된 TSDB WAL로 대체(스크래핑 로직, 서비스 검색 및 관련 구성과 같은 다른 모든 것은 동일하게 유지)
  • 장점
    • 효율성 :  agetn TSDB WAL은 성공적인 쓰기 직후 데이터를 제거함. remote endpoint 에 도달할 수 없는 경우에는 remote endpoint이 다시 온라인 상태가 될 때까지 데이터를 디스크에 임시로 유지(서버 모드 설정과 동일). 즉agent 모드는 일반 Prometheus 서버가 유사한 상황에서 사용하는 리소스의 일부만 사용하게 됨.
    • 확장 가능성 : 메트릭 대상의 양과 대상이 노출하는 메트릭의 수를 기반으로 자동 확장이 가능해야 함.  서버 모드의 Prometheus에서는 수집된 모든 것이 한곳에 있는 그대로 유지되어야 하고(stateful) 모든 인스턴스(예: Thanos Query 또는 Promxy)에서 모든 샘플을 집계할 수 있는 전역 보기 쿼리가 필요하게 됨. agent 모드는 검색, 스크래핑 및 원격 쓰기를 별도의 마이크로 서비스로 이동하여 수집에만 집중된 운영 모델이 가능함.(stateless) Prometheus 기반 스크래핑의 손쉬운 수평적 자동 확장 기능을 활성화하여 지표 대상의 동적 변화에 반응 가능.

https://prometheus.io/blog/2021/11/16/agent/

 

 

 

 

'k8s' 카테고리의 다른 글

prometheus agent 사용(EKS환경)  (0) 2023.01.16
CKA 취득 후기 및 공부 방법  (0) 2023.01.03

Providers

  • Official : Terraform (AWS, GCP, Azure…)
  • Verified : 3rd party. heroku …
  • Community

terraform init

여러번 수행해도 아무 문제 없다.

단순히 Provider Plugin을 받는것. ~/.terraform/Plugin 에 설치

Hostname/Organizational Namespace/type 형태로 설치됨

Plugin은 최신 버전으로 다운 받는다.



Configuration Directory

테라폼은 해당 경로에서 확장자가 tf인 파일은 전부 다 읽어서 처리함

보통 main.tf , variable.tf, output.tf, provider.tf 로 지정


Variables

variable 로 시작하여 선언

var.변수명으로 사용

type이 LIst인 경우: var.변수명[0] 부터 시작. 인덱스는 0부터 시작

type이 Map인 경우 : var.변수명[“키명”]

type이 set인 경우 : list와 비슷하지만, 중복할 수 없다. 중복 요소가 있는 경우 에러 발생

type이 Tuple인 경우 : 리스트와 비슷하지만, 각각의 요소들이 각각의 type을 가질 수 있다.

Variable에 default 값을 입력하지 않을 경우, terraform 명령 수행시 직접 입력해야 한다.

Variable 선언 방식

Environment Variable : export TF_VAR_변수명

*.tfvars 파일에 선언

*.auto.tfvars 파일에 선언

명령어로 선언

variable.auto.tfvars 에 입력하면 자동으로 var 입력이 된다.

variable 입력 순서. 뒤로 갈수록 앞의 순번의 것을 덮어쓰므로 더 우선순위가 된다.

1번. Environment Vairables : $export TF_VAR_filename=”/root/cats.txt”

2번. terraform.tfvars : terraform.tfvars에 선언

3번 variable.auto.tfvars : 파일에 선언

4번 명령어 플래그 : terraform apply -var “filename=/root/cats.txt”

Resource Dependencies

Implicit Dependency : 암묵적으로 다른 리소스의 속성을 가져다 쓰는경우. 먼저 지워야한다.($resource_type.resource_name.attribute)

Explicit Dependency : depends on으로 명시적으로 기술한 경우 (왜 이걸 쓰는지 확인 필요)

Output Variables

output 블럭 사용

output “변수명” {
value = variable_value
….
}

$ terraform output 으로 모든 output 변수를 확인할 수 있다.
$ terraform output 변수명 으로 해당 변수명에 대한 값을 확인할 수 있다.

앤서블이나 쉘 스크립트에서 사용가능하다.

Terraform state

terraform init : plugin 받는다

terraform plan :

terraform apply :

terraform.tfstate : 테라폼 스테이트 파일. apply 명령어로 생성됨. json 데이터 구조. 테라폼 명령어로 생성된 모든 인프라가 적혀 있음. single source of truth 로 사용됨
plan 시 tfstate 파일과 비교해서 작성하게 됨

tfstate 파일 사용
– 종속관계 파악 : 리소스들간의 종속성을 파악하여, 생성/삭제 시 디펜던시가 있는 리소스 먼저 삭제한다.
– 성능 : tfstate 파일을 직접 사용할 뿐만 아니라 캐싱 처리도 해둠. 대규모 인프라를 사용하는 곳에서는 매번 tfstate 파일을 refresh 하면 시간이 많이 걸리기 때문에 terraform plan –refresh=false와 같은 명령어로 캐시에서도 사용가능함
– Collaboration : 팀으로 일하는 경우 terraform.tfstate 파일을 팀원간에 공유하여 remote state로 관리한다.

tfstate 고려할점
– state 파일은 민감한 정보를 포함한 인프라의 모든 정보를 다 담고 있다. DB라면 비밀번호도 가지고 있다.
– state 파일은 안전한 스토리지에 저장해두어야 한다.
– tf 파일은 깃헙 정도면 되지만, state 파일은 S3나 gcp bucket 같은 안전한곳에 보관한다.
– tfstate 파일을 직접 건드리지 않는다.

terraform 명령어

– terraform validate : tf 파일이 유효한지 확인한다.
– terraform fmt : tf파일을 보기 좋은 형태(cannonical format)로 변경해준다.
– terraform show : 생성된 인프라의 모든 정보를 다 보여준다.(-json 플래그로 json 형태로 표시가능)
– terraform providers : provider 정보를 다 보여준다.
– terraform output : 결과로 생성되는 변수를 다 보여준다.
– terraform refresh : 테라폼으로 만든 인프라를 수동으로 수정한 경우, tfstate 파일을 현재 상태에 맞도록 수정한다.
– terraform graph : apt install graphviz -y 설치하여 terraform graph | dot -Tsvg > graph.svg 로 파일 생성 후 파일 열면, 리소스 간의 형태를 그래프형태로 볼수 있다.

Mutalbe vs Immutable Infrastructure

테라폼은 왜 인프라를 다 부셨다가 다시 만들까? 서버의 버전을 올린다고 생각해보면, 서버 여러대를 운영할 경우 기존 서버를 업그레이드 하는 건 업그레이드 과정에서 여러가지 이슈가 발생할 수 있다.(configuration drift) 서버들이 운영 중에 미묘하게 차이가 날 수 있다.

따라서 버전이 올라간 서버를 새로 만들고, 오래된 버전의 서버를 폐기한다. -> Immutable Infrastructure 버전을 올린 서버에 문제가 생긴 경우, 다시 이전 버전의 서버를 살린다. 인프라 스트럭처에 버저닝을 하는건 롤백도 쉽고, 운영도 쉽다.

'cloudnative' 카테고리의 다른 글

ArgoCD 사용자 계정 설정(권한)  (0) 2023.01.25

무중단 서비스를 유지하면서 EKS nodegorup의 spec을 변경해야 하는 경우 적용

사전작업

  • 서비스 이중화 : 서비스의 replicas를 2 이상 설정하여 가용성울 보장한다.
  • request 값 확인 : 변경하려는 node의 spec이 서비스들의 request에 부족하지 않은지 확인한다.
  • topologySpreadConstraints 확인 : hostName으로 최대한 노드 이름 기준으로 POD가 분산 되어 뜰 수 있도록 확인한다.

Node Spec 변경

신규 노드그룹 추가

테라폼 코드를 활용하거나, EKS console에서 Add node group 메뉴를 통해 원하는 스펙의 노드그룹을 추가한다.

 

기존 노드 taint 설정

기존 노드에 taint(NoSchedule)을 설정하여 이동하려는 POD가 기존 노드 그룹에 뜨는걸 방지한다.
node_name_1은 ip-xx-xx-xx-xx.ap-northeast-2.compute.internal 과 같은 형태이다.

$ kubectl taint nodes node_name_1  key=value:NoSchedule
$ kubectl taint nodes node_name_2  key=value:NoSchedule

 

기존 노드 Drain 설정

1번 노드에 drain 설정하여 POD를 신규 노드 그룹으로 이동시킨다.

$  kubectl drain node_name_1 –ignore-daemonsets

위와 같이 local storage를 사용하는 POD를 삭제할 수 없다는 메시지가 나오는 경우 아래와 같은 옵션을 추가하여 POD를 이동시킨다.
이때 이동하는 POD의 data는 전부 삭제되기 때문에 주의해야 한다.

$  kubectl drain node_name_1 –ignore-daemonsets –delete-emptydir-data


1번 노드에서 이동한 POD들이 정상적으로 뜬걸 확인 후 2번 노드도 동일하게 작업한다.

$  kubectl drain node_name_2 –ignore-daemonsets

 

기존 노드 그룹 삭제 처리

POD 들이 완전히 이동한 걸 확인 후 기존 노드 그룹은 삭제처리한다.

EKS console 혹은 테라폼 코드를 활용한다.

참고

https://aws.amazon.com/ko/premiumsupport/knowledge-center/eks-worker-node-actions/

https://docs.aws.amazon.com/ko_kr/eks/latest/userguide/migrate-stack.html

https://halfmoon95.tistory.com/entry/EKS-Pod-%EC%88%98-%EC%A0%9C%ED%95%9C

Ubuntu 기준

EC2에서 이중화한 서버의 경우 시간대는 KST나 UTC로 맞추었지만, date를 찍어보면 2~3분 정도 시간차이가 발생하는걸 확인할 수 있다.

이런 경우 발생한 로그를 추적하기에도 어려움이 있기 때문에 시간을 동일하게 맞추어 주는 작업이 필요하다.

Amazon Time Sync Service를 사용하면 손쉽게 적용 가능하다.

아래와 같은 명령어를 입력하여 서버에 적용하면 서버간 시간대가 초 단위까지 일치하는 것을 확인할 수 있다.

$ sudo apt update
$ sudo apt install chrony
$ sudo vi /etc/chrony/chrony.conf
 
#server나 pool 문 앞에 아래 내용 추가
server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4
 
#chrony 서비스 재시작
$ sudo /etc/init.d/chrony restart
 
#동기화 확인
$ chronyc sources -v
 
#동기화 지표 확인
$ chronyc tracking



https://aws.amazon.com/ko/about-aws/whats-new/2017/11/introducing-the-amazon-time-sync-service/

https://docs.aws.amazon.com/ko_kr/AWSEC2/latest/UserGuide/set-time.html

'AWS' 카테고리의 다른 글

EKS node group spec 변경  (0) 2023.01.03
postgreSQL RDS dump 뜨기(pg_dumpall)  (0) 2023.01.03
ALB + Tomcat 환경에서 client ip 로깅하기  (0) 2023.01.03
AWS Access key 종류  (0) 2023.01.03
EC2 EBS 볼륨 증설(ubuntu os)  (0) 2023.01.03

AWS에서 서비스하는 postgreSQL RDS의 경우 super user 권한을 가진 user가 없어서 pg_dumpall 를 수행할 수 없다고 공식 가이드 문서에서 확인할 수 있다.

https://docs.aws.amazon.com/ko_kr/AmazonRDS/latest/UserGuide/PostgreSQL.Procedural.Importing.html

하지만, 약간의 변형을 가하면, pg_dumpall 명령어를 사용할 수 있다.

기본 구성

  • postgreSQL (source DB) : dump를 뜨려는 원본 RDS
  • postgreSQL (target DB) : dump를 복원하려는 타겟 RDS
  • dump용 EC2 : postgreSQL client 버전 12 이상이 설치되어 있는 서버. source RDS와 target RDS에 접속가능해야 한다.

DUMP 수행

postgreSQL RDS는 rdsadmin 이 소유하고 있는 database가 있는데 이건 RDS 생성시 만들었던 master 계정이 권한이 없기 때문에 덤프를 뜨는게 불가능하다. postgreSQL 12버전 이상을 사용하면 특정 database를 제외하고 덤프를 뜰 수 있다.(–exclude-database 옵션)

덤프를 뜨기전, master 계정이 database에 권한을 가지고 있는지, tablespace 소유 여부를 확인한다.

# postgreSQL 접속
$ psql --host=(source RDS Endpoint) --port=(source RDS port) --username=(master 계정) --password

# db list 조회
> \l 

# 사용자 권한 조회
> \du

# table space 조회
> \db

# master 계정 소유로 table space 변경
> ALTER TABLESPACE (tablespace 명) OWNER TO (master 계정);

# master 계정에게 db 권한 부여
> GRANT (db명) TO (master 계정);

master계정에게 권한이 부여되었다면, 아래 명령어로 rdsadmin이 소유한 database는 제외하고 dump를 뜬다. –no-role-passwords 옵션을 사용하여 super_user 권한이 없는 계정으로 dump를 뜬다. 복원 후 사용자 비밀번호는 다시 지정한다.

$ pg_dumpall --no-role-passwords -f (파일명) --exclude-database=rdsadmin --exclude-database=template0 -v -h (source RDS endpoint) -U (master 계정) -p (source RDS port)

데이터 용량이 많아서 압축 덤프를 사용하는 경우의 명령어는 아래와 같다.(gzip 사용)

$ pg_dumpall --no-role-passwords --exclude-database=rdsadmin --exclude-database=template0 -v -h (source RDS endpoint) -U (master 계정) -p (source RDS port) | gzip > 파일명.gz

덤프 중 실제로 잘 덤프를 뜨고 있는지 여부에 대한 확인은 RDS의 모니터링 지표 중 connection 지표를 확인한다.

RESTORE 수행

덤프 작업이 완료 된 후 restore를 수행한다.

$ psql -h (target RDS endpoint) -U (master 계정) -p (target RDS port) < (백업 파일)

압축 덤프를 사용했던 경우에는 아래 명령어로 복원한다.

gunzip -c 파일명.gz | psql -h (target RDS endpoint) -U (master 계정) -p (target RDS port) 

복원 후 psql로 target RDS에 접속하여 사용자 비밀번호를 다시 입력한다.

# target RDS 연결
$ psql --host=(target RDS Endpoint) --port=(target RDS port) --username=(master 계정) --password

# 사용자 정보 변경
> ALTER ROLE (사용자명) WITH LOGIN;
> ALTER USER (사용자명) WITH PASSWORD '(비밀번호)';

40 GB 데이터 베이스 기준으로 dump 뜨는데 30분, restore하는데 20분이 수행되었다.

pg_dump의 경우 table space 및 사용자의 권한은 복사되지 않고, 데이터 베이스 별로 덤프를 떠서 복원해야 하기 때문에 RDS 전체 데이터를 백업해야 하는 경우에는 pg_dumpall 이 더 빠르고 정확하고 편하다.

'AWS' 카테고리의 다른 글

EKS node group spec 변경  (0) 2023.01.03
EC2 서버간 시간 동기화(Amazon Time Sync Service)  (0) 2023.01.03
ALB + Tomcat 환경에서 client ip 로깅하기  (0) 2023.01.03
AWS Access key 종류  (0) 2023.01.03
EC2 EBS 볼륨 증설(ubuntu os)  (0) 2023.01.03

kubernetes v1.21 기준으로 시험봤던 후기입니다.

교육준비 과정은 아래와 같습니다.

Udemy CKA 강의

https://www.udemy.com/course/certified-kubernetes-administrator-with-practice-tests/

누구나 아는 그 강의를 신청하였습니다. 개인적으로 영어를 듣기에 힘이 들어 kodekloud 에서 제공해주는 실습 위주로 공부하였습니다. 직접 명령어를 치며 개념을 익히는 방안으로 수행하니 지루하지 않게 공부할 수 있었습니다. 이론을 제대로 듣지 않았던 만큼 실습을 3번정도 돌며 공부했습니다.


Kubernetes in Action

어려운 개념은 잘 정리된 블로그를 참고하셔도 되지만, 책을 보고 싶은 분은 이 책을 보시면 됩니다. 두께가 상당한 만큼 기본 개념들에 대한 설명이 자세하게 잘 나와 있습니다. 모르는 부분 위주로 찾아서 읽었습니다.


시험 대비

시험 보기 전 다른 분들의 후기를 많이 찾아봤습니다. 저는 k8s cluster 업데이트, kubelet 트러블 슈팅, etcd 백업 및 복구 문제가 어려운 난이도의 문제였는데 거의 비슷하게 나오는것 같으니 이정도는 꼭 미리 보고 가셨으면 좋겠습니다.

시험 볼때 사용중인 클러스터를 매 문제마다 변경해야 합니다. 이부분에 가장 실수가 많을것 같습니다. 문제 풀 때 클러스터를 꼼꼼히 확인 하셔야 합니다.

2시간이라서 시간이 부족할까 걱정했는데 의외로 시간은 많이 남았습니다. 어려운 문제만 잘 확인하고 가신다면 그렇게 어려운 시험은 아닌 것 같습니다.

참고가능한 명령어

공부하면서 사용했던 명령어들입니다. 주로 KodeKloud 의 실습 문제들에 활용이 가능합니다. 좋은 결과 있으시길 바랍니다.

alias 사용

https://kubernetes.io/ko/docs/reference/kubectl/cheatsheet/

alias k='kubectl' 


interactive 명령어 사용

#create taint
kubectl taint nodes node01 spray=mortein:NoSchedule

#untaint
kubectl taint nodes master node-role.kubernetes.io/master:NoSchedule-	

#node info
kubectl get pods -o wide

#노드한테 label 추가
kubectl label node node01 color=blue

#create deployment
kubectl create deployment blue --image=nginx
kubectl scale deployment blue --replicas=6

#create static pod
kubectl run --restart=Never --image=busybox static-busybox --dry-run=client -o yaml --command -- sleep 1000 > /etc/kubernetes/manifests/static-busybox.yaml

#multi scheduler
netstat -natulp | grep 10251 ~ 10253까지 찾아서 안쓰는걸로 port 지정

#log
kubectl logs -f pod이름 (container 이름)

# exec pod
kubectl -n elastic-stack exec -it app cat /log/app.log'

# config view
kubectl config view --kubeconfig my-kube-config

# 현재 컨텍스트(접속 매개 변수)를 선택
kubectl config use-context

# change current context
kubectl config --kubeconfig=/root/my-kube-config use-context research

# get role
kubectl get roles

# user check
kubectl get pods --as dev-user

# get count
kubectl get clusterroles --no-headers | wc -l

# confirm auth
k auth can-i list nodes --as michelle

# edit deployment
kubectl edit deployment

#api resource 확인
kubectl api-resources


network 영역

#network
cat /etc/network/interfaces #network interface 확인가능

# get mac address
arp node01

# route table 확인
ip route

#port 확인
netstat -nplt
netstat -anp | grep scheduler
netstat -anp | grep etcd

# CNI plugin 확인
ls /etc/cni/net.d/

# network ip range
ip addr

'k8s' 카테고리의 다른 글

prometheus agent 사용(EKS환경)  (0) 2023.01.16
multi cluster환경 모니터링(prometheus, grafana)  (0) 2023.01.12

tomcat 8.5.xx 버전을 사용하는 서버 환경에서 어플리케이션을 호출하는 ip를 로깅해야 할 경우가 생긴다. 기본 설정대로 하면 tomcat의 access log에 실제 클라이언트의 외부 IP가 아닌 ALB의 IP가 찍히게 된다.


아래 설정을 참고하면 ALB가 아닌 외부에 호출하는 실체 client ip가 로깅된다.

server.xml 에서 Valve 설정을 아래와 같이 수정한다.

<Valve className="org.apache.catalina.valves.AccessLogValve"
  ....(중략)
  pattern="%{X-Forwarded-For}i %l %u %t &quot;%r&quot; %s %b %{User-Agent}i"
  ....(중략)
/>

<Valve className="org.apache.catalina.valves.RemoteIpValve"
internalProxies="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
remoteIpHeader="x-forwarded-for"
proxiesHeader="x-forwarded-by"
protocolHeader="x-forwarded-proto" />


Remote Ip Valve 설정을 추가할때 모든 IP에 대해 추적하기 위해 정규식을 internalProxies 에 모든 숫자에 대해서 넣었지만, 특정 IP 대역에 대해 추적하려면 해당하는 IP 정규식을 넣으면 된다.


위와 같이 설정시 ALB IP가 아닌 Client IP가 access log에 찍히게 된다.

 

aws 에서 발급하는 access key는 여러가지 종류가 있다. 보통 가장 많이 사용하게 되는 IAM 의 Security credentials에서 발급하게 되는 access key 일 것이다. 하지만 발급을 해보면 AKIA 로 시작하는것을 확인 할 수 있다.

사실 aceess key에는 여러종류가 있어서 접두어로 그 종류를 구분할 수 있다.


IAM Role로 발행한 key의 경우 ASIA로 시작하는 액세스키를 갖게 된다. codecommit을 위한 SSH 퍼블릭 키를 발행받는다면 APKA로 시작하게 된다.

혹시 Access Key로 무언가를 추적해야 할때 유용하게 쓰일 수 있다.


참고 : https://aws.amazon.com/ko/blogs/korea/aws-api-call-2-s3-pre-signed-url/