RDS 인증서 교체 작업이 있어 확인한 내용을 기록합니다.

변경 가능한 리스트 인증서 및 유효기간

  • rds-ca-rsa2048-g1
  • rds-ca-rsa4096-g1
  • rds-ca-ecc384-g1

무중단 수정 가능 확인 (재 기동)

SupportsCertificateRotationWithoutRestart 값이 true일 경우 RDS 재시작이 필요없습니다.

 

import boto3
import csv
import subprocess


# RDS 클라이언트 생성
region_name = 'ap-northeast-2'
session = boto3.Session(profile_name='test')
rds = session.client('rds', region_name=region_name)


response = rds.describe_db_instances()


# CSV 파일 열기
with open('rds_instances.csv', mode='w', newline='') as file:
    writer = csv.writer(file)

    # 헤더 행 작성
    writer.writerow(['엔진 버전', '인스턴스 이름', '엔드포인트', '엔진 정보'])

    # 각 RDS 인스턴스에 대한 정보 작성
    for db_instance in response['DBInstances']:
        engine = db_instance['Engine']
        if engine == 'docdb':  # DocumentDB 인스턴스 건너뛰기
            continue

        engine_version = db_instance['EngineVersion']
        db_instance_name = db_instance['DBInstanceIdentifier']
        endpoint = db_instance['Endpoint']['Address']
        region = 'ap-northeast-2'  # 필요한 경우 리전을 변경하세요

        command = f"aws rds describe-db-engine-versions --profile test --engine {engine} --engine-version {engine_version} --include-all --region {region}"
        result = subprocess.run(command, shell=True, executable='/bin/zsh',  capture_output=True, text=True)
        if result.stderr:
            print(f"Error: {result.stderr}")
        else:
            engine_info = result.stdout
            jq_filter = '.DBEngineVersions[] | "EngineName: \(.Engine), EngineVersion: \(.EngineVersion), SupportsCertificateRotationWithoutRestart: \(.SupportsCertificateRotationWithoutRestart), SupportedCAs: \(.SupportedCACertificateIdentifiers | join(\", \"))"'
            engine_info = subprocess.run(['jq', '-r', jq_filter], input=engine_info, text=True, capture_output=True).stdout
            writer.writerow([engine_version, db_instance_name, endpoint, engine_info])

 

TLS 통신하는 RDS, 계정 확인 (Mysql)

-- SSL/TLS
SELECT id, user, host, connection_type
FROM performance_schema.threads pst
INNER JOIN information_schema.processlist isp
ON pst.processlist_id = isp.id;

 

 

인증서 교체 전 어플리케이션 이슈 검토

제가 확인한 내용으로 잘못된 정보가 있을 확률이 매우 높습니다. 

 

1. 기존 TLS 통신을 하는 서비스에는 이슈가 없다. 

 - 이유: 신뢰 인증저장소에 AWS Root CA가 등록되어 있는 상태임으로 rds-ca-rsa2048-g1로 교체 해도 이슈는 없다.

2. 만약 외부 인터넷과 통신이 어려운 서비스는 AWS 번들을 신뢰 저장소에 등록이 필요할 것으로 예상 합니다.(완전 추정)

 

교체

순단 이슈는 검토 했지만 따로 기록하지 않겠습니다.

웹 콘솔에서 작업 또는 aws cli 중 선택해서 진행하면 됩니다.

 

참고로 테스트 당시 인증서 교체에 약 26초 정도 걸렸습니다.

현재 Github action self hosted runner 구성은 서버에 프로세스 형태로 구성하기 또는 쿠버네티스에 ARC 로 구성하는 방법이 있습니다.

 

참고 : 

 ARC : https://tech.buzzvil.com/blog/%EC%BF%A0%EB%B2%84%EB%84%A4%ED%8B%B0%EC%8A%A4%EC%97%90%EA%B2%8C-github-actions-%EC%84%A4%EC%B9%98%EC%97%90-%EB%8C%80%ED%95%B4-%EB%AC%BB%EB%8B%A4/

 

 

GitHub Actionsでself-hosted runnersをDockerで作る - Qiita

https://docs.github.com/ja/actions/hosting-your-own-runners/managing-self-hosted-runners/about-self…

qiita.com

 

 

저는 특정 상황 때문에 이미지 파일로 구성하려고 합니다. 

 

도커 파일 

FROM ubuntu:22.04


ARG PERSONAL_ACCESS_TOKEN
ARG HOST=https://github.com
ARG ORGANIZATION
ARG REPOSITORY

ENV BINARY_URL=https://github.com/actions/runner/releases/download/v2.315.0/actions-runner-linux-x64-2.315.0.tar.gz

