본문 바로가기

개발/AWS 주저리 주저리

[AWS] Elastic Beanstalk Configuration files(.ebextensions) 다뤄보기

Elastic Beanstalk


Elastic Beanstalk 은 전체적인 서버구성/배포등을 손쉽게 할 수 있도록 제공하는 AWS 서비스군 중 하나입니다.

프로덕션이든 베타든 서비스를 시작하기 앞서 서버구성이 필수인데 그걸 Elastic Beanstalk 이 클릭 몇번만으로 손쉽게 해주는걸 말합니다.

장점은 확장성과 손쉬운 서버 구성( 클릭 몇번만으로 ELB, ALB , auto scaling , 모니터링, 손쉬운 배포등등 이 있습니다.

물론 장점만 있는건 아니죠, 제한적인 플랫폼 , 제한적인 커스마이징 등등..


서비스를 함에 있어 플랫폼 구성을 변경하거나 시스템 환경을 변경해야 할 필요는 분명히 있습니다

가장 흔한 케이스가 apache 나 ngnix 설정 변경등이 있는데요 이러한 제한 적인 커스마이징을 위해서 Elastic Beanstalk은 .ebextensions 라는 환경설정 옵션을 제공하고 있습니다.



AWS Elastic Beanstalk configuration files (.ebextensions)


Elastic Beanstalk 에 프로젝트를 배포하는경우 beanstalk 에서 요구하는 bundle 형태가 있습니다.

이 bundle 에는 Procfile 를 포함해서 압축을 하거나 Buildfile 를 통해 직접 빌드환경을 구성할 수 있습니다.


배포 단계에서 시스템 설정등의 옵션을 지정할경우 bundle 디렉토리 구조는 아래와 같을 것입니다.


위처럼 .ebextensions 폴더를 추가하고 해당 폴더 아래에 설정 파일을 넣어주시면 됩니다.

예를 들어 위의 nginx/nginx.conf 의 경우처럼 설정 파일을 넣으면, EC2 서버의 /etc/nginx/nginx.conf  파일을 통으로 덮어씌워 교체하게 됩니다.

물론 부분적인 설정을 추가할 수도 있겠죠? 이경우 아래 경로에 nginx  설정파일을 넣어주면 배포시 반영됩니다.


/etc/nginx/conf.d/elasticbeanstalk


그럼 몇가지 케이스를 만들어 옵션을 바꿔볼까요?

제가 환경을 구성하며 겪은 기본적인 문제점들 입니다.


1. 강제적인 https 환경 구성 필요( http 접속시 https 로 리다이렉트 )

  ALB 혹은 ELB를 사용하는 경우 ngnix 로 들어오는 host 네임을 가지고 리다이렉트 처리를 해주어야 합니다.


사용자 -(http or https) ->  ALB or ELB ( 80 or 443 ) -( 80내부통신 )->  EC2  ->  nginx proxy_pass(127.0.0.1:5000) -->Applicateion

대부분 beanstalk 으로 서비스를 구성하면 위와 같은 흐름대로 구성이 될텐데요

저기서 문제되는 부분은 ELB나 ALB 는 http 를 https 로 포워딩 하는 기능이 없습니다. 즉 http 나 https 를 사용하지 못하도록 리스너를 막아버릴 순 있지만 포워딩은 할 수 없다는 거죠( 이부분은 AWS 공식 문서상에서 역방향 프록시를 구성하는걸 권고 하고 있습니다. )


ELB,ALB 는 EC2 즉 nginx 를 호출할때 proxy header 에 요청자 ip, host 등등에 대한 정보를 함께 넘겨주고 있습니다

이를 통해 nginx 에서 http 인경우를 확인하여 다시 https 로 리다이렉트 처리를 해주면 됩니다.


        proxy_set_header X-Forwarded-Proto $scheme;

        if ( $http_x_forwarded_proto != 'https' ) {

                return 301 https://$host$request_uri;

        }


저같은 경우는 nginx 설정을 직접 커스마이징 해서 nginx.conf 를 아예 덮어씌우도록 해버렸습니다.

nginx.conf 파일을 .ebextensions/nginx/nginx.conf 로 넣으시면 통으로 덮어 씌워지게 됩니다 :)




2. 특정 디렉토리에 파일생성( pg사 log파일등 )


특정 디렉토리에 설정파일이나 라이브러리 등등.. 추가가 필요한 경우가 생기는데요

.ebextensions 를 통해 배포단계에서 작성되게 하거나 , url 을 통해 다운받아 원하는 디렉토리에 위치시키는게 가능합니다.


파일을 직접 생성하는 경우, 

files:

"/저장될경로/파일명.확장자명":
mode: "권한( 예로 000777 )"
owner: root
group: root
content: |
파일명.확장자명 파일에 작성될 내용



s3 에서 url로 다운받아 배치하는 경우

sources: 저장될 경로: https://리전.amazonaws.com/{버킷네임}/다운받을 파일




3. 리눅스 타임존 변경( beanstalk 의 기본 타임존은 UTC )


기본 타임존이 UTC이다보니 서버시간이 맞지 않을 수 있습니다. 꼭 타임존이 아니더라도 시스템 환경설정을 바꿀 필요성이 있는 경우입니다.

.ebextensions 폴더 하위에 timezone-linux.config 파일을 생성하고 아래와 같이 내용을 작성해줍니다.


###################################################################################################
#### Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
####
#### Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
#### except in compliance with the License. A copy of the License is located at
####
#### http://aws.amazon.com/apache2.0/
####
#### or in the "license" file accompanying this file. This file is distributed on an "AS IS"
#### BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#### License for the specific language governing permissions and limitations under the License.
###################################################################################################

###################################################################################################
#### This configuration file configures the timezone on each instance in the environment.
####
#### It begins by setting an environment property "TZ" to a timezone of your choosing. Have a look
#### in /usr/share/zoneinfo on any of the instances in your environment for all possible options.
#### Additionally this configuration file sets the same chosen timezone on the instance itself by
#### changing the "/etc/localtime" and "/etc/sysconfig/clock".
###################################################################################################

option_settings:
- namespace: aws:elasticbeanstalk:application:environment
option_name: TZ
value: "Asia/Seoul"

files:
"/tmp/set_timezone.sh":
mode: "000755"
owner: root
group: root
content: |
#!/bin/bash
NEWTIMEZONE="$(/opt/elasticbeanstalk/bin/get-config environment -k TZ)"
if [ -z $NEWTIMEZONE ] ; then
echo "TZ" environment property not set
exit 1
fi
if [ ! -f /usr/share/zoneinfo/$NEWTIMEZONE ] ; then
echo /usr/share/zoneinfo/$NEWTIMEZONE does not exist
exit 1
fi
echo 'ZONE="'$NEWTIMEZONE'"' > /etc/sysconfig/clock
echo 'UTC=true' >> /etc/sysconfig/clock
ln -f -s /usr/share/zoneinfo/$NEWTIMEZONE /etc/localtime
ntpdate -u pool.ntp.org

commands:
00-custom-timezone:
command: /tmp/set_timezone.sh



이제 번들을 압축한 다음 beanstalk에 배포해보시면 지정하신 설정이 반영된걸 확인하실 수 있습니다.


추가적인 옵션에 대한 설명은 AWS 공식 문서를 참고해보세요

https://docs.aws.amazon.com/ko_kr/elasticbeanstalk/latest/dg/ebextensions.html