CloudFormation - kamialie/knowledge_corner GitHub Wiki

Content

Overview

Infrastructure as a code tool (free service). Templates are saved in S3 and can be written in JSON or YAML. Provides drift detection to find changes in infrastructure.

New AWS features are often not immediately available in CloudFormation, but its Lambda function can be used (called) to create resources that are not currently supported.

Stack is a collection of resources that can be created, updated, and deleted as a unit. Resources in a stack can also be managed individually. Parent stack can span one or multiple child stacks (created before other resources). It can also reference values from child stack that exposes them as outputs in the form of key/value pairs. StackSets allow to create, update, or delete stacks across multiple accounts and regions.

Template sections

Only resources section is mandatory. To references values from other section use Fn::Rf function and name of resource:

Properties:
  VpcId: !Ref VpcParameter
  • Format version - what format and values to expect
     AWSTemplateFormatVersion: 2010-09-09
    
  • Description - documentation and is visible after execution
     Description:
       Simple example
    
  • Metadata
  • Parameters - dynamic inputs (at run-time). AWS also provides pseudo parameters (enabled and supplied by default) - AWS:AccountId, AWS::StackName and so on.
    Parameters:
      BucketName:
        Type: String
        Default: default-value
        Description: bucket to create
    
  • Conditions - create resources or outputs based on logical statement(s). Each condition can reference another condition, parameter value or mapping.
    Conditions:
      CreateProdResources: !Equals [!Ref EnvType, prod]
    
  • Mappings - static variables in a form of map of values, e.g. region corresponding to AMI. Use Fn::FindInMap function to retrieve a value from specific key - !FindInMap [Mapname, TopLevelKey, SecondLevelKey]
    Mappings:
      RegionMap:
        us-east-1:
          "HVM64": "ami-0ff8a91507f77f867"
        us-west-1:
          "HVM64": "ami-0bdb828fd58c52235"
    
  • Transform - reference macros, re-usable code, or external code, e.g. Lambda code.
  • Resources (mandatory)
    Resources:
      ResourceName:
        Type: AWS::AWSProductName::DataTypeName
        Properties:
          [...]
    
  • Outputs - information about created resources
    Outputs:
      WebsiteURL:
        Description: URL of website
        Value:
          !GetAttr [
            "WebsiteBucket",
            "WebsiteURL"]
    

Intrinsic functions

  • Ref - when referencing resources returns physical id
  • Fn:GetAtt - get attributes of resources by passing attribute name
  • Fn:FindInMap
  • Fn:ImportValue
  • Fn:Join
  • Fn:Sub - create interpolated strings, must contain ${VariableName}
  • Condition functions:
    • Fn:If
    • Fn:Not
    • Fn:Equals

Exporting values

To share data between stacks export using Outputs block - Export field is used to set the name of the resource to be exported. Fn::ImportValue function is used to import value using this name. Exported stack can not be deleted until all references are deleted.

Exporter:

Outputs:
  SubnetId:
    Description:
    Value: !Ref Subnet
    Export:
      Name:
        Fn::Sub: ${AWS::StackName}-SubnetId

Importer:

Parameter:
  ExporterStackName:
    Type: String
SubnetId:
  Fn::ImportValue:
    Fn::Sub: ${ExporterStackName}-SubnetId

Stacks

Nested stack

Template within a template that allows re-using common resources. To updated a nested stack always update parent stack.

Resources:
  NestedStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: "https://s3.amazon.com/.../template.yaml"
      Parameters:
        Foo: "bar"

ChangeSet

The difference between currently deployed version and new template definition. Does not confirm if update will be successful.


StackSet

Create, update, or delete stacks across multiple accounts and regions. Administrator can create a StackSet, while trusted accounts can create, update, delete stack instances from a StackSet.

Operations

By default update action is allowed on all resources. Stack Policies allow protecting certain resources from changes - defined in a JSON document (similar to IAM policy). When Stack Policy is in place, all resource are protected by default, therefore, an explicit Allow policy should be in place to allow updates.

{
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "Update:*",
      "Principal": "*",
      "Resource": "*"
    }
  ]
}

Rollback

By default if stack creation fails, every rolls back (gets deleted). Optionally rollback feature can be disabled, which helps with troubleshooting - only keeps successfully created resources, failed resources are removed or rolled back, if they existed before.


Notifications

Supports SNS Topic. Notifies stack state changes, such as rollback in progress, stack being created, deleted and so on.


Drift

Drift detection doesn't support all resources (but does most). Drift detection mechanism must be triggered manually, which would show the current and expected (defined in template) results for each drifted resource.

Serverless Application Model

Extension of CloudFormation to define Serverless applications. Provides simplified syntax for defining Serverless resources, e.g. API Gateway, Lambda, etc. Also comes with its own CLI.

# Package application and upload to S3
$ sam package

# Deploy using CloudFormation
$ sam deploy

CLI

# Validate template file
$ aws cloudformation validate-template --template-body <path/to/file>

# Deploy template
$ aws cloudformation deploy --template-file <path/to/file> --stack-name <custom_name>
# Get general info on deployed stack(s)
$ aws cloudformation describe-stacks [--stack-name <custom_name>]
# Delete stack
# Doesn't return any info, run describe command to see status
$ aws cloudformation delete-stack --stack-name <custom_name>

# View outputs values
$ aws cloudformation describe-stack