목차
서버리스 서비스를 이용하면 서버를 설치 운용하거나 관리할 필요 없이 비지니스 로직을 코드로 구현하는 것만으로도 애플리케이션 구축이 가능합니다 . 지난 "Amazon Polly를 통한 음성 읽기 서버리스 앱 개발하기" 블로그에서, AWS 관리 콘솔에서 서버리스 웹 애플리케이션을 구축하는 방법을 살펴 보았습니다. 이번에는 웹 애플리케이션 구축을 위하여 프로젝트를 생성하고, 코드를 만들고, 서비스를 배포하는 일련의 과정을 Cloud9 IDE를 이용하는 방법을 살펴봅니다. 또한, SAM(Serverless Application Model)과 AWS Code 시리즈를 이용하여 DevOps 환경으로 CI/CD 프로세스를 구축하는 방법을 실습합니다.
프리티어 기준으로 비용이 발생하지 않는 범위내에서 실습을 진행할 수 있습니다. 해당 실습을 위해서는 별도의 쿠폰이 제공됩니다.
Service | Sub Service | Unit | Pricing | Use | free tier | etc |
---|---|---|---|---|---|---|
Cloud9 | EC2 - t2.micro | 1 h | $0.0116/Hour | t2.micro 2hour | 750hour/month | |
EBS - 8GB | 1 m | $0.1/GB | 8GB 2hour | 30GB/month | ||
Lambda | - | 128MB | $0.000000208/100ms | 1,000번 이하 | 100만번 요청 400GB-초 | 1년 후 지속 제공 |
API Gateway | - | 1백만 API 호출당 $3.50 처음 10TB에 대해 $0.09/GB | 1,000번 이하 | 호출 100만건 | ||
DynamoDB | - | WCU당 최소 $0.47 RCU당 최소 $0.09 GB당 최소 $0.25 | WCU 5 RCU 5 스토리지 100M | 매달 2억건 요청 | 1년 후 지속 제공 | |
SNS | - | 처음 1GB/월 $0.000 GB당 최대 10TB/월 $0.090 GB당 | 100M 이하 | 매달 15GB의 데이터 전송 | ||
Polly | - | 1백만 문자당 $4 | 1,000 문자 이하 | 매달 문자 500만개 | ||
CodeStar | CodePipeline | 월별 활성 파이프라인*당 $1 | 1개 | 매월 활성 파이프라인 1개 | ||
CodeCommit | 최초 5명 초과시 월별 $1 GB당 $0.06/월 (10GB/월 초과) Git 요청당 $0.001 (1000회/월 초과) | 1개 | 최초 5명까지 매달 50GB의 스토리지 매달 10,000건의 Git 요청 | 1년 후 지속 제공 | ||
CodeBuild | build.general1.small $0.005/분 | 30분 | 매월 100 빌드 분의 build.general1.small | 1년 후 지속 제공 | ||
CodeDeploy | EC2 또는 Lambda에 배포 무료 | 30회 | - | |||
CloudFormation | - | - | - | |||
s3 | - | PUT, COPY, POST 또는 LIST 요청 $0.005/1,000건 GET, SELECT 및 기타 모든 요청 $0.0004/1,000건 처음 50TB/월 $0.023/GB | Put 100번 내외 GET 2,000번 내외 | 매달 5GB 스토리지 Get 요청 20,000건 Put 요청 2,000건 |
실습이 종료되고 나면 리소스를 삭제해야 합니다. 해당 실습은 CloudFormation 기반으로 진행됩니다. 배포 Stack을 삭제하고, 실습에 사용한 Cloud9과 같은 Stack을 삭제하면, 배포되어 있는 리소스도 함께 삭제가 됩니다. 반드시 상단에 게시된 리소스에 대해서 삭제가 이루어졌는지 확인 후 실습을 종료합니다. 만약 S3 버킷에 객체가 남아 있어서 삭제가 되지 않는 경우, 해당 S3 버킷을 직접 삭제하고 확인 합니다.
아래는 실습에 구축할 서버리스 웹 애플리케이션의 다이어그램입니다. 서버리스 서비스를 이용하기 때문에, 프로비저닝, 패치, 확장에 대해 고민할 필요가 없으며, 사용한 만큼만 비용을 지불합니다. 또한, 서버리스 서비스는 완전 관리형 서비스이기 때문에, 개발자는 애플리케이션 개발 자체에만 집중할 수 있습니다.
이 애플리케이션은 다섯 가지 영역으로 구분할 수 있습니다.
실습 순서는 다음과 같이 Lab1과 Lab2로 구성되어져 있습니다.
Lab1은 Cloud9 IDE를 이용하여 서버리스 웹 애플리케이션을 구축하는 방법을 살펴봅니다. 이 실습은 Cloud9이 존재하는 Singapore 리전에서 English 언어로 진행합니다. 통합 개발 환경(IDE)은 싱가포르 리전을 사용하지만, 서비스 배포는 리전을 선택 할 수 있습니다. 이 실습에서는 배포 서비스의 확인을 간단히 하기 위해서 Singapore 리전을 그대로 사용하겠습니다.
새로운 애플리케이션 및 람다 함수를 생성합니다. Cloud9 IDE 우측 네비게이션의 AWS Resources 탭을 클릭하고, Lambda 아이콘을 클릭하면 새로운 함수를 생성할 수 있습니다. 앞으로 추가할 나머지 3개의 함수도 동일한 방법으로 생성합니다.
PostNews 함수는 아래에서 제공하는 코드로 대체하고 Ctrl+S를 눌러서 저장합니다. 코드 설명은 주석을 기반으로 생략합니다.
# -*- coding: utf-8 -*- from __future__ import print_function import boto3 import os import json import uuid import datetime def lambda_handler(event, context): if "body" in event: event = json.loads(event['body']) print (event) recordId = str(uuid.uuid4()) voice = event["voice"] originText = event["text"] timbre = event["timbre"] pitch = event["pitch"] updateDate = datetime.datetime.now().strftime("%Y%m%d") print('Generating new DynamoDB record, with ID: ' + recordId) # Create the item in DynamoDB table dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['DB_TABLE_NAME']) table.put_item( Item={ 'id' : recordId, 'originText': originText, 'postDate': int(updateDate), 'pollyVoice' : voice, 'pollyStatus' : "PROCESSING", 'pollyTimbre': timbre, 'pollyPitch': pitch } ) # Sending notification about new post to SNS client = boto3.client('sns') client.publish( TopicArn = os.environ['SNS_TOPIC'], Message = recordId ) response = { 'statusCode': 200, 'body': json.dumps({'recordId': recordId}), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } } return response |
이번에는 SAM Template을 변경합니다. 먼저 좌측 소스코드 영역에서 template.yaml 파일을 더블클릭하여 편집 창을 열고, 아래 Template 코드로 대체하고, Ctrl+S를 눌러서 저장합니다.
AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Description: >- Building Serverless development environment and CI/CD process for DevOps based on Cloud9 Globals: Function: Runtime: python2.7 Handler: lambda_function.lambda_handler MemorySize: 128 Timeout: 60 Resources: PostNews: Type: 'AWS::Serverless::Function' Properties: CodeUri: PostNews Description: Post news text to convert from text to speech Events: PostNewsApi: Type: Api Properties: Path: /news Method: POST Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:PutItem' - 'sns:Publish' Resource: '*' |
SAM 템플릿 구성은 다음과 같습니다.
Globals는 전역으로 사용합니다. 함수(Function)이나 API에서 반복해서 사용하는 것을 선언할 수 있습니다.
SAM 설정이 완료되면 해당 template.yaml 파일을 Cloud9에서 바로 배포할 수 있습니다.
우측의 해당 Lambda 함수에서 마우스 우측 버튼을 클릭하고 Deploy 명령을 수행합니다. 해당 SAM template이 CloudFormation Stack에 업데이트 되는 것을 확인할 수 있습니다.
SAM 템플릿을 이용해서 S3 Bucket, SNS, DynamoDB 테이블을 배포할 수 있습니다. 다음과 같이 template.yaml 파일에 리소스에 추가합니다.
Environment: 환경 변수를 선언합니다. 각각의 Lambda 함수에는 DynamoDB, SNS, S3 버킷에 접근하기 위해서 ARN이 필요합니다. SAM에서 자동으로 만들어준 각각의 리소스 ARN을 참조할 수 있도록 설정합니다.
NewsTable: SAM에서 SimpleTable은 DynamoDB를 의미합니다. 여기서 DynamoDB를 기본 세팅인 WCU 5, RCU 5 값으로 생성합니다.
NewsTopic: PostNews에 들어온 텍스트 값은 비동기적으로 처리를 위하여 ConvertAudio 함수의 처리를 필요로 합니다. ConvertAudio의 처리를 위해서 사용할 SNS Topic을 하나 생성합니다.
PollyMp3Bucket: Amazon Polly를 이용해서 생성한 MP3 파일을 저장할 S3 버킷을 생성합니다.
StaticWebBucket: S3는 객체 스토리지이면서 정적 웹 호스팅을 위한 서비스로 활용할 수 있습니다. 여기서는 정적 웹 호스팅을 위한 설정까지 함께 구성하여 SAM에 서비스를 추가합니다.
변경된 SAM 템플릿을 반영하기 위해서 우측 Lambda 함수에서 마우스 우측 버튼을 클릭하고 Deploy 명령을 수행합니다.
AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Description: >- Building Serverless development environment and CI/CD process for DevOps based on Cloud9 Globals: Function: Runtime: python2.7 Handler: lambda_function.lambda_handler MemorySize: 128 Timeout: 60 Environment: Variables: DB_TABLE_NAME: Ref: NewsTable SNS_TOPIC: Ref: NewsTopic BUCKET_NAME: Ref: PollyMp3Bucket Resources: NewsTable: Type: 'AWS::Serverless::SimpleTable' Properties: PrimaryKey: Name: id Type: String ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 NewsTopic: Type: 'AWS::SNS::Topic' Properties: DisplayName: NewsTopic PollyMp3Bucket: Type: 'AWS::S3::Bucket' StaticWebBucket: Type: 'AWS::S3::Bucket' Properties: AccessControl: PublicRead WebsiteConfiguration: IndexDocument: index.html ErrorDocument: error.html PostNews: Type: 'AWS::Serverless::Function' Properties: CodeUri: PostNews Description: Post news text to convert from text to speech Events: PostNewsApi: Type: Api Properties: Path: /news Method: POST Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:PutItem' - 'sns:Publish' Resource: '*' |
ConvertAudio 함수 코드를 다음과 같이 변경하고 저장합니다. 소스 코드의 설명은 주석으로 대체합니다.
# -*- coding: utf-8 -*- from __future__ import print_function import boto3 import os from contextlib import closing from boto3.dynamodb.conditions import Key, Attr import re def lambda_handler(event, context): postId = event["Records"][0]["Sns"]["Message"] print ("Text to Speech function. Post ID in DynamoDB: ", postId) # Retrieving information about the post from DynamoDB table dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['DB_TABLE_NAME']) postItem = table.query( KeyConditionExpression=Key('id').eq(postId) ) text = postItem["Items"][0]["originText"] voice = postItem["Items"][0]["pollyVoice"] timbre = postItem["Items"][0]["pollyTimbre"] pitch = postItem["Items"][0]["pollyPitch"] rest = text # Because single invocation of the polly synthesize_speech api can # transform text with about 3,000 characters, we are dividing the # post into blocks of approximately 2,900 characters. textBlocks = [] while (len(rest) > 3000): begin = 0 end = rest.find(".", 2900) if (end == -1): end = rest.find(" ", 2900) textBlock = rest[begin:end] rest = rest[end:] textBlocks.append(textBlock) textBlocks.append(rest) #For each block, invoke Polly API, which will transform text into audio polly = boto3.client('polly') for textBlock in textBlocks: removeBrackets = re.sub(r'\([^)]*\)', '', textBlock) repTextBlock = re.sub('[·…]', '<break time="100ms"/>', removeBrackets) #repTextBlock = re.sub('["·\'…]', '<break time="100ms"/>', removeBrackets) ssmlBlock = "<speak><amazon:effect vocal-tract-length=\"" + timbre + "\"><prosody pitch=\"" + pitch + "\">" + repTextBlock + "</prosody></amazon:effect></speak>" #print (ssmlBlock) response = polly.synthesize_speech(OutputFormat='mp3', Text = ssmlBlock, VoiceId = voice, TextType = 'ssml') #Save the audio stream returned by Amazon Polly on Lambda's temp # directory. If there are multiple text blocks, the audio stream # will be combined into a single file. if "AudioStream" in response: with closing(response["AudioStream"]) as stream: output = os.path.join("/tmp/", postId) with open(output, "a") as file: file.write(stream.read()) s3 = boto3.client('s3') s3.upload_file('/tmp/' + postId, os.environ['BUCKET_NAME'], postId + ".mp3") s3.put_object_acl(ACL='public-read', Bucket=os.environ['BUCKET_NAME'], Key= postId + ".mp3") location = s3.get_bucket_location(Bucket=os.environ['BUCKET_NAME']) region = location['LocationConstraint'] if region is None: url_begining = "https://s3.amazonaws.com/" else: url_begining = "https://s3-" + str(region) + ".amazonaws.com/" \ url = url_begining \ + str(os.environ['BUCKET_NAME']) \ + "/" \ + str(postId) \ + ".mp3" #Updating the item in DynamoDB response = table.update_item( Key={'id':postId}, UpdateExpression= "SET #statusAtt = :statusValue, #urlAtt = :urlValue", ExpressionAttributeValues= {':statusValue': 'UPDATED', ':urlValue': url}, ExpressionAttributeNames= {'#statusAtt': 'pollyStatus', '#urlAtt': 'mp3Url'}, ) return |
아래와 같이 자동으로 template.yaml 파일에 ConvertAudio 함수 설정이 추가되는 것을 확인할 수 있습니다. 하지만, 해당 SAM 설정 대신 아래의 SAM 코드로 대체합니다.
Resources: ... ConvertAudio: Type: 'AWS::Serverless::Function' Properties: CodeUri: ConvertAudio Description: Convert Audio using Amazon Polly Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:Query' - 'dynamodb:UpdateItem' - 's3:GetBucketLocation' - 's3:PutObject' - 's3:PutObjectAcl' - 'polly:SynthesizeSpeech' Resource: '*' Events: ConvertResource: Type: SNS Properties: Topic: Ref: NewsTopic |
코드는 다음을 참고합니다. 함수에 대한 설명은 주석으로 대체합니다.
from __future__ import print_function import boto3 import os import json import decimal from boto3.dynamodb.conditions import Key, Attr # https://docs.aws.amazon.com/ko_kr/amazondynamodb/latest/developerguide/GettingStarted.Python.04.html # Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) def lambda_handler(event, context): if "queryStringParameters" in event: event = event['queryStringParameters'] print (event) postId = event["postId"] dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['DB_TABLE_NAME']) if postId == "*": items = table.scan() else: items = table.query(KeyConditionExpression=Key('id').eq(postId)) response = { 'statusCode': 200, 'body': json.dumps(items["Items"], cls=DecimalEncoder), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } } return response |
SAM 템플릿을 GetNews 함수에 맞게 기존 설정을 지우고 아래와 같이 추가합니다.
Resources: ... GetNews: Type: 'AWS::Serverless::Function' Properties: CodeUri: GetNews Description: Gather information from Ajax calls from web pages Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:Query' - 'dynamodb:Scan' Resource: '*' Events: GetNewsApi: Type: Api Properties: Path: /news Method: GET |
코드는 다음을 참고합니다. 함수에 대한 설명은 주석으로 대체합니다.
from __future__ import print_function import boto3 import os import json from boto3.dynamodb.conditions import Key, Attr def lambda_handler(event, context): if "body" in event: event = json.loads(event['body']) print (event) # Bad Request if event["postId"] is None or event["postId"] == "": response = { 'statusCode': 400, 'body': json.dumps({'message': "An unknown error has occurred. Missing required parameters."}), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } } return response postId = event["postId"] dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['DB_TABLE_NAME']) table.delete_item(Key={"id":postId}) s3 = boto3.client('s3') s3.delete_object(Bucket=os.environ['BUCKET_NAME'], Key= postId + ".mp3") response = { 'statusCode': 200, 'body': json.dumps({'message': "item is deleted : " + postId}), 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } } return response |
DeleteNews를 위해서 SAM 템플릿을 아래와 같이 추가합니다.
Resources: ... DeleteNews: Type: 'AWS::Serverless::Function' Properties: CodeUri: DeleteNews Description: Delete news item in DynamoDB Table and mp3 file in S3 bucket. Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:DeleteItem' - 's3:DeleteObject' Resource: '*' Events: DeleteNewsApi: Type: Api Properties: Path: /news Method: DELETE |
삭제 이벤트에 대해서 DynamoDB의 항목을 삭제하기 위해서 dynamodb:DeleteItem 정책과 S3에 생성된 MP3 파일을 삭제하기 위해서 s3:DeleteObject 정책을 추가합니다.
SAM 템플릿에서 생성된 리소스를 확인하기 위해서 CloudFormation의 Stack 상세에서 Outputs으로 출력을 만들 수 있습니다. 여기서는 3개의 출력물을 생성합니다.
Outputs: S3WebBucket: Description: S3 Bucket Name for web hosting Value: Ref: StaticWebBucket WebsiteURL: Description: Name of S3 bucket to hold website content Value: 'Fn::Join': - '' - - 'https://' - 'Fn::GetAtt': - StaticWebBucket - DomainName - '/index.html' APIEndpointURL: Description: URL of your API endpoint Value: 'Fn::Sub': >- https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/news |
S3에서 제공하는 정적 웹 호스팅을 하는 버킷에서 제공하는 URL의 도메인과 API Gateway 에서 배포한 API Endpoint URL의 도메인은 서로 상이합니다. 따라서 브라우저에서 발생하는 보안 이슈를 해결하기 위해서는 CORS 설정을 해야합니다. 이 설정 역시 SAM에 모든 Lambda 함수에 추가할 수 있습니다. 따라서 Globals에 API 영역에 다음과 같이 추가합니다.
Globals: ... Api: # enable CORS; to make more specific, change the origin wildcard # to a particular domain name, e.g. "'www.example.com'" Cors: AllowMethods: "'*'" AllowHeaders: "'*'" AllowOrigin: "'*'" |
지금까지의 SAM을 정리하면 다음과 같습니다.
AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Description: >- Building Serverless development environment and CI/CD process for DevOps based on Cloud9 Globals: Function: Runtime: python2.7 Handler: lambda_function.lambda_handler MemorySize: 128 Timeout: 60 Environment: Variables: DB_TABLE_NAME: Ref: NewsTable SNS_TOPIC: Ref: NewsTopic BUCKET_NAME: Ref: PollyMp3Bucket Api: # enable CORS; to make more specific, change the origin wildcard # to a particular domain name, e.g. "'www.example.com'" Cors: AllowMethods: "'*'" AllowHeaders: "'*'" AllowOrigin: "'*'" Resources: NewsTable: Type: 'AWS::Serverless::SimpleTable' Properties: PrimaryKey: Name: id Type: String ProvisionedThroughput: ReadCapacityUnits: 5 WriteCapacityUnits: 5 NewsTopic: Type: 'AWS::SNS::Topic' Properties: DisplayName: NewsTopic PollyMp3Bucket: Type: 'AWS::S3::Bucket' StaticWebBucket: Type: 'AWS::S3::Bucket' Properties: AccessControl: PublicRead WebsiteConfiguration: IndexDocument: index.html ErrorDocument: error.html PostNews: Type: 'AWS::Serverless::Function' Properties: CodeUri: PostNews Description: Post news text to convert from text to speech Events: PostNewsApi: Type: Api Properties: Path: /news Method: POST Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:PutItem' - 'sns:Publish' Resource: '*' ConvertAudio: Type: 'AWS::Serverless::Function' Properties: CodeUri: ConvertAudio Description: Convert Audio using Amazon Polly Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:Query' - 'dynamodb:UpdateItem' - 's3:GetBucketLocation' - 's3:PutObject' - 's3:PutObjectAcl' - 'polly:SynthesizeSpeech' Resource: '*' Events: ConvertResource: Type: SNS Properties: Topic: Ref: NewsTopic GetNews: Type: 'AWS::Serverless::Function' Properties: CodeUri: GetNews Description: Gather information from Ajax calls from web pages Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:Query' - 'dynamodb:Scan' Resource: '*' Events: GetNewsApi: Type: Api Properties: Path: /news Method: GET DeleteNews: Type: 'AWS::Serverless::Function' Properties: CodeUri: DeleteNews Description: Delete news item in DynamoDB Table and mp3 file in S3 bucket. Policies: - Version: '2012-10-17' Statement: - Effect: Allow Action: - 'logs:PutLogEvents' - 'logs:CreateLogStream' - 'dynamodb:DeleteItem' - 's3:DeleteObject' Resource: '*' Events: DeleteNewsApi: Type: Api Properties: Path: /news Method: DELETE Outputs: S3WebBucket: Description: S3 Bucket Name for web hosting Value: Ref: StaticWebBucket WebsiteURL: Description: Name of S3 bucket to hold website content Value: 'Fn::Join': - '' - - 'https://' - 'Fn::GetAtt': - StaticWebBucket - DomainName - '/index.html' APIEndpointURL: Description: URL of your API endpoint Value: 'Fn::Sub': >- https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/news |
정적 웹 호스팅 파일 다운로드 받기
wget https://s3.ap-northeast-2.amazonaws.com/polly.awsdemokr.com/301_static_web.zip |
압축 풀고 폴더 이동
unzip 301_static_web.zip cd 301_static_web |
Cloud9에서 scripts.js 파일 열어서 CloudFormation Stack에 배포된 Output의 APIEndpointURL 값을 소스코드에 반영 (WebsiteURL이 아니므로 주의)
var API_ENDPOINT = "https://xxxxxxxxxx.execute-api.ap-southeast-1.amazonaws.com/Prod/news/"; if (API_ENDPOINT === "") { alert("scripts.js 파일의 상단에 API Gateway에 배포한 URL을 등록하고 실행하세요."); } |
정적 웹 포스팅하고자 하는 S3 버킷에 public-read 권한으로 파일을 업로드 (CloudFormation Stack에 배포된 Output의 S3WebBucket 값을 아래에 대체)
aws s3 sync . s3://cloud9-webapp-staticwebbucket-xxxxxxxxxxxx --acl public-read |
먼저 SAM 템플릿 배포를 위해서 S3 버킷을 하나 생성(예: template-deploy-hyouk2 이름을 변경)합니다. 해당 S3 버킷에 패키지를 업로드 합니다.
aws s3 mb s3://template-deploy-hyouk2 |
Cloud9 IDE 하단의 ~/environment 디렉토리에서 하단의 작업을 진행할 수 있습니다.
sam package --template-file WebApp/template.yaml --output-template-file webapp-output.yaml --s3-bucket template-deploy-hyouk2 |
template-depoly-hyouk 버킷에는 배포에 필요한 아티팩트가 들어가 있습니다. 각 람다 함수별로 패키징된 임의의 파일들이 생성되는 것을 확인할 수 있습니다.
각각의 파일은 ZIP 파일로 바로 Lambda 함수에 배포할 수 있는 코드의 묶음입니다. 직접 다운로드 해서 unzip을 하면 확인할 수 있습니다.
다음과 같이 WebAppTest 라는 새로운 스택으로 배포를 진행할 수 있습니다. webapp-outpuy.yaml 파일에는 Function의 CodeUri가 S3로 변경되어져 있는 것을 확인할 수 있습니다.
sam deploy --template-file /home/ec2-user/environment/webapp-output.yaml --stack-name WebAppTest --capabilities CAPABILITY_IAM |