122
Cloud Formation & Code Series 박선용 SA

Gaming technical workshop 박선용 솔루션즈 아키텍트

Embed Size (px)

Citation preview

Page 1: Gaming technical workshop 박선용 솔루션즈 아키텍트

Cloud Formation &

Code Series

박선용 SA

Page 2: Gaming technical workshop 박선용 솔루션즈 아키텍트

Agenda

CF Template 설계

CF를 지원하는 AWS 리소스

CF함수 살펴보기

어플리케이션 Bootstrapping

Nested Stack

Page 3: Gaming technical workshop 박선용 솔루션즈 아키텍트

Cloud Formation Template 설계

Page 4: Gaming technical workshop 박선용 솔루션즈 아키텍트

CLOUDFORMATION TEMPLATES

Familiar JSON Format

ReusableManage Relationships

Automate Generation Avoid Collisions

Provide Feedback

Write & GoLook Up Resources

Page 5: Gaming technical workshop 박선용 솔루션즈 아키텍트

CloudFormation을 이루는 구성요소

Template CloudFormation Stack

JSON 형식의 파일

Parameter 정의

Resource 생성

실제 구성 액션

구성된 AWS 서비스

포괄적인 AWS 서비스(제품) 지원

Service event aware

Customisable

프레임 워크

Stack 생성

Stack 업데이트

에러감지 및 롤백

Page 6: Gaming technical workshop 박선용 솔루션즈 아키텍트

Food Catalog website

Ordering website

Customer DB service

Inventory service

Recommendations service

Analytics service Fulfillment

service

Payment

service

각 단위 서비스(모듈)별 관계 도식화

Page 7: Gaming technical workshop 박선용 솔루션즈 아키텍트

Food Catalog website

Customer DB service

“Outputs” : {

“CustDBEndPoint”

}

“Parameters” : {

“CustDBEndPoint”

}

Depends On

“Wire”

모듈간의 선행/후행 관계 지정 및 전달 값 정의

Page 8: Gaming technical workshop 박선용 솔루션즈 아키텍트

CloudFormation 템플릿 기본구조

{"AWSTemplateFormatVersion" : "2010-09-09”

"Description" : "A text description for the template usage",

"Parameters": {// A set of inputs used to customize the template per deployment

},"Resources" : {

// The set of AWS resources and relationships between them},"Outputs" : {

// A set of values to be made visible to the stack creator},

}

Page 9: Gaming technical workshop 박선용 솔루션즈 아키텍트

EC2인스턴스를 생성하는 간단한 템플릿 예시{

"AWSTemplateFormatVersion": "2010-09-09"

"Description": "Create an EC2 instance running the latest Amazon Linux AMI.","Parameters": {

"KeyPair": {"Description": "The EC2 Key Pair to allow SSH access to the instance","Type": "String"

}},"Resources": {

"Ec2Instance": {"Properties": {

"ImageId": "ami-9d23aeea","InstanceType" : "m3.medium","KeyName": {

"Ref": "KeyPair"}

},"Type": "AWS::EC2::Instance"

}},"Outputs": {

"InstanceId": {"Description": "The InstanceId of the newly created EC2 instance","Value": {

"Ref": "Ec2Instance"}

}},

}

파라미터를 설정하여 사용자가 직접타이핑을 하거나, 선택옵션을 제공하여 특정값을 선택하도록 구성가능.

인스턴스에 사용될 KeyPair 입력 요청

Page 10: Gaming technical workshop 박선용 솔루션즈 아키텍트

{"AWSTemplateFormatVersion": "2010-09-09"

"Description": "Create an EC2 instance running the latest Amazon Linux AMI.","Parameters": {

"KeyPair": {"Description": "The EC2 Key Pair to allow SSH access to the instance","Type": "String"

}},"Resources": {

"Ec2Instance": {"Properties": {

"ImageId": "ami-9d23aeea","InstanceType" : "m3.medium","KeyName": {

"Ref": "KeyPair"}

},"Type": "AWS::EC2::Instance"

}},"Outputs": {

"InstanceId": {"Description": "The InstanceId of the newly created EC2 instance","Value": {

"Ref": "Ec2Instance"}

}},

}

지정된 속성값 (ImageID & Instance Type) 및KeyPair 파라미터 값에대한 참조를 포함.

ImageID 는 Stack을 실행하는 Region에

해당하는 것을 사용

EC2인스턴스를 생성하는 간단한 템플릿 예시

Page 11: Gaming technical workshop 박선용 솔루션즈 아키텍트

{"AWSTemplateFormatVersion": "2010-09-09"

"Description": "Create an EC2 instance running the latest Amazon Linux AMI.","Parameters": {

"KeyPair": {"Description": "The EC2 Key Pair to allow SSH access to the instance","Type": "String"

}},"Resources": {

"Ec2Instance": {"Properties": {

"ImageId": "ami-9d23aeea","InstanceType" : "m3.medium","KeyName": {

"Ref": "KeyPair"}

},"Type": "AWS::EC2::Instance"

}},"Outputs": {

"InstanceId": {"Description": "The InstanceId of the newly created EC2 instance","Value": {

"Ref": "Ec2Instance"}

}},

}

템플릿이 실행을 끝마치면 아래와 같이설정된

결과값이 반환됨

EC2인스턴스를 생성하는 간단한 템플릿 예시

Page 12: Gaming technical workshop 박선용 솔루션즈 아키텍트

Cloud Formation을 지원하는 AWS 리소스

Page 13: Gaming technical workshop 박선용 솔루션즈 아키텍트

"myVolume" : {"Type" : "AWS::EC2::Volume","Properties" : {

"Size" : "10","SnapshotId" : "snap-7b8fd361","AvailabilityZone" : "eu-west-1a"

}}

본 예시는 “myVolume”이라는 이름의 Amazon EBS 볼륨을 정의하며,

“Type” :"AWS::EC2::Volume” 로 지정합니다.

Page 14: Gaming technical workshop 박선용 솔루션즈 아키텍트

Auto Scaling

Amazon CloudFront

AWS CloudWatch

AWS Data Pipeline

Amazon DynamoDB

Amazon EC2

Amazon ElastiCache

AWS Elastic Beanstalk

AWS Elastic Load Balancing

AWS Identity and Access Management

Amazon RDS

Amazon Redshift

Amazon Route 53

Amazon S3

Amazon SNS

Amazon SQS

Amazon VPC AWS Kinesis AWS Lambda OpsWorks

지원되는 AWS Service 목록

Page 15: Gaming technical workshop 박선용 솔루션즈 아키텍트

다른 리소스의 속성값 참조하기

Page 16: Gaming technical workshop 박선용 솔루션즈 아키텍트

{ "Resources" : { "Ec2Instance" : {

"Type" : "AWS::EC2::Instance","Properties" : {

"SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],"KeyName" : "mykey","ImageId" : "ami-7a11e213”

}}, "InstanceSecurityGroup" : {

"Type" : "AWS::EC2::SecurityGroup","Properties" : {

"GroupDescription" : "Enable SSH access via port 22", "SecurityGroupIngress" : [ {

"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" :"0.0.0.0/0" } ]

}}

} }

Page 17: Gaming technical workshop 박선용 솔루션즈 아키텍트

{ "Resources" : { "Ec2Instance" : {

"Type" : "AWS::EC2::Instance","Properties" : { "SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" }, , "MyExistingSG" ],"KeyName" : "mykey", "ImageId" : "ami-7a11e213" }

}, "InstanceSecurityGroup" : {

"Type" : "AWS::EC2::SecurityGroup","Properties" : {

"GroupDescription" : "Enable SSH access via port 22", "SecurityGroupIngress" : [ {

"IpProtocol" : "tcp", "FromPort" : "22", "ToPort" : "22", "CidrIp" :"0.0.0.0/0" } ]

}}

} }

