CloudFormation
What is Infrastructure As Code? (laC) the process of managing and provisioning computer data centers (eg, AWS) through machine-readable definition files (eg, YAML, JSON files) rather than physical hardware configuration or interactive configuration tools. (stop doing manual configuration!)
Use Case People pay a monthly subscription and we run a Minecraft server. They choose where they want and what size of server they want to run.
We can use their inputs and use an AWS Lambda to create a new Cloud Formation stack. We have a lambda send them the email of their new Minecraft Server IP address and details.
CloudFormation - Template Formats
JSON or YAML
Template Anatomy
Template Sections MetaData Additional information about the template
Description A description of what this template is suppose to do
Parameters Values to pass to your template at runtime
Mappings A lookup table. Maps keys to values so you change your values to something else
Conditions Whether resources are created or properties are assigned
Transform Applies marcos (like applying a mod which change the anatomy to be custom)
Resources* A resource you want to create eg. IAM Role, EC2 Instance, Lambda, RDS Outputs
Values that returned eg. an ip-address of new server created.
Stack Updates**
When you need to make a change to stack instead of deleting and recreating the stack. You can modify the CloudFormation template and push a stack update and CloudFormation will intelligently change or delete and recreate resources.
There are two ways to perform a stack update
- direct update: You directly update a stack, you submit changer and AWS CloudFormation immediately deploys them. Use direct updates when you want to quickly deploy your updates
- executing change sets: You can preview the changes to CloudFormation will make to your stack and then decide whether to apply those changes. Use change sets when you want to ensure that CloudFormation doesn’t make unintentional changes
When you submit and update, CloudFormation updates differently depending on the state of your resources and circumstances
Update with No Interruption
- Updates the resource without disrupting operation
- and without changing the resource’s physical ID
Updates with Some Interruption
- Updates the resource with some interruption
- and retains the physical ID.
Replacement
- recreates the resource during an update,
- also generates new physical ID.
Prevent Stack Updates
You may want certain resources not to be updated. Preventing a stack-updated could be to prevent data loss or interruption to service
StackPolicy A stack policy is a JSON document that defines the update actions that can be performed on designated resources.
Nested Stacks
NestedStacks allows you to reference CFN templates inside of another CFN templates:
- create modular templates (reusability)
- assemble large templates (reduce complexity).
Drift Detection
What is Drift? Drift is when your stack’s actual configuration differs (has drifted) by what CloudFormation expects.
Why does Drift happen? When developers start making manual ad-hoc changes to the stack (most common example is deleting resources) Instead of changing configuration by updating and relaunching the CloudFormation template
CloudFormation “Detect Drift” Feature CloudFormation can detect drift and tell you if resources deleted or have been modified
Nest Stacks and Drift Detection When detecting drift on a stack, CloudFormation does not detect drift on any nested stacks that belong to that stack. Instead, you can initiate a drift detection operation directly on the nested stack.
Rollbacks
When you create, update or destroy a stack you could encounter and error: Eg. Your CloudFormation template has a syntax error Eg. Your stack is trying to delete a resource which no longer exists.
CloudFormation will attempt to Rollback in case of an error put your stack back to its previous State.
RollbackS are turned on my default. You can ignore rollback by using the --ignore-rollback flag via the AWS CLI.
Rollback can fail. Sometimes you’ll have to investigate and change resource configurations or possibly need To reach out to paid AWS Support to resolve the failed rollback
- When a rollback is in progress you’ll see ROLLBACK_INPROGRESS
- When a rollback succeeds you’ll see UPDATE_ROLLBACK_COMPLETE
- When a rollback fails you’ll see UPDATE_ROLLBACK_FAILED
PseudoParameters
parameters that a predefined by AWS CloudFormation You do not declare them in your template Use them the same way as you would a parameter, as the argument to the Ref function
| Parameter | Description | Example |
|---|---|---|
| AWS::Partition | Returns the partition that the resources is in | aws-us-gov |
| AWS::Region | Returns ta string representing the AWS Region in which the encompassing resource is being created | eu-west-1 |
| AWS::StackId | Returns the ID of the stack as specified with the AWS CloudFormation create-stack command | arn:aws:cloudformation:us-west-2:123123312:stack/teststack/51asdkfjsakl-dsf-sdfasd-sdfsdfdsff |
| AWS::StackName | Returns the name of the stack as specified with the AWS CloudFormation create-stack command | my-cfn-stack |
| **AWS::URLSuffix | Returns the suffix for a domain. The suffix is typically amazonaws.com, but might differ by region. | amazonaws.com.cn |
Resource Attributes
Creation Policy prevent its status from reaching create complete until AWS CloudFormation receives a specified number of success signals or the timeout period is exceeded.
Deletion Policy reserve or (in some cases) backup a resource when its stack is deleted Delete, Retain or Snapshot
UpdatePolicy How to handle an update for ASG, ElastiCache, Domain or Lambda Alias
UpdateReplacePolicy To retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation. Delete, Retain or Snapshot
DependsOn That resource is created only after the creation of the resource specified in the DependsOn attribute
MetaData enables you to associate structured data with a resource. cfn-get-metadata helper can be used to fetch metadata programatically
Intrinsic Functions
Use intrinsic functions in your templates to assign values to properties that are not available until runtime
| Function Name | Description |
|---|---|
| Fn::Base64 | returns the Base64 representation of the input string. |
| Fn::Cidr | returns an array of CIDR address blocks |
| Condition Functions | Fn::And Fn::Equals Fn:lf Fn::Not Fn::Or |
| Fn:FindinMap | returns the value corresponding to keys in a two-level map that is declared in the Mappings section |
| Fn::Transform | a macro to perform custom processing on part of a stack template |
| Fn::GetAZs | returns an array that lists Availability Zones for a specified region |
| Fn:ImportValue | returns the value of an output exported by another stack |
| Fn:: Join | appends a set of values into a single value, separated by the specified delimiter |
| Fn::Select | returns a single object from a list of objects by index |
| Fn:Split | split a string into a list of string values so that you can select an element from the resulting string list |
| Fn:Sub | substitutes variables in an input string with values that you specify |
| Fn::GetAtt | returns the value of an attribute from a resource in the template |
| Ref | returns the value of the specified parameter or resource |
Ref
Ref returns different things for different resources. You need to to look up each resource in the AWS Docs to see what it returns: .e.g. ARN, Resource Name, Physical ID
When you have a value for a resource and can’t get it from Ref you can get it from Fn::GetAttr
Fn:GetAttr
GetAttr allows you to access many different variables on a resources. You’ll need to check the AWS Docs to see what is available per resource.
Wait Conditions
Wait Conditions wait for a condition They are used in ✌🏾 two cases:
- To coordinate stack resource creatiob with configuration actions that are external to the stack creation
- To track the status of a configuration process