# CloudFormation

## Overview

### Benefits

* Scaling by sharing template for use across organization
* Can share best practices and company policies.
* Manage 3rd parties & private resources.

### Workflow

* **Code** the JSON/YAML template.
* **Review** the code and **Upload** it to S3 bucket.
* Using `CloudFormation` service (through CLI or Console) to **create** the `Stack`.
* The `CloudFormation` will **provision and configure** resources base on the previous `Stack`.

## Features

### vs.Elastic Beanstalk

<table><thead><tr><th width="134.33333333333331"></th><th>CloudFormation</th><th>Beanstalk</th></tr></thead><tbody><tr><td></td><td>easily provision &#x26; run app</td><td>environment for managing application lifecycle</td></tr><tr><td></td><td>behind the scenes, it uses CloudFormation to control the workload</td><td></td></tr></tbody></table>

### CloudFormation Designer

Help you design the CloudFormation template visually.

### Preview change

Provide the change sets, show the summary of proposed changes.&#x20;

### Dependency management

* You do **NOT** need to worry about the dependencies between the resources. It will determine the correct order of provision.
* `DependOn`: specify ***explicit***&#x6C;y the creation of specific resource follow another.
* Dependent stacks also have ***implicit*** dependencies in the form of target properties `!Ref`, `!GetAtt`, and `!Sub`.

### StackSets

Deploy CloudFormation stacks across multiple AWS accounts and regions with a single CloudFormation template.

By using `create-stack-set` CLI command, developer can deploy the same CloudFormation stack to multiple regions

## Helper script

### cfn-init

* Implement as part of the user data.
* execute CloudFormation metadata one time.

### cfn-hup

monitor CloudFormation metadata, and applies change when discovered.

### cfn-signal

provides a completion signal to designate the creation (successful or not) of a `CreationPolicy` or `WaitCondition`.

### cfn-get-metadata

view cureent metadata stored within the AWS CloudFormation stack.

## Best practices

* Adopt DevOps and GitOps best practices
* Automated deployments with pipeline integrations: GitHub Actions, AWS CodePipeline
* Create a integartion `pipeline`.
* **DO NOT** <mark style="color:red;">manually</mark> updating resouces that belong to a CloudFormation stack

## Trivia

* You need IAM policies if you want to upload an template.
  * to create a bucket S3
  * for CloudFront to access S3
* If you create resource outside of CloudFormation, you can bring that resource into CloudFormation using `resource import`.
* Some change require replacement. So sometime you will encounter error like can not remove resource when update resources.

## Concepts

* [Drift](#concepts): happen when environment get change, while CloudFormation not aware of that.