Page 18: Gaming technical workshop 박선용 솔루션즈 아키텍트

입력 값(Property) 참조하기

Page 19: Gaming technical workshop 박선용 솔루션즈 아키텍트

{"Parameters" : {

"KeyPair" : { "Description" : "The EC2 Key Pair to allow SSH access to the instance", "Type" : "String"

},"Resources" : {

"Ec2Instance" : { "Type" : "AWS::EC2::Instance","Properties" : {

"SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" }],"KeyName" : { "Ref" : "KeyPair"}, "ImageId" : "" }

},…

} }

Page 20: Gaming technical workshop 박선용 솔루션즈 아키텍트
Page 21: Gaming technical workshop 박선용 솔루션즈 아키텍트

"WordPressUser": {"Default": "admin", "Description" : "The WordPress database admin account username","Type": "String", "MinLength": "1", "MaxLength": "16", "AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*"

},

유효한 값이 입력되었는지를 검증하는 규칙생성:

Maxlength, MinLength, MaxValue, MinValue, AllowedPattern, AllowedValues

Page 22: Gaming technical workshop 박선용 솔루션즈 아키텍트

Cloud Formation 함수

Page 23: Gaming technical workshop 박선용 솔루션즈 아키텍트

Cloud Formation 기본함수 및 Pseudo 파라미터

Pseudo 파라미터

AWS::NotificationARNs

AWS::Region

AWS::StackId

AWS::StackName

기본함수

Fn::Base64

Fn::FindInMap

Fn::GetAtt

Fn::GetAZs

Fn::Join

Fn::Select

Ref

Page 24: Gaming technical workshop 박선용 솔루션즈 아키텍트

