☁️ Cloud

CloudFormation

AWS CloudFormation

AWS's IaC service. Defines infrastructure in YAML/JSON. Manages resources in units of stacks.

📖 Detailed Explanation

AWS CloudFormation is AWS's flagship Infrastructure as Code (IaC) service that uses template files in YAML or JSON format to declaratively define and provision AWS resources.

The core concept of CloudFormation is the Stack. A stack refers to a collection of AWS resources created from a single template, and it can manage more than 1,000 AWS service resources, including VPC, EC2, RDS, and Lambda, as a single stack.

Key features:

💻 Code Example

# vpc-stack.yaml - VPC와 EC2 인스턴스 생성 템플릿
AWSTemplateFormatVersion: '2010-09-09'
Description: Production VPC with EC2 instance

Parameters:
  Environment:
    Type: String
    Default: production
    AllowedValues:
      - production
      - staging
      - development
  InstanceType:
    Type: String
    Default: t3.medium
    Description: EC2 instance type

Resources:
  # VPC 생성
  MainVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      EnableDnsSupport: true
      Tags:
        - Key: Name
          Value: !Sub ${Environment}-vpc
        - Key: Environment
          Value: !Ref Environment

  # Public Subnet
  PublicSubnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref MainVPC
      CidrBlock: 10.0.1.0/24
      AvailabilityZone: !Select [0, !GetAZs '']
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub ${Environment}-public-subnet

  # Internet Gateway
  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: !Sub ${Environment}-igw

  # EC2 Instance
  WebServer:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: !Ref InstanceType
      ImageId: ami-0c55b159cbfafe1f0
      SubnetId: !Ref PublicSubnet
      Tags:
        - Key: Name
          Value: !Sub ${Environment}-web-server

Outputs:
  VPCId:
    Description: VPC ID
    Value: !Ref MainVPC
    Export:
      Name: !Sub ${Environment}-VPCId
  WebServerPublicIP:
    Description: Public IP of web server
    Value: !GetAtt WebServer.PublicIp
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "S3 Bucket with versioning and lifecycle",

  "Parameters": {
    "BucketName": {
      "Type": "String",
      "Description": "Name of the S3 bucket"
    },
    "RetentionDays": {
      "Type": "Number",
      "Default": 90,
      "Description": "Days to retain objects"
    }
  },

  "Resources": {
    "DataBucket": {
      "Type": "AWS::S3::Bucket",
      "DeletionPolicy": "Retain",
      "Properties": {
        "BucketName": { "Ref": "BucketName" },
        "VersioningConfiguration": {
          "Status": "Enabled"
        },
        "LifecycleConfiguration": {
          "Rules": [
            {
              "Id": "ArchiveOldVersions",
              "Status": "Enabled",
              "NoncurrentVersionTransitions": [
                {
                  "StorageClass": "GLACIER",
                  "TransitionInDays": 30
                }
              ],
              "NoncurrentVersionExpiration": {
                "NoncurrentDays": { "Ref": "RetentionDays" }
              }
            }
          ]
        },
        "PublicAccessBlockConfiguration": {
          "BlockPublicAcls": true,
          "BlockPublicPolicy": true,
          "IgnorePublicAcls": true,
          "RestrictPublicBuckets": true
        }
      }
    }
  },

  "Outputs": {
    "BucketArn": {
      "Description": "S3 Bucket ARN",
      "Value": { "Fn::GetAtt": ["DataBucket", "Arn"] }
    }
  }
}
# 스택 생성
aws cloudformation create-stack \
  --stack-name production-vpc-stack \
  --template-body file://vpc-stack.yaml \
  --parameters \
    ParameterKey=Environment,ParameterValue=production \
    ParameterKey=InstanceType,ParameterValue=t3.large \
  --capabilities CAPABILITY_IAM \
  --tags Key=Project,Value=MainApp

# 스택 생성 완료 대기
aws cloudformation wait stack-create-complete \
  --stack-name production-vpc-stack

# 변경 세트 생성 (업데이트 미리보기)
aws cloudformation create-change-set \
  --stack-name production-vpc-stack \
  --change-set-name update-instance-type \
  --template-body file://vpc-stack-updated.yaml \
  --parameters \
    ParameterKey=InstanceType,ParameterValue=t3.xlarge

# 변경 세트 확인
aws cloudformation describe-change-set \
  --stack-name production-vpc-stack \
  --change-set-name update-instance-type

# 변경 세트 실행 (실제 업데이트)
aws cloudformation execute-change-set \
  --stack-name production-vpc-stack \
  --change-set-name update-instance-type

# 드리프트 감지 시작
aws cloudformation detect-stack-drift \
  --stack-name production-vpc-stack

# 드리프트 상태 확인
aws cloudformation describe-stack-drift-detection-status \
  --stack-drift-detection-id abc12345-1234-1234-1234-abc123456789

# 스택 삭제
aws cloudformation delete-stack \
  --stack-name production-vpc-stack

🗣️ Say It Like This in Practice

In an infrastructure design meeting
"We're planning to manage this microservice infrastructure with CloudFormation. If we separate the network, compute, and database layers into nested stacks, each team can manage its templates independently. We can share the VPC ID and subnet information through cross-stack references."
In an interview, in response to a question about IaC experience
"I have experience managing more than 30 stacks with CloudFormation. In particular, I used change sets to always review resource change details before production deployments, and I found resources that had been accidentally modified in the console through drift detection and synchronized them with the template."
In an incident response meeting
"During yesterday's deployment, the RDS instance type change failed and was automatically rolled back. The cause was that UpdateReplacePolicy was set to Delete, so it attempted the replacement without a snapshot. I'll change it to Retain, take a manual snapshot, and then redeploy."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Hardcoded resource names

If you hardcode S3 bucket or IAM role names, you can't create multiple environments from the same template. Use Parameters and the !Sub function: !Sub ${Environment}-data-bucket

❌

DeletionPolicy not set

If you don't set DeletionPolicy on data resources such as RDS, S3, and DynamoDB, data is permanently lost when the stack is deleted. In production, always set DeletionPolicy: Retain or Snapshot.

✅

The right way: use Change Sets

Before updating a production stack, always create a change set to review which resources will be added, modified, or deleted. In particular, changes that trigger Replacement can cause downtime, so caution is needed.

🔗 Related Terms

📚 Learn More