Summary
AWS CloudFormation의 Master Class를 보고 Reference document를 통해 내용을 살펴보자.
특징
- Infra structure as a code를 실현하기에 간편한 도구
 - 리소스를 Provisioning하고 update를 해줌
 - Code로 관리하기 때문에 버전관리에 용이
 - AWS cli 또는 AWS console을 통해 배포 및 업데이트가 가능
 - 리소스에 대해서만 과금되기 때문에 별도의 비용지출이 없음
 - Parameter를 통해 Project별로 Customizing이 용이
 - 코드만 올리면 인프라가 형성되기 때문에 인프라 도입에 대한 리소스 투입이 적음
 
Cloudformation template의 특징
- JSON, YAML 로 개발자 친화적인 포맷
 - 코드로 관리하기 때문에 재사용에 용이
 - Stack 생성시 message를 통해 feedback 제공
 - Sample template 제공
 
아래는 yaml형식의 ec2를 생성하는 sample template이다. CloudFormation으로 ec2를 생성할 때 파라미터를 받는다. instanceType, KeyName, SSHLocation을 설정할 수 있도록 되어 있다. 선택할 수 있는 인스턴스의 종류를 제한했기 때문에 t2계열의 인스턴스만 선택할 수 있다. 그리고 AMI는 Amazon linux를 사용하였다.
# EC2 sample template
AWSTemplateFormatVersion: 2010-09-09
Description: EC2 Sample
Parameters: # Using before cloudformation is being created
  KeyName:
    Description: Name of an existing EC2 KeyPair to enable SSH access to the instance. Recommend use only office IP.
    Type: 'AWS::EC2::KeyPair::KeyName'
    ConstraintDescription: must be the name of an existing EC2 KeyPair.
  InstanceType:
    Description: WebServer EC2 instance type
    Type: String
    Default: t2.small
    AllowedValues:  # allow only restricted instance
      - t2.nano
      - t2.micro
      - t2.small
      - t2.medium
      - t2.large
    ConstraintDescription: must be a valid EC2 instance type.
  SSHLocation:
    Description: The IP address range that can be used to SSH to the EC2 instances
    Type: String
    MinLength: '9'
    MaxLength: '18'
    Default: 0.0.0.0/0
    AllowedPattern: '(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})'
    ConstraintDescription: must be a valid IP CIDR range of the form x.x.x.x/x.
Mappings: # Conditional value when cloudformation is being created
  AWSInstanceType2Arch:
    t2.nano:
      Arch: HVM64
    t2.micro:
      Arch: HVM64
    t2.small:
      Arch: HVM64
    t2.medium:
      Arch: HVM64
    t2.large:
      Arch: HVM64
  AWSInstanceType2NATArch:
    t2.nano:
      Arch: NATHVM64
    t2.micro:
      Arch: NATHVM64
    t2.small:
      Arch: NATHVM64
    t2.medium:
      Arch: NATHVM64
    t2.large:
      Arch: NATHVM64
  AWSRegionArch2AMI:
    ap-northeast-2:
      PV64: NOT_SUPPORTED
      HVM64: ami-2b408b45
      HVMG2: NOT_SUPPORTED
Resources:
  EC2Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
      InstanceType: !Ref InstanceType
      SecurityGroups:
        - !Ref InstanceSecurityGroup
      KeyName: !Ref KeyName
      ImageId: !FindInMap 
        - AWSRegionArch2AMI
        - !Ref 'AWS::Region'
        - !FindInMap 
          - AWSInstanceType2Arch
          - !Ref InstanceType
          - Arch
  InstanceSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup'
    Properties:
      GroupDescription: Enable SSH access via port 22
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '22'
          ToPort: '22'
          CidrIp: !Ref SSHLocation
Outputs:
  InstanceId:
    Description: InstanceId of the newly created EC2 instance
    Value: !Ref EC2Instance
  AZ:
    Description: Availability Zone of the newly created EC2 instance
    Value: !GetAtt 
      - EC2Instance
      - AvailabilityZone
  PublicDNS:
    Description: Public DNSName of the newly created EC2 instance
    Value: !GetAtt 
      - EC2Instance
      - PublicDnsName
  PublicIP:
    Description: Public IP address of the newly created EC2 instance
    Value: !GetAtt 
      - EC2Instance
      - PublicIp
한국 유저는 Asia/seoul region cloudformation sample template 을 통해 여러 샘플들을 볼 수 있다.
다른 지역의 템플릿을 사용하고 싶으면 left bar에서 다른 region을 선택하면 된다.
AWS CLI for CloudFormation
CloudFormation은 다른 서비스와 마찬가지로 AWS Cli를 통해 사용할 수 있다. 명령어들은 아래와 같다.
# example
$ aws cloudformation update-stack help
- get-stack-policy
 - set-stack-policy
 - create-stack
 - update-stack
 - cancel-update-stack
 - delete-stack
 - list-stack-resources
 - list-stacks
 - describe-stack-events
 - describe-stack-resouce
 - describe-stack-resouces
 - describe-stacks
 - get-template
 - validate-template
 
Intrinsic functions & pseudo parameters
아래와 같은 function과 parameter를 통해 yaml형식의 파일에서 별도의 로직을 추가할 수 있다.
- Intrinsic function
- Fn::Base64
 - Fn::FindInMap
 - Fn::GetAtt
 - Fn::GetAZs
 - Fn::Join
 - Fn::Select
 - Ref
 
 - Pseudo parameters
- AWS::NotificationARNs
 - AWS::Region
 - AWS::StackId
 - AWS::StackName
 
 
위에서 EC2를 생성하는 경우에 Fn::FindInMap와 Ref과 같은 것을 사용하였는데 ref는 글자에서 느껴지듯이 reference로 특정 변수를 가리킬 때 사용한다. Fn::FindInMap은 별도로 Mapping에 두엇던 파라미터에서 값을 불러오기 위해 사용한다.
더 자세한 내용을 알고 싶다면 AWS Intrinsic function reference를 참고하도록 하자.