AWS

프론트엔드 CD 설정

MDanderson 2023. 7. 23. 08:18

https://cafe.naver.com/eddicorp/1698

 

[ 링크쌤 컬럼 ] AWS EC2 인스턴스 특성 제어를 위한 IAM 사용자 추가

안녕하세요. 에디로봇아카데미의 링크쌤입니다. 이번에는 IAM 사용자를 추가해보도록 하겠습니다. 사용자 추가를 누릅니다. 다음으로 권한을 설정해야 합니다. AmazonEC2...

cafe.naver.com

 

위를 참고하여 iam 사용자를 추가하자 설정후

 

깃허브 Secret설정하기

AWS_ACCESS_KEY_ID

 

위 속성은 AWS IAM을 가지고 만든 ACCESS_KEY에 해당합니다

 

AWS_SECRET_ACCESS_KEY

위의 IAM 설정과 관련되며 비밀키 생성시 발급되므로 잘 기억해뒀다가 사용해야 합니다.

만약 잊어버렸다면 다시 발급하면 됩니다.

 

CD_DEPLOY_CONFIG

이 옵션은 실제 axios 요청을 보내는 대상을 지정하게 됩니다.

저희 Frontend 입장에서는 VUE_APP_BASE_URL=http://bastion host ip:spring port 형태가 됩니다.

 

BASTION_HOST_PEM_KEY

pem키 웹 브라우저나 편집기서 열고 내용 복사해서 붙여넣으세요.

 

BASTION_SECURITY_GROUP_ID

AWS상에 Bastion Host로 사용하는 녀석의 Security Group ID 입니다.

BASTION_HOST_IP

 

정확하게 BASTION_HOST_DNS라고 표현하는 것이 더 좋았을 것 같습니다.

AWS상에서 public DNS에 해당합니다

 

 

 

bastion host에다가 deploy폴더와 finish폴더를 만들고 workflow를 구동시킨다

그러면 deploy/dist안에 빌드된 프론트 바이너리가 들어있다.

 


python watcher 스크립트 구성

 

https://cafe.naver.com/eddicorp/1737

 

[ 링크쌤 컬럼 ] EC2 instance에 python watcher 스크립트 작성 준비하기

안녕하세요. 에디로봇아카데미의 링크쌤입니다. 우선 아래와 같이 AWS instance에 접속합니다. 그리고 아래와 같이 watcher 스크립트를 작성합니다. watcher ...

cafe.naver.com

sudo yum install python3-devel openssl-devel libffi-devel

python3 --version

pip3 --version

pip3 install cryptography

pip3 install paramiko

pip3 install watchdog

 

위 명령어를 실행해야하는데 pip가 안깔릴것이다.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

pyhon 3 get-pip.py

pip –version

이렇게 pip를 설치한후 install을 진행해보자.

 

 

bastion host에 watcher폴더를만든다  그안에 monitor.py를 만든다

https://cafe.naver.com/eddicorp/1743

 

[ 링크쌤 컬럼 ] Frontend CD with Bastion Host

안녕하세요. 에디로봇아카데미의 링크쌤입니다. 우선 적당히 Spring과 Frontend (Vue or React)를 사용해서 게시판을 만듭니다. 게시판을 작성한 이후 아래와...

cafe.naver.com

vi monitor.py로 아래와같이 만듦

 

 

import os
import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

WATCH_DIR = '/home/ec2-user/deploy/dist'
REMOTE_DIR = '/home/ec2-user/deploy-test/html/'
PRIVATE_EC2_HOST = 'x.x.x.x'       # 내부망 IP
PRIVATE_EC2_KEY = '/home/ec2-user/deploy-test.pem'

class FileChangeHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory and event.src_path == '/home/ec2-user/finish/send.txt':
            self.perform_deployment()
            self.delete_send_file()

    def perform_deployment(self):
        print(f'Deploying files in directory: {WATCH_DIR}')

        contents = [os.path.join(WATCH_DIR, f) for f in os.listdir(WATCH_DIR)]

        subprocess.call(['scp', '-i', PRIVATE_EC2_KEY, '-r'] + contents + [f'ec2-user@{PRIVATE_EC2_HOST}:{REMOTE_DIR}'])
        subprocess.call(['ssh', '-i', PRIVATE_EC2_KEY, f'ec2-user@{PRIVATE_EC2_HOST}', 'docker-compose', '-f', f'{REMOTE_DIR}/../docker-compose.yml', 'up', '-d'])
        print(f'Deployment complete')

    def delete_send_file(self):
        send_file = '/home/ec2-user/finish/send.txt'
        if os.path.exists(send_file):
            os.remove(send_file)
            print(f'{send_file} deleted')

if __name__ == "__main__":
    event_handler = FileChangeHandler()
    observer = Observer()
    observer.schedule(event_handler, '/home/ec2-user/finish', recursive=False)
    observer.start()
    print(f'Watching directory: /home/ec2-user/finish')

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()
[출처] [ 링크쌤 컬럼 ] Frontend CD with Bastion Host (에디로봇아카데미) | 작성자 링크쌤

 

 

python3 monitor.py로 실행

 

deploy-test/html/

private ec2
에 위 형식의 디렉토리가 존재해야함

home/ec2-user/deploy-test/html


private ec2에  deploy-test폴더 안에

deploy-test/conf/dev,conf

html폴더

docker-compose.yaml

위 3개의 폴더or파일을 만든다.

 

docker-compose.yaml에는

version: "3.7"
services:
  nginx:
    image: "nginx:latest"
    container_name: frontend-deploy-nginx
    restart: unless-stopped
    volumes:
      - /home/ec2-user/deploy-test/conf:/etc/nginx/conf.d
      - /home/ec2-user/deploy-test/html:/usr/share/nginx/html
    ports:
      - "80:80"
    networks:
      - app

networks:
  app:
    driver: bridge
[출처] [ 링크쌤 컬럼 ] Frontend CD with Bastion Host (에디로봇아카데미) | 작성자 링크쌤

 

dev.conf에는

server {
  listen 80;
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}
[출처] [ 링크쌤 컬럼 ] Frontend CD with Bastion Host (에디로봇아카데미) | 작성자 링크쌤

 

위와같이 작성

 

 

python3 monitor.py 를 실행한 상황에서 , workflow실행 , docker-compose up

그러면 docker ps 해보면 nginx가 돌아가고 있을것.

 

 

 

'AWS' 카테고리의 다른 글

IAM 계정생성  (0) 2024.02.28
aws amplify 와 github 연동  (1) 2024.02.26
백엔드 CD 설정  (0) 2023.07.23
bastion host와 private EC2 만들기  (0) 2023.07.20
고대디 도메인 구매 ,연결  (0) 2023.05.06