ENV RUNNER_NAME=myRunner
ENV RUNNER_GROUP=Default
ENV RUNNER_LABELS="self-hosted,Linux"
ENV RUNNER_WORKDIR=_work

RUN apt-get update && \
    apt-get install -y dotnet-sdk-6.0 curl sudo && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

SHELL ["/bin/bash", "-o", "pipefail", "-c"]
RUN useradd runner && \
    echo "runner:runner" | chpasswd && \
    chsh -s /usr/bin/bash runner && \
    usermod -aG sudo runner && \
    mkdir /actions-runner && \

    chown runner:runner /actions-runner

USER runner
WORKDIR /actions-runner

RUN curl -fsSL -o actions-runner-linux-x64-2.315.0.tar.gz -L $BINARY_URL && \
    tar xf ./actions-runner-linux-x64-2.315.0.tar.gz && \
    rm actions-runner-linux-x64-2.315.0.tar.gz && \
    rm actions-runner.tar.gz && \
    echo $PERSONAL_ACCESS_TOKEN && \
    ./config.sh \
        --unattended \
        --url $HOST/$ORGANIZATION/$REPOSITORY \
        --pat $PERSONAL_ACCESS_TOKEN \
 #      --token $PERSONAL_ACCESS_TOKEN \
        --name $RUNNER_NAME \
        --runnergroup $RUNNER_GROUP \
        --labels $RUNNER_LABELS \
        --work $RUNNER_WORKDIR

CMD ["nohup","./run.sh", "&"]

작업 : AMI → EC2 생성

 

원인 : cloud-init와 관련된 python2.7 내의 종속성 문제 추정하고 있습니다. 

  

이슈 감지 :

   AMI로 EC2 (A) 생성

   EC2 상태 “인스턴스 상태 검사” 실패 확인 및 서버 접속 불가

 

로그 확인:

 

EC2 직렬콘솔로 부팅 화면확인

   Failed to start LSB: Bring up/down networking error message 에러 발생

    추정 (cloud-init 동작에 문제가 발생되어 IP를 할당 실패)

 

1차 조치 진행 후 [cloud-initFAILED[607]: ] File "/usr/bin/cloud-init", line 9, in <module>Failed to start Initial cloud-init job (pre-networking). 에러 발생

   추정 (문제는 cloud-init와 관련된 python2.7 내의 종속성 문제로. pip 및 yum을 통해 요청 및 urllib3을 제거한 다음 yum을 통해 다시 설치)

 

 

조치 (1차) -실패

https://repost.aws/questions/QU8L6L6c7HRRqU0-SajiAc5A/aws-instance-failed-to-start-lsb-bring-up-down-networking-error-message

위에 글을 참고하여 신규 ec2 (B) 생성 문제 EBS(A)를 신규 ec2에 연결

1. Stop the impaired instance and detach the root volume.
2. Attach the root volume on another rescue instance (which is running in the same availability zone).
3. Check the disk/volume attached and mount it.

            $ sudo lsblk
            $ sudo lsblk -f
            $ mkdir /rescue
            $ mount /dev/xvdf1 /rescue

4. Mount the required pseudo filesystems and chroot into the environment.

            $ for i in proc sys dev run; do mount --bind /$i /rescue/$i ; done
            $ chroot /rescue

5. Check the cloud-init configurations and the cloud-init package, if it is installed.

            $ ls -l /etc/cloud/
            $ sudo rpm -qa | grep cloud-init
            $ sudo yum install cloud-init

6. Exit from the chroot environment and unmount the filesystems.

            $ exit
            $ for i in proc sys dev run; do umount /rescue/$i ; done
            $ umount /rescue

8. Detach the root volume from the rescue instance and attach it to the original instance.

 9. Start the instance.

 

 

조치 (2차) - 성공

 

   AMI 로 다시 EC2 (C) 생성 볼륨 분리 후 EC2(B) 에 연결

   조치 1차 4번 까지 진행 후 하기 명령어 실행

   sudo pip uninstall urllib3

   sudo pip install urllib3

   조치 1차 5번 진행

     5. Check the cloud-init configurations and the cloud-init package, if it is installed.

   sudo yum update cloud-init

   조치 1차 6번 진행

     6. Exit from the chroot environment and unmount the filesystems.

   EBS 분리 후 EC2 (C)에 연결 후 서버 기동

 

 

후기 :

  ami 생성 후 원본서버가 기동 상태에서 ami로 서버가 잘 올라오는지 확인 후 원본 서버를 삭제가 필요합니다 ㅠㅠ

 

'AWS > EC2' 카테고리의 다른 글

NLB + ALB (고정 퍼블릭 IP  (0) 2024.08.26

+ Recent posts