iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CloudFormation

CloudFormation is AWS-native infrastructure as code. It is verbose, but it is also the lowest common denominator every AWS team understands.

CloudFormation - first stack

EXAMPLE
# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Description: Static site bucket + CloudFront + ACM cert

Parameters:
  DomainName:
    Type: String
    Description: e.g. www.example.com
  CertArn:
    Type: String
    Description: ACM cert in us-east-1

Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref DomainName
      OwnershipControls:
        Rules: [{ ObjectOwnership: BucketOwnerEnforced }]
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  OAC:
    Type: AWS::CloudFront::OriginAccessControl
    Properties:
      OriginAccessControlConfig:
        Name: !Sub '${DomainName}-oac'
        OriginAccessControlOriginType: s3
        SigningBehavior: always
        SigningProtocol: sigv4

  Distribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Aliases: [!Ref DomainName]
        DefaultRootObject: index.html
        Enabled: true
        Origins:
          - Id: s3Origin
            DomainName: !GetAtt Bucket.RegionalDomainName
            OriginAccessControlId: !Ref OAC
            S3OriginConfig: { OriginAccessIdentity: '' }
        DefaultCacheBehavior:
          TargetOriginId: s3Origin
          ViewerProtocolPolicy: redirect-to-https
          AllowedMethods: [GET, HEAD]
          CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # CachingOptimized
        ViewerCertificate:
          AcmCertificateArn: !Ref CertArn
          SslSupportMethod: sni-only

Outputs:
  BucketName:
    Value: !Ref Bucket
  DistributionId:
    Value: !Ref Distribution

# Deploy:
# aws cloudformation deploy \
#   --stack-name static-site \
#   --template-file template.yaml \
#   --parameter-overrides DomainName=www.example.com CertArn=arn:aws:acm:us-east-1:111:certificate/xxx

Why it matters

CloudFormation feels old next to Terraform or CDK - but it is the reference implementation, drift detection works, and there is nothing to install. Use it for small bounded stacks; reach for CDK or Terraform when the YAML starts hurting.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
AWSTemplateFormatVersion: '2010-09-09'
Resources:
    MyBucket:
        Type: AWS::S3::Bucket
        Properties:
            BucketName: my-bucket
Try it Yourself »

Discussion

Loading…