> For the complete documentation index, see [llms.txt](https://ysfang82.gitbook.io/development-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ysfang82.gitbook.io/development-notes/aws-notes/service/deployment/cloudformation.md).

# CloudFormation

**Introduction**

* IaC in AWS
* Portability of stacks across multiple accounts and regions
* Backbone of:
  * Elastic Beanstalk
  * Service Catalog
  * SAM (Serverless Application Model) framework

**Feature**

* CloudFormation with ASG
  * CloudFormation manages the ASG, not the underlying EC2
  * Can define "success condition" for the lauch of EC2 instances useing a `CreationPolicy`
  * Can define "update strategies" for the update of EC2 instances using an `UpdatePolicy`
  * To update the underlying EC2 in an ASG, you have to create a new launch configuration / launch template & use an `UpdatePolicy`
* Retain data on deletes
  * Can put a `DeletionPolicy` on any resource to control what happens when the CloudFormation template is deleted.
  * `DeleteionPolicy` Options:
    * `Retain`
      * Specify on resources to preserve / backup in case of CloudFormation deletes
      * To keep a resource, specify Retain (works for any resource / nested stack)
    * `Snapshot`
      * EBS Volume
      * ElastiCache Cluster / ReplicationGroup
      * RDS Cluster / Instance
      * Redshift Cluster
    * `Delete` (default mostly)
      * RDS Cluster default policy: Snapshot
      * S3 bucket must be empty to perform deletion
* IAM
  * Permission for execution options:
    * With your IAM permission
    * Assign an IAM Role to the stack to perform actions
  * Creating IAM resources
    * Need to explicitly provide a "capability" to CloudFormation `CAPABILITY_IAM` or `CAPABILITY_NAMED_IAM`
  * Reference IAM Role to EC2 instances
    * Assign with the `InstanceProfileName` property
* Custom Resources
  * With Lambda to program anything you want. To be called by CloudFormation.
* Cross vs Nested Stacks
  * Cross Stacks
    * Helpful when stacks have different lifecycles
    * Work with Outputs Export and `Fn::ImportValue`
  * Nested Stacks
    * Helpful when components must be re-used
* CloudFormer
  * Create an AWS CloudFormation template from existing AWS resources
* ChangeSets
  * Generate & preview the CloudFormation changes before applying
* StackSets
  * Deploy a CloudFormation stack to provision stack resources across multiple accounts and regions
* Stack Policies
  * Prevent accidental updates / deletes to stack resources
* Tempates
  * [Conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html)
  * [Intrinsic function reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html) can be used for
    * resource properties
    * outputs
    * metadata attributes
    * update policy attributes