{"Mappings" : {"RegionMap" : {

"us-east-1" : { "AMI" : "ami-76f0061f" },"us-west-1" : { "AMI" : "ami-655a0a20" }, "eu-west-1" : { "AMI" : "ami-7fd4e10b" }, "ap-southeast-1" : { "AMI" : "ami-72621c20" },"ap-northeast-1" : { "AMI" : "ami-8e08a38f" } } },

"Resources" : { "Ec2Instance" : {"Type" : "AWS::EC2::Instance", "Properties" : {

"KeyName" : { "Ref" : "KeyName" }, “ImageId" : {

"Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]}}

} } } { "Fn::FindInMap" : [ ”MapName”, “ TopLevelKey” , ”SecondLevelKey”]

= Second Level에 할당되는(매핑되는) Key값 반환

Page 25: Gaming technical workshop 박선용 솔루션즈 아키텍트

"PrivateSubnet1" : {"Type" : "AWS::EC2::Subnet","Properties" : {"AvailabilityZone" : { "Fn::GetAtt" : ["PublicSubnet1",

"AvailabilityZone"] },"VpcId" : { "Ref" : "VPC" },"CidrBlock" : {"Ref": "privateSub1"},}

},

"PublicSubnet1" : {"Type" : "AWS::EC2::Subnet","Properties" : {"AvailabilityZone" :{ "Fn::Select" : [ "0", {"Ref" :

"pAZSeclection"}]},"VpcId" : { "Ref" : "VPC" },"CidrBlock" : {"Ref": "pubSUB1"},"Tags" : [{"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} },{"Key" : "Network", "Value" : "Public" }

]}

},

{ "Fn::GetAtt" : [ "logicalNameOfResource", "attributeName" ]} = attribute value

{ "Fn::Select" : [ index, listOfObjects ] } = List 에서 Index에 의해 선택된 값반환

Page 26: Gaming technical workshop 박선용 솔루션즈 아키텍트

"ElasticLoadBalancer" : {"Type" : "AWS::ElasticLoadBalancing::LoadBalancer","Properties" : {

"AvailabilityZones" : { "Fn::GetAZs" : "" },"CrossZone" : "true","Listeners" : [ {

"LoadBalancerPort" : "80","InstancePort" : "80","Protocol" : "HTTP"

} ],

"Outputs" : {

"URL" : {"Description" : "URL of the website","Value" : { "Fn::Join" : [ "", [ "http://", { "Fn::GetAtt" : [ "ElasticLoadBalancer", "DNSName"

]}]]}

{ "Fn::GetAZs" : ”region” } = 해당 리젼의 모든 AZ 정보 반환

{ "Fn::Join" : [“:”, [“a”, “b”, “c”]] } = “a:b:c” 의 형태로 반환

Page 27: Gaming technical workshop 박선용 솔루션즈 아키텍트

어플리케이션 Boot Strapping

Page 28: Gaming technical workshop 박선용 솔루션즈 아키텍트

"Resources" : {"Ec2Instance" : {

"Type" : "AWS::EC2::Instance","Properties" : {"KeyName" : { "Ref" : "KeyName" },"SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],"ImageId" : { "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]},"UserData" : { "Fn::Base64" : { "Fn::Join" : ["",[

"#!/bin/bash -ex","\n","yum -y install gcc-c++ make","\n","yum -y install mysql-devel sqlite-devel","\n","yum -y install ruby-rdoc rubygems ruby-mysql ruby-devel","\n","gem install --no-ri --no-rdoc rails","\n","gem install --no-ri --no-rdoc mysql","\n","gem install --no-ri --no-rdoc sqlite3","\n","rails new myapp","\n","cd myapp","\n","rails server -d","\n","curl -X PUT -H 'Content-Type:' --data-binary '{\"Status\" : \"SUCCESS\",",

"\"Reason\" : \"The application myapp is ready\",","\"UniqueId\" : \"myapp\",","\"Data\" : \"Done\"}' ",

"\"", {"Ref" : "WaitForInstanceWaitHandle"},"\"\n" ]]}}}

}

옵션 1: AWS::EC2::Instance 리소스의 Property로제공되는 EC2-Userdata 사용

Page 29: Gaming technical workshop 박선용 솔루션즈 아키텍트

cfn-hup

cfn-signal

cfn-get-metadata

Amazon EC2AWS CloudFormation

cfn-init

Metadata Key — AWS::CloudFormation::Init

Cfn-init 에서 메타데이터 키를 읽어서 정의된 패키지들을(e.g, httpd, mysq & PhP) 설치

옵션 2: AWS CloudFormation 에서 제공하는 Helper Script사용

AMAZON Linux AMI에 기본 설치 (/opt/aws/bin)

타 Linux 의 경우 Amazon Repository를 통해 설치가능

Page 30: Gaming technical workshop 박선용 솔루션즈 아키텍트

"Resources" : {"WebServer": {

"Type": "AWS::EC2::Instance","Metadata" : {"Comment1" : "Configure the bootstrap helpers to install the Apache Web Server and PHP","Comment2" : "The website content is downloaded from the CloudFormationPHPSample.zip file",

"AWS::CloudFormation::Init" : {"config" : {

"packages" : {"yum" : {

"mysql" : [],"mysql-server" : [],"mysql-libs" : [],"httpd" : [],"php" : [],"php-mysql" : []

}},

"sources" : {"/var/www/html" : "https://s3.amazonaws.com/cloudformation-examples/CloudFormationPHPSample.zip"

}}

}}

Page 31: Gaming technical workshop 박선용 솔루션즈 아키텍트

"Properties": {"ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" },

{ "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] },"InstanceType" : { "Ref" : "InstanceType" },"SecurityGroups" : [ {"Ref" : "WebServerSecurityGroup"} ],"KeyName" : { "Ref" : "KeyName" },"UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [

"#!/bin/bash -v\n","yum update -y aws-cfn-bootstrap\n", //AMAZON AMI에 기본 설치되어 있지만 항상 최신의 Script를 위해 수행 설정

"# Install packages\n","/opt/aws/bin/cfn-init -s ", { "Ref" : "AWS::StackName" }, " -r WebServer "," --region ", { "Ref" : "AWS::Region" }, " || error_exit 'Failed to run cfn-init'\n"

]]}} }

},

“UserData“ 키를 사용하여 Shell명령어를 실행

예시) 아래 템플릿은 두 개의 Shell명령어를 실행시킴:

1) CF 의 Helper Script들을 설치하도록 명령

2) cfn-init을 실행시킴

Page 32: Gaming technical workshop 박선용 솔루션즈 아키텍트

"files" : {"/tmp/setup.mysql" : {

"content" : { "Fn::Join" : ["", ["CREATE DATABASE ", { "Ref" : "DBName" }, ";\n","GRANT ALL ON ", { "Ref" : "DBName" }, ".* TO '", { "Ref" : "DBUsername" },

"'@localhost IDENTIFIED BY '", { "Ref" : "DBPassword" }, "';\n"]]},

"mode" : "000644","owner" : "root","group" : "root"

}}

“Files” 키를 사용하여 인스턴스의 파일 시스템에 직접 쓸 수 있도록 설정

Page 33: Gaming technical workshop 박선용 솔루션즈 아키텍트

"services" : {"sysvinit" : {

"mysqld" : { "enabled" : "true", "ensureRunning" : "true" },"httpd" : { "enabled" : "true", "ensureRunning" : "true" },"cfn-hup" : { "enabled" : "true", "ensureRunning" : "true“ }

}}

“Services” 키를 사용하면 cfn-init 를 통해 설치된 서비스들에 대한

동작과, 재 부팅 시에 자동으로 시작하도록 설정가능

More on Deploying Applications with AWS CloudFormation: docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/deploying.applications.html

Page 34: Gaming technical workshop 박선용 솔루션즈 아키텍트

cfn-init을 사용하여 인스턴스의 구성 자동화

"Resources" : {

"WebServer": {

"Type": "AWS::EC2::Instance",

"Metadata" : {

"AWS::CloudFormation::Init" : {

"config" : {

"packages" : {

"httpd" : ["2.4.12"]

}

"commands" : {

"WriteDemoToFile" : {

"command" : "echo \"Demo\" > test.txt"

}

}

},

"UserData" : {

"/opt/aws/bin/cfn-init -s<stackID>

-r<ResourceID> --region <Region>"

}

1. Packages

2. Groups

3. Users

4. Sources

5. Files

6. Commands

7. Services

Page 35: Gaming technical workshop 박선용 솔루션즈 아키텍트

cfn-init 의 동작방식

instancestack

#> cfn-init-–stack <stackname>--resource <resourcename>

"AWS::CloudFormation::Init" : {

"config" : {

"packages" : {

"httpd" : ["2.4.12"]

}

"commands" : {

"WriteDemoToFile" : {

"command" : "echo \"Demo\" > test.txt"

}

}

}

}

메타 데이터를읽어서 정의된동작 수행

AWS CloudFormation

Page 36: Gaming technical workshop 박선용 솔루션즈 아키텍트

creationPolicy 를 통해 인스턴스 설정상황 공지

"Resources" : {

"WebServer": {

"Type": "AWS::EC2::Instance",

"CreationPolicy": {

"ResourceSignal": {

"Count": "1",

"Timeout": "PT15M"

}

}

},

"Metadata" : {

"UserData" : {

"/opt/aws/bin/cfn-signal –-stack <stackID>

--resource <ResourceID> --success"

}

}

• EC2 인스턴스 또는 Auto Scaling Group의 속성

• 설정이 완료되면 CloudFormation 에게 공지

Page 37: Gaming technical workshop 박선용 솔루션즈 아키텍트

creationPolicy 를 통해 인스턴스 설정상황 공지

• EC2 인스턴스 또는 Auto Scaling Group의 속성

• 설정이 완료되면 CloudFormation 에게 공지

"Resources" : {

"WebServer": {

"Type": "AWS::EC2::Instance",

"CreationPolicy": {

"ResourceSignal": {

"Count": "1",

"Timeout": "PT15M"

}

}

},

"Metadata" : {

"UserData" : {

"/opt/aws/bin/cfn-signal –-stack <stackID>

--resource <ResourceID> --success"

}

}

Page 38: Gaming technical workshop 박선용 솔루션즈 아키텍트

creationPolicy 의 동작방식

#> cfn-signal --success--stack <stackname>--resource <resourcename>

완료 신호 전송

"AWS::CloudFormation::Init" : {

"config" : {

"packages" : {

"httpd" : ["2.4.12"]

}

"commands" : {

"WriteDemoToFile" : {

"command" : "echo \"Demo\" > test.txt"

}

}

}

}

instancestackAWS CloudFormation

Page 39: Gaming technical workshop 박선용 솔루션즈 아키텍트

waitCondition 을 통해 인스턴스 설정시간 보장

"Resources" : {

“WaitHandle”:{"Type" : "AWS::CloudFormation::WaitConditionHandle",}

"WaitCondition" : {"Type" : "AWS::CloudFormation::WaitCondition","DependsOn" : "WebServer","Properties" : {"Handle" : {"Ref" : "WaitHandle"},"Timeout" : "600"}

},

"WebServer": {"Type": "AWS::EC2::Instance","Metadata" : {"UserData" : {"/opt/aws/bin/cfn-signal –success <WailHandle>"}

}

개별적인 Resource

Page 40: Gaming technical workshop 박선용 솔루션즈 아키텍트

WaitCondition

Resource"Count": "2"

Instance AstackAWS

CloudFormation

Instance B

#> cfn-signal

–-success

<URL>

#> cfn-signal

–-success

<URL>

waitCondition 을 통해 인스턴스 설정시간 보장

완료 신호 전송

Page 41: Gaming technical workshop 박선용 솔루션즈 아키텍트

CF로 설정한 인프라에 대한 버전관리

Users

Web Server RDS Database

security group security groupRoute 53

Page 42: Gaming technical workshop 박선용 솔루션즈 아키텍트

기존 템플릿 변경 또는 새로

템플릿 생성 <모든 리소스는 그대로

존재해야 함 >

Infrastructure as Code: 버전관리 시스템으로 관리

사용되는 코드 저장

Git, Subversion, etc

템플릿을 업데이트<변경>후 기존 Stack에 적용

Page 43: Gaming technical workshop 박선용 솔루션즈 아키텍트

스택 Resource 업데이트 방식

새로운 resources 추가 및 기존 Resource 삭제

추가, 수정, 삭제 가능

Properties of existing resources.

Attributes for resources

Mapping declarations.

Output value declarations.

Update with No Interruption Update with Some Interruption Replacement

* Update에 따른 Resource별 영향도는 아래의 3가지로 분류

Page 44: Gaming technical workshop 박선용 솔루션즈 아키텍트

Resource의 특성상 새로운 Resource생성 필요시

Page 45: Gaming technical workshop 박선용 솔루션즈 아키텍트

스택 삭제시 Resource 삭제 설정 :DeletionPolicy

"Resources" : {

"myS3Bucket" : {

"Type" : "AWS::S3::Bucket",

"DeletionPolicy" : "Retain"

}

}

Default 설정 : Delete

Page 46: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS Code 시리즈

Page 47: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS 코드 시리즈

CodeCommit CodePipeline CodeDeploy

Page 48: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeCommit

© 2015, Amazon Web Services, Inc. or its affiliates. All rights reserved

Page 49: Gaming technical workshop 박선용 솔루션즈 아키텍트

What is Code Commit?

AWS CodeCommit is a secure, highly scalable, managed

source control service that hosts private Git repositories.

AWS CodeCommit eliminates the need for you to manage

your own source control system or worry about scaling its

infrastructure. You can use AWS CodeCommit to store

anything from code to binaries. It supports the standard

functionality of Git, so it works seamlessly with your

existing Git-based tools.

Page 50: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodeCommit - AWS의 코드 리비전 컨트롤서비스

AZ를 통한 데이터 이중화

데이터 암호화

AWS IAM과 통합

무한 확장 (Repo 크기제한 없음)

Git 명령을 지원하는 기존 도구와의 호환

(Visual Studio, Jenkins, Asana, ZenDesk, Jira, Eclipse, etc.)

git push CodeCommit

Git objects

in Amazon S3

Git index

in Amazon

DynamoDB

Encryption key

in AWS KMS

SSH or HTTPS

Secure, scalable, and managed Git source control

Page 51: Gaming technical workshop 박선용 솔루션즈 아키텍트

What is GIT?

분산형 소스 컨트롤 시스템

오픈소스, 무료 (GNU GPL V2)

Linus Torvalds 에 의해 개발

속도와 효율성에 초점을 맞춤

Page 52: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeCommit – Git: Repositories

저장소는 문서, 소스코드 및 바이너리

파일과 같은 자산을 저장하는 데이터 구조

AWS CodeCommit은 Cloud 저장소를

관리하고, 개발자는 해당 파일을 변경할 수

있도록 그 저장소를 복제할 수 있음

로컬 저장소는 개발자가 로컬 작업을 수행할

수 있도록 지원

My

Local Repo

Albert’s

Local Repo

Stephan’s

Local Repo

Suzi’s

Local Repo

Remote Repository

Page 53: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeCommit – Git: Branching

Branching 은 원본 객체를 여러개로

복제해서 병렬로 여러가지

변경사항들을 적용할 수 있도록

하는것임

Merging 은 각각 수행되던

Branch들을 다시 하나의 원본으로

통합하는것

Page 54: Gaming technical workshop 박선용 솔루션즈 아키텍트

Git 과 동일한 사용자 인터페이스$ git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/aws-cli

Cloning into 'aws-cli'...

Receiving objects: 100% (16032/16032), 5.55 MiB | 1.25 MiB/s, done.

Resolving deltas: 100% (9900/9900), done.

Checking connectivity... done.

$ nano README.rst

$ git commit -am 'updated README'

[master 4fa0318] updated README

1 file changed, 1 insertion(+)

$ git push

Counting objects: 3, done.

Delta compression using up to 4 threads.

Compressing objects: 100% (3/3), done.

Writing objects: 100% (3/3), 297 bytes | 0 bytes/s, done.

Total 3 (delta 2), reused 0 (delta 0)

remote:

To https://git-codecommit.us-east-1.amazonaws.com/v1/repos/aws-cli

4dacd6d..4fa0318 master -> master

Page 55: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeCommit – Git: 기본 사용절차

1 저장소 생성

2 로컬로 복제

3 Commit

4 Push

Page 56: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodeCommit 저장소 생성

$ aws codecommit create-repository --repository-name MyDemoRepo --repository-description "My demonstration repository"

01 Run the create-repository command, specifying a name that uniquely

identifies the AWS CodeCommit repository, and an optional

description.

Page 57: Gaming technical workshop 박선용 솔루션즈 아키텍트

로컬 저장소 복제(Clone)

$ git clone https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo my-demo-repo

01 Set up a local repo on your local machine to connect to your AWS

CodeCommit repository

$ git config --local user.name “user-name”

02 Change to your newly-created directory, and configure your

username and email for this repository

$ git config --local user.email “email-address”

Page 58: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodeCommit 살펴보기 : Commits

Changes made to files in a local repository can be

committed to CodeCommit. By committing your

changes, you allow other collaborators to pull down

those changes, merging them with their own.

Page 59: Gaming technical workshop 박선용 솔루션즈 아키텍트

Create a Commit

$ git add myfile.txt

01 Using a text editor, create a simple file to add to your repository.

You’ll create and save the file into your repo directory. Then, run gitadd to stage the change to your local repo.

$ git commit myfile.txt

02 Run git commit to commit the change to your local repo.

Page 60: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodeCommit 살펴보기 : Pushes

A push is the act of sending the changes made in

your local repository to your AWS CodeCommit

repository.

Page 61: Gaming technical workshop 박선용 솔루션즈 아키텍트

Push your first commit

$ git push –u origin master

01 From the command line, issue the git push command, pushing to

the default remote name (master) that Git uses for your AWS

CodeCommit repository.

Page 62: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodeCommit 살펴보기 : Pulls

A pull is the act of retrieving changes from a repot CodeCommit

repository, and incorporating them into your local repository.

Page 63: Gaming technical workshop 박선용 솔루션즈 아키텍트

Pull remote files into your local repo

$ git pull

01 From the command line, issue the git pull command, which will

bring in any files added by other contributors into your repository.

Page 64: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeDeploy

© 2015, Amazon Web Services, Inc. or its affiliates. All rights reserved

Page 65: Gaming technical workshop 박선용 솔루션즈 아키텍트

왜 Deployment 서비스를 사용하는가?

배포 자동화 복잡성관리

다운타임최소화

Page 66: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeDeploy – Overview

효율적으로 서버들에 코드를 배포

높은 확장성 및 신뢰성

유연성:

애플리케이션/언어에 상관없이

Windows or Linux

EC2 or on-premises

헬스체크를 통한 “Smart” 배포

Amazon S3, AWS CodeCommit(예정), Git, AWS CodePipeline,

ELB, Auto-Scaling 등과 통합

Page 67: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodeDeploy

1개에서 수 천개의 인스턴스 까지 확장

다운타임 없이 구성

중앙에서 관리 및 모니터링 되는 Deployment

Staging

CodeDeployv1, v2, v3

Production

Dev

Coordinate automated deployments, just like Amazon

Application

revisions

Deployment groups

Page 68: Gaming technical workshop 박선용 솔루션즈 아키텍트

어떻게 동작하는지..

Application: 언어의 종류에 상관없는 리비전 컨테이너

Revision: 아카이브에 포함됨 애플리케이션의 버전

지원되는 저장소:

S3

CodeCommit : (예정)

GitHub

Page 69: Gaming technical workshop 박선용 솔루션즈 아키텍트

쉽게말해 이렇게..

Page 70: Gaming technical workshop 박선용 솔루션즈 아키텍트

어플리케이션

• 리비전을 인스턴스에 적용하기 전에 반드시 어플리케이션을생성해야 함

Page 71: Gaming technical workshop 박선용 솔루션즈 아키텍트

인스턴스

• 지원되는 인스턴스 Amazon Linux . Ubuntu.

Windows.

• 인스턴스 세팅 Cloudformation Template. 새로운 인스턴스 구성 기존 인스턴스 사용

Page 72: Gaming technical workshop 박선용 솔루션즈 아키텍트

인스턴스구성

인스턴스에 CodeDeploy 에이전트 설치

인스턴스 Tag.

IAM인스턴스 프로파일이 포함된 Instance 론칭

서비스 Role 생성

Page 73: Gaming technical workshop 박선용 솔루션즈 아키텍트

에이전트 (Agent)

Deployment 수행

설정 가능한 Agent

리비전과 로그 아카이빙

Deployment 삭제(정리)

Agent Agent

Agent Agent

Agent

Agent

Page 74: Gaming technical workshop 박선용 솔루션즈 아키텍트

Deployment 그룹

• Deployment group identifies Tag를통해인스턴스식별

AutoScaling Group을통해식별

두가지모두사용

Agent Agent

Agent Agent

Agent

Agent

Deployment Group

Page 75: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeDeploy – Deployment Group

리비전이 배포될 인스턴스의 그룹

Auto-Scaling 과 Tag 에 통합

Dev/QA/Prod 환경에 대한 이상적인 구조

Application

Revision 1

Revision 2

Revision 3

.

.

Revision n

.

Deployments

Deployment

Configuration

Deployment Group

Instance 1

Instance 2

Instance 3

.

.

Instance m

.Specification

File

Goal Design Develop Deploy TestRun and

Monitor

Deploy Test

Deploy Test

Run and

Monitor

Run and

Monitor

Dev

QA

Prod

Page 76: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeDeploy – Deployment

배포 그룹에 리비전을 배포하는 행위

Tag 통합

Auto-Scaling 통합

Auto-Scaling group에 포함된 모든 인스턴스에 배포

Auto-Scaling에 의해 생성된 새로운 인스턴스에 배포

Roll Back

이전 버전을 배포

Page 77: Gaming technical workshop 박선용 솔루션즈 아키텍트

Deployment 그룹

Agent Agent

Agent Agent

Agent

Agent

Deployment Group

Deployment

Page 78: Gaming technical workshop 박선용 솔루션즈 아키텍트

Deployment 구성

Deployment가 어떻게진행될지 결정

다운타임 없는 Deployment 구성

Page 79: Gaming technical workshop 박선용 솔루션즈 아키텍트

v2 v1 v1 v1 v1 v1 v1 v1

v2 v2 v1 v1 v1 v1 v1 v1

v2 v2 v2 v2 v1 v1 v1 v1

v2 v2 v2 v2 v2 v2 v2 v2

One-at-a-timeMin. healthy hosts = 99%

[Custom]Min. healthy hosts = 75%

Half-at-a-timeMin. healthy hosts = 50%

All-at-onceMin. healthy hosts = 0

Deployment 구성

Page 80: Gaming technical workshop 박선용 솔루션즈 아키텍트

리비전

리비전은 Deploy하고자 하는 소스나 스크립트의 특정버전을 포함하고 있음

Deployment를 위한 리비전 준비 리비전 계획 리비전에 AppSpec 파일 추가 리비전을 Amazon S3 나 GitHub로 푸시 리비전 Deploy

여러 리비전들이 같은 인스턴스에 Deploy될수도 있고 하나의리비전이 여러 인스턴스들에 Deploy될 수도 있음

Page 81: Gaming technical workshop 박선용 솔루션즈 아키텍트

리비전에 AppSpec 파일 추가

CodeDeploy 는 AppSpec 파일을 통해 리비전을Deploy하며 무엇을 언제 할지 결정함

개별 리비전은 오직 하나의 AppSpec 파일만을 가져야 함

파일 이름은 appspec.yml 이어야 함

AppSpec 파일이 리비전의 Root 디렉토리에 추가되어야 함

Page 82: Gaming technical workshop 박선용 솔루션즈 아키텍트

Application Specification File

Application Specification File (AppSpec file) 은 YAML 포멧의 파일

Hooks appspec.yml 샘플

Page 83: Gaming technical workshop 박선용 솔루션즈 아키텍트

Agent

Lifecycle Events

Page 84: Gaming technical workshop 박선용 솔루션즈 아키텍트

Lifecycle Events

ApplicationStop

Agent

Page 85: Gaming technical workshop 박선용 솔루션즈 아키텍트

ApplicationStop

BeforeInstall

Agent

Lifecycle Events

Page 86: Gaming technical workshop 박선용 솔루션즈 아키텍트

ApplicationStop

BeforeInstall

AfterInstallAgent

Lifecycle Events

Page 87: Gaming technical workshop 박선용 솔루션즈 아키텍트

AfterInstall

ApplicationStart

ApplicationStop

BeforeInstall

Agent

Lifecycle Events

Page 88: Gaming technical workshop 박선용 솔루션즈 아키텍트

AfterInstall

ApplicationStart

ValidateService

ApplicationStop

BeforeInstall

Agent

Lifecycle Events

Page 89: Gaming technical workshop 박선용 솔루션즈 아키텍트

ApplicationStop

BeforeInstall

AfterInstall

ApplicationStart

ValidateService

DownloadBundle

Install

Agent

Start

End

Lifecycle Events

Page 90: Gaming technical workshop 박선용 솔루션즈 아키텍트

ApplicationStop

BeforeInstall

AfterInstall

ApplicationStart

ValidateService

DownloadBundle

Install

Agent

Start

End

Lifecycle Events

Page 91: Gaming technical workshop 박선용 솔루션즈 아키텍트

Step 1: Package your application (with an AppSpecfile)

version: 0.0os: linuxfiles:

- source: chef/destination: /etc/chef/codedeploy

- source: target/hello.wardestination: /var/lib/tomcat6/webapps

hooks:ApplicationStop:- location: deploy_hooks/stop-tomcat.sh

BeforeInstall:- location: deploy_hooks/install-chef.sh

AfterInstall:- location: deploy_hooks/librarian-install.sh

ApplicationStart:- location: deploy_hooks/chef-solo.sh

ValidateService:- location: deploy_hooks/verify_service.sh

Page 92: Gaming technical workshop 박선용 솔루션즈 아키텍트

Step 2: Set up your target environments

Agent Agent Agent

Staging

Agent Agent

Agent Agent

Agent

Agent

Production

Deployment groupDeployment group

인스턴스 그룹핑

• Auto Scaling group

• Amazon EC2 tag

• On-premises tag

Page 93: Gaming technical workshop 박선용 솔루션즈 아키텍트

Step 3: Deploy!

aws deploy create-deployment \

--application-name MyApp \

--deployment-group-name TargetGroup \

--s3-location bucket=MyBucket,key=MyApp.zip

AWS CLI & SDKs

AWS Console

CI / CD Partners

GitHub

Page 94: Gaming technical workshop 박선용 솔루션즈 아키텍트

리비전푸시(Push)

어플리케이션의 소스 컨텐츠 폴더를 아카이브 파일로묶음 (tar, tar.gz or zip).

Tar 나 압축된 tar 는 Windows 에서 지원되지 않음

Archive 파일을 S3 나 GIT Hub 저장소로 업로드

Page 95: Gaming technical workshop 박선용 솔루션즈 아키텍트

리비전 Deploy

• 리비전 Deploy를 위해 CLI또는콘솔 사용가능

aws deploy create-deployment --application-name WordPress_App --

deployment-config-name CodeDeployDefault.OneAtATime --deployment-

group-name WordPress_DG --description "My demo deployment" --s3-

location

bucket=CodeDeployDemoBucket,bundleType=zip,eTag=dd56cfd59d434b8e

768f9d77fEXAMPLE,key=WordPressApp.zip

Page 96: Gaming technical workshop 박선용 솔루션즈 아키텍트

Deployment 설정– 속도 선택

v2 v1 v1 v1 v1 v1 v1 v1

v2 v2 v2 v2 v1 v1 v1 v1

v2 v2 v2 v2 v2 v2 v2 v2

한번에 하나씩

한번에 절반적용

한번에 모두 적용

Page 97: Gaming technical workshop 박선용 솔루션즈 아키텍트

롤링 업데이트 – 다운타임 없이 Deploy

v1v1 v1

Load Balancer

Page 98: Gaming technical workshop 박선용 솔루션즈 아키텍트

v1v2 v1

Load Balancer

롤링 업데이트 – 다운타임 없이 Deploy

Page 99: Gaming technical workshop 박선용 솔루션즈 아키텍트

v2v2 v1

Load Balancer

롤링 업데이트 – 다운타임 없이 Deploy

Page 100: Gaming technical workshop 박선용 솔루션즈 아키텍트

v2v2v2

Load Balancer

롤링 업데이트 – 다운타임 없이 Deploy

Page 101: Gaming technical workshop 박선용 솔루션즈 아키텍트

v2v2 v2

Load Balancer

롤링 업데이트 – 다운타임 없이 Deploy

Page 102: Gaming technical workshop 박선용 솔루션즈 아키텍트

Health Tracking – Catch deployment problems

v2v2 v2

Load Balancer

Page 103: Gaming technical workshop 박선용 솔루션즈 아키텍트

v3 v2 v2Stop

Load Balancer

Health Tracking – Catch deployment problems

Page 104: Gaming technical workshop 박선용 솔루션즈 아키텍트

v2v2 v2

Load Balancer

Rollback

Health Tracking – Catch deployment problems

Page 105: Gaming technical workshop 박선용 솔루션즈 아키텍트

v2v2 v2

Load Balancer

Health Tracking – Catch deployment problems

Page 106: Gaming technical workshop 박선용 솔루션즈 아키텍트

Deployment 롤백

이전 리비전을 다시 Deploy

자동 롤백(Rollback)과 같은 기능은 지원되지 않음

이전 리비전을 다시 Deploy함으로서 Rollback의 형태구현

Page 107: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS 서비스 통합

Auto Scaling – 리비전을 Auto Scaling 그룹에 적용

CloudTrail - CodeDeploy API 호출을 캡쳐

CodePipeline – 전체 오케스트레이션의 한 부분으로서

Deployment 트리거

Elastic Load Balancer –리비전을 로드 벨런서에 등록된

인스턴스들에 Deploy 하는것을 조율

Lambda - Lambda에서 CodeDeploy를 호출

CodeCommit - CodeCommit 저장소에 있는 리비전을 Deploy

Page 108: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeBuild

© 2015, Amazon Web Services, Inc. or its affiliates. All rights reserved

Page 109: Gaming technical workshop 박선용 솔루션즈 아키텍트

Introducing AWS CodeBuild (IAD, PDX, DUB)

Fully managed build service that compiles source code, runs tests,

and produces software packages that are ready to deploy.

Fully Managed Build

Service

Eliminates the need to set up,

patch, update, and manage your

own build servers and software

Pay as You Go

You are charged based on the

number of minutes it takes to

complete your build

=

No more paying for idle build

server capacity

Continuous Scaling

Immediately processes each

build request

+

Runs builds concurrently

=

No more queues

Page 110: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeBuild Key Features

• Build & test code• Support for Java, Python, Node.js, Ruby, Go, Android,

Docker, Windows (coming soon)

• Install your own build tools and language runtimes

• Configurable build settings• Specify build commands

• Three compute types based on memory and CPU

• Source integrations (GitHub, AWS CodeCommit, Amazon S3)

• Enables Continuous Integration & Delivery (CI/CD)

Page 111: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodeBuild pricing

• Per minute pricing based on:

• Build Duration: Minutes for your build to complete

• Compute Type: Three options depending on your needs

Free Tier: 100 build minutes of build.general1.small per month

Does not automatically expire at the end of the 12-month free tier

Compute instance type Memory (GB) vCPUPrice per build

minute ($)

build.general1.small 3 2 0.005

build.general1.medium 7 4 0.010

build.general1.large 15 8 0.020

Page 112: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodePipeline

© 2015, Amazon Web Services, Inc. or its affiliates. All rights reserved

Page 113: Gaming technical workshop 박선용 솔루션즈 아키텍트

배포 자동화 서비스를 왜 사용하는가?

워크플로우자동화

빠른 배포 품질 보장

Page 114: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodePipeline 이란 무엇인가?

A continuous delivery and release

automation service that aids smooth

deployments.

Provides the capability to set up configurable

gates between each stage such as time-based

rules or manual approvals

Workflows can be created to run unit and

integration tests before deploying to production

Bamboo 또는 Jenkins와 유사

Page 115: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodePipeline

개별 설정 가능한 워크플로우 엔진

파트너 및 개별 시스템들과 통합

비주얼 에디터 및 상태 확인

Continuous delivery and release automation, just like Amazon

Build

1) Build

2) Unit test

1) Deploy

2) UI test

Source Beta Production

1) Deploy

2) Load test

Gamma

1) Deploy region1

2) Deploy region2

3) Deploy region3

Page 116: Gaming technical workshop 박선용 솔루션즈 아키텍트

CodePipeline

Delivery and Release를 조율: 커스텀 릴리즈 워크플로우 모델링

자동화

파일프라인 상태를 시각적으로 모니터링

그러므로…: 사이클을 가속화 (integration, deployment, delivery)

과정과 결과의 일관성을 보장

AWS 및 3rd party tool 과의 통합

Page 117: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodePipeline – Console / 실행 Flow

Page 118: Gaming technical workshop 박선용 솔루션즈 아키텍트

AWS CodePipeline – 다양한 파트너 솔루션 연동

GitHub : Github Repository 를 Source로 사용 Jenkins : CodePipeline Plugin을 사용하여 Build 또는 Code 테스트진행

Cloudbees: Cloudbee Jenkins와 연동하여 Build 또는 Code 테스트진행(SaaS)

Apica : Apica의 load testing 툴과 연동하여 배포 전 테스트 수행 BlazeMeter : Jmeter, API Test 등의 테스트 수행하며 실패시 배포중지

Ghost Inspector : SaaS 기반의 UI Testing 서비스 와 연동 Runscope: API 테스트 서비스 XebiaLabs : 다양한 플랫폼을 지원하는 배포 서비스

Page 119: Gaming technical workshop 박선용 솔루션즈 아키텍트
Page 120: Gaming technical workshop 박선용 솔루션즈 아키텍트

Use Case 1: Without AWS Code Services

Amazon S3

Pro

d -

subnet

Webserver

Appserver

Amazon RDS

ELB

Pro

duction

Dev

-subnet

Auto Scaling group

Webserver

Auto Scaling group

Appserver

Amazon RDS

ELB

Develo

pm

ent

Test -

subnet

Web server

Appserver

Amazon RDS

ELB

Test

CI/CDServer

Project mgtTicketingServerΩ

Amazon RDS

VersionControl

Shared Service Subnet

AutomationMaster

Page 121: Gaming technical workshop 박선용 솔루션즈 아키텍트

Use Case 2: Using AWS Code Services

Amazon S3

Pro

d -

subnet

Webserver

Appserver

Amazon RDS

ELB

Dev

-subnet

Auto Scaling group

Webserver

Auto Scaling group

Appserver

Amazon RDS

ELB

Test -

subnet

Web server

Appserver

Amazon RDS

ELB

CodePipleline CodeDeployCodeCommit

Services- Highly available CloudWatch alarm

CloudTrail

CloudFormation

Elastic

Beanstalk

Project mgtTicketingServer

Page 122: Gaming technical workshop 박선용 솔루션즈 아키텍트