Elastic Beanstalk에서 Docker 다단계 빌드를 위한 동적 환경 변수를 설정하려면 어떻게 해야 하나요?

4분 분량
0

AWS Elastic Beanstalk에서 Docker 다단계 빌드를 위한 동적 환경 변수를 설정하고 싶습니다.

간략한 설명


빌드 단계에서만 Dockerfile에 하드코딩된 변수 또는 정적 변수를 설정할 수 있습니다. 예를 들어, ENV 키를 사용하여 정적 변수를 설정합니다. 이전 단계에서 빌드한 Dockerfile의 다른 컨테이너는 Elastic Beanstalk 변수에 액세스할 수 없습니다. 다단계 빌드 중에 동적 환경 변수를 설정하려면 AWS Systems Manager AWS::SSM::Parameter 리소스 또는 Elastic Beanstalk 변수를 사용하세요. 변수는 한 번만 설정해야 하므로 SSM 파라미터를 사용하는 것이 가장 좋습니다.

**참고:**AWS Command Line Interface(AWS CLI) 명령을 실행할 때 오류가 발생하는 경우 AWS CLI 오류 해결을 참고하세요. 또한 최신 AWS CLI 버전을 사용하고 있는지 확인하세요.

해결 방법

**참고:**다음 예제에서는 Alpine Linux에 React 애플리케이션이 설치되어 있습니다. 모든 배포 패키지 관리자를 사용하여 컨테이너를 빌드하고 필요한 패키지를 설치할 수 있습니다.

SSM 파라미터 사용

**참고:**Amazon Elastic Compute Cloud(Amazon EC2) 리눅스 인스턴스가 SSM 파라미터를 가져오도록 허용하려면 EC2 리눅스 인스턴스 프로필에 ssm:GetParameters 권한이 있어야 합니다.

1.시스템 관리자 콘솔을 사용하여 SSM 파라미터를 생성합니다. 또는 put-parameter AWS CLI 명령을 실행합니다.

aws ssm put-parameter --name PRODURL_SSM --value http://myproddomain.com --type String

2.다음 Dockerfile을 사용하여 애플리케이션을 배포합니다. Dockerfile은 임시 또는 빌드 컨테이너 내에 있는 SSM 매개변수 값을 가져온 다음 빌드 중에 변수를 내보냅니다.

# Build environment
FROM node:13.12.0-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package.json ./
COPY package-lock.json ./
RUN npm install react-scripts@3.4.1
COPY . ./
## Install the required packages for awscli, curl, and jq. ##
RUN apk -v --no-cache add \
        py-pip \
        curl \
        jq \
        && \
        pip install awscli --upgrade --user
## Export the region dynamically retrieving it from the instance metadata, and then retrieve the SSM parameter value using awscli. Then, place the parameter in a text file, and export the variable using the value from the text file. Finally, run the build. ##
RUN TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` && export REGION=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)&& /root/.local/bin/aws ssm get-parameters --names PRODURL_SSM --region $REGION | grep Value | cut -d '"' -f4 >> /tmp/SSMParameter.txt && export DYNAMIC_SSM_VAR=$(cat /tmp/SSMParameter.txt) && npm run build
# Production environment
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html
## Copy the text file that has the SSM parameter value from the build container to the production container to confirm the variable was retrieved successfully. ##COPY --from=build /tmp/SSMParameter.txt /tmp
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

3.배포가 성공했는지 확인하려면 복사한 파일에 SSM 파라미터 변수 값이 포함되어 있는지 확인합니다.

예시:

# docker exec -it <Container-Id> sh# cat /tmp/SSMParameter.txt
http://myproddomain.com

Elastic Beanstalk 변수 사용

**참고:인스턴스 프로파일을 환경으로 허용하려면 인스턴스 프로필에 ** ElasticBeanstalk:DescribeConfigurationSettings AWS ID 및 액세스 관리(IAM) 권한이 있어야 합니다.

1.EB CLI(Elastic Beanstalk 명령줄 인터페이스)에서 사용하는 config.yml 파일을 프로젝트 루트 디렉터리에 복사합니다.

예시:

cp .elasticbeanstalk/config.yml .

2.EB CLI를 사용하여 Elastic Beanstalk 변수를 설정하려면 다음 명령을 실행하여 기존 환경을 업데이트하거나 배포하세요.

eb setenv PRODURL_EB=http://myproddomain.com

3.새 Elastic Beanstalk 환경을 만들려면 프로젝트 루트 디렉터리의 config.yml 파일에 새 환경 이름을 추가합니다. 그리고 나서 다음 명령을 실행합니다.

eb create --envvars PRODURL_EB=http://myproddomain.com

4.다음 Dockerfile을 사용하여 애플리케이션을 배포합니다. Dockerfile은 빌드 컨테이너 내에 있는 Elastic Beanstalk 변수의 값을 가져온 다음 빌드 중에 변수를 내보냅니다.

# Build environmentFROM node:13.12.0-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package.json ./
COPY package-lock.json ./
RUN npm install react-scripts@3.4.1
COPY . ./
## Create an .elasticbeanstalk directory to place the config.yml file in, so that the eb cli can interact with the Elastic Beanstalk environment. ##
RUN mkdir .elasticbeanstalk
## Copy config.yml to /app/.elasticbeanstalk inside the build container as it will be used by eb cli ##
COPY config.yml /app/.elasticbeanstalk
## Install required packages for awsebcli ##
RUN apk -v --no-cache add \
        gcc \
        musl-dev \
        openssl \
        openssl-dev \
        make \
        py-pip \
        libffi-dev \
        python \
        python-dev \
        && \
        pip install awsebcli --upgrade --user
## Retrieve the Elastic Beanstalk variable using awsebcli and place it in a text file. Then, export the desired variable using the value from the text file, then run the build. ##
RUN /root/.local/bin/eb printenv | grep PRODURL_EB | awk '{print $3}' >> /tmp/EBVar.txt && export DYNAMIC_EB_VAR=$(cat /tmp/EBVar.txt) && npm run build
# Production environment
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html
## Copy the text file that has the Elastic Beanstalk variable value from the build container to the production container to confirm the variable was retrieved successfully ##
COPY --from=build /tmp/EBVar.txt /tmp
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

5.배포가 제대로 되었는지 확인하려면 복사한 파일에 Elastic Beanstalk 변수 값이 포함되어 있는지 확인하세요.

# docker exec -it <Container-Id> sh# cat /tmp/EBVar.txt
http://myproddomain.com

관련 정보

인스턴스 ID 문서

get-parameters

AWS 공식
AWS 공식업데이트됨 6달 전