☰ See All Chapters |
AWS CloudFormation Template Anatomy
Template is a JSON or YAML formatted text file that describes your AWS infrastructure. The following examples show an AWS CloudFormation template structure and its sections. A CloudFormation template is structured into ten parts:
Format version (optional): The latest template format version is 2010-09-09, and this is currently the only valid value. Specify this version; the default is to use the latest version, which will cause problems if new versions are introduced in the future.
Description (optional): What is this template about?
Metadata (optional): Objects that provide additional information about the template.
Parameters (optional): Parameters are used to customize a template with values: for example, domain name, customer ID, and database password.
Rules: Validates a parameter or a combination of parameters passed to a template during a stack creation or stack update.
Mappings (optional): A mapping of keys and associated values that you can use to specify conditional parameter values, similar to a lookup table. You can match a key to a corresponding value by using the Fn::FindInMap intrinsic function in the Resources and Outputs sections.
Conditions (optional): Conditions that control whether certain resources are created or whether certain resource properties are assigned a value during stack creation or update. For example, you could conditionally create a resource that depends on whether the stack is for a production or test environment.
Transform (optional): For serverless applications (also referred to as Lambda-based applications), specifies the version of the AWS Serverless Application Model (AWS SAM) to use.
Resources (required): A resource is the smallest block you can describe. Examples are a virtual machine, a load balancer, or an Elastic IP address.
Outputs(optional): An output is comparable to a parameter, but the other way around. An output returns something from your template, such as the public name of an EC2 instance.
AWSTemplateFormatVersion: "2010-09-09"
|
Format version (optional)
The AWSTemplateFormatVersion section identifies the capabilities of the template. The latest template format version is 2010-09-09 and is currently the only valid value. The AWSTemplateFormatVersion is an optional section, if you don’t, CloudFormation will use whatever version is the latest one. If you don’t specify it takes new format version is if introduced in the future, you’ll end up using the wrong format and get into serious trouble.
Description (optional)
Description is optional section; it is recommended to add description defining what the template is about. A meaningful description will help you in the future to remember what the template is for. It will also help your coworkers.
Metadata (optional)
Metadata is optional. This can be used to add data about data that provide details about the template. For example, you can include template implementation details about specific resources, as shown in the following snippet:
Metadata:
|
You can use any keys for Metadata. Also there are some predefined keys to retrieve settings or configuration information that you define in the Metadata section.
AWS::CloudFormation::Init
Defines configuration tasks for the cfn-init helper script. This script is useful for configuring and installing applications on EC2 instances.
AWS::CloudFormation::Interface
Defines the grouping and ordering of input parameters when they are displayed in the AWS CloudFormation console. By default, the AWS CloudFormation console alphabetically sorts parameters by their logical ID.
AWS::CloudFormation::Designer
Describes how your resources are laid out in AWS CloudFormation Designer (Designer). Designer automatically adds this information when you use it to create and update templates.
Metadata:
|
Parameters (optional)
Use the optional Parameters section to customize your templates. Parameters enable you to input custom values to your template each time you create or update a stack. A parameter has at least a name and a type. We encourage you to add a description as well.
Parameters:
|
Below table list out the allowed valid Types:
Type | Description |
String | A literal string. For example, users could specify "MyUserName". |
Number | An integer or float |
List<Number> | An array of integers or floats that are separated by commas. |
CommaDelimitedList | A list of strings separated by commas |
AWS::EC2::AvailabilityZone::Name | An Availability Zone, such as us-west-2a. |
AWS::EC2::Image::Id | An Amazon EC2 image ID, such as ami-0ff8a91507f77f867. Note that the AWS CloudFormation console doesn't show a drop-down list of values for this parameter type. |
AWS::EC2::Instance::Id | An Amazon EC2 instance ID, such as i-1e731a32. |
AWS::EC2::KeyPair::KeyName | An Amazon EC2 key pair name. |
AWS::EC2::SecurityGroup::GroupName | An EC2-Classic or default VPC security group name, such as my-sg-abc. |
AWS::EC2::SecurityGroup::Id | A security group ID, such as sg-a123fd85. |
AWS::EC2::Subnet::Id | A subnet ID, such as subnet-123a351e. |
AWS::EC2::Volume::Id | An Amazon EBS volume ID, such as vol-3cdd3f56. |
AWS::EC2::VPC::Id | A VPC ID, such as vpc-a123baa3. |
AWS::Route53::HostedZone::Id | An Amazon Route 53 hosted zone ID, such as Z23YXV4OVPL04A. |
List<AWS::EC2::AvailabilityZone::Name> | An array of Availability Zones for a region, such as us-west-2a, us-west-2b. |
List<AWS::EC2::Image::Id> | An array of Amazon EC2 image IDs, such as ami-0ff8a91507f77f867, ami-0a584ac55a7631c0c. Note that the AWS CloudFormation console doesn't show a drop-down list of values for this parameter type. |
List<AWS::EC2::Instance::Id> | An array of Amazon EC2 instance IDs, such as i-1e731a32, i-1e731a34. |
List<AWS::EC2::SecurityGroup::GroupName> | An array of EC2-Classic or default VPC security group names, such as my-sg-abc, my-sg-def. |
List<AWS::EC2::SecurityGroup::Id> | An array of security group IDs, such as sg-a123fd85, sg-b456fd85. |
List<AWS::EC2::Subnet::Id> | An array of subnet IDs, such as subnet-123a351e, subnet-456b351e. |
List<AWS::EC2::Volume::Id> | An array of Amazon EBS volume IDs, such as vol-3cdd3f56, vol-4cdd3f56. |
List<AWS::EC2::VPC::Id> | An array of VPC IDs, such as vpc-a123baa3, vpc-b456baa3. |
List<AWS::Route53::HostedZone::Id> | An array of Amazon Route 53 hosted zone IDs, such as Z23YXV4OVPL04A, Z23YXV4OVPL04B. |
AWS::SSM::Parameter::Name | The name of a Systems Manager parameter key. Use this parameter when you want to pass the parameter key. For example, you can use this type to validate that the parameter exists. |
AWS::SSM::Parameter::Value<String> | A Systems Manager parameter whose value is a string. This corresponds to the String parameter type in Parameter Store. |
AWS::SSM::Parameter::Value<List<String>> or AWS::SSM::Parameter::Value<CommaDelimitedList> | A Systems Manager parameter whose value is a list of strings. This corresponds to the StringList parameter type in Parameter Store. |
AWS::SSM::Parameter::Value<AWS-specific parameter type> | A Systems Manager parameter whose value is an AWS-specific parameter type. For example, the following specifies the AWS::EC2::KeyPair::KeyName type: AWS::SSM::Parameter::Value<AWS::EC2::KeyPair::KeyName> |
AWS::SSM::Parameter::Value<List<AWS-specific parameter type>> | A Systems Manager parameter whose value is a list of AWS-specific parameter types. For example, the following specifies a list of AWS::EC2::KeyPair::KeyName types: AWS::SSM::Parameter::Value<List<AWS::EC2::KeyPair::KeyName>> |
In addition to using the Type and Description properties, you can enhance a parameter with the properties listed in below table:
Parameter | Description | Example |
AllowedPattern | A regular expression that represents the patterns to allow for String or CommaDelimitedList types. When applied on a parameter of type String, the pattern must match the entire parameter value provided. When applied to a parameter of type CommaDelimitedList, the pattern must match each value in the list. | AllowedPattern: '[a-zA-Z0-9]*' allows only a–z, A–Z, and 0–9 with any length |
AllowedValues | An array containing the list of values allowed for the parameter. When applied to a parameter of type String, the parameter value must be one of the allowed values. When applied to a parameter of type CommaDelimitedList, each value in the list must be one of the specified allowed values. | AllowedValues: [1, 2, 3] |
ConstraintDescription | A string that explains a constraint when the constraint is violated. | ConstraintDescription: 'Maximum value is 10.' |
Default | A value of the appropriate type for the template to use if no value is specified when a stack is created. If you define constraints for the parameter, you must specify a value that adheres to those constraints. | Default: 'm5.large' |
Description | A string of up to 4000 characters that describes the parameter. | Description of the parameter |
MaxLength | An integer value that determines the largest number of characters you want to allow for String types. | MaxLength: 12 |
MaxValue | A numeric value that determines the largest numeric value you want to allow for Number types. | MaxValue: 10 |
MinLength | An integer value that determines the smallest number of characters you want to allow for String types. | MinLength: 12 |
MinValue | A numeric value that determines the smallest numeric value you want to allow for Number types. | MinValue: 10 |
NoEcho | Whether to mask the parameter value to prevent it from being displayed in the console, command line tools, or API. If you set the NoEcho attribute to true, CloudFormation returns the parameter value masked as asterisks (*****) for any calls that describe the stack or stack events, except for information stored in the locations specified below. | NoEcho: true |
Rules (optional)
Rules are used to validate parameter values before creating or updating resources. Rule is formed using two elements:
RuleCondition: This is optional and if specified it decides whether to apply rule or not
Assertions: This is mandatory in rules and describes what values users can specify for a particular parameter.
Rules Syntax
JSON Syntax{
|
YML SyntaxRules:
|
Rule-specific intrinsic functions
RuleConditions and Assertions are formed using rule-specific intrinsic functions. You can nest functions, but the final result of a rule condition or assertion must be either true or false. You can use the following rule-specific intrinsic functions to define rule conditions and assertions:
Functions
Examples
In the following example, the two rules check the value of the InstanceType parameter. Depending on the value of the environment parameter (test or prod), the user must specify a1.medium or a1.large for the InstanceType parameter. The InstanceType and Environment parameters must be declared in the Parameters section of the same template. If you see !Ref NameOfSomething, think of it as a placeholder for what is referenced by the name.
Parameters:
|
Yaml hints:
- (Hyphen) is used to add array element
! (exclamation mark) is used to add non-specific tag
Resources (required)
The resources section is mandatory to declare the AWS resources that you want to include in the stack, such as an Amazon EC2 instance or an Amazon S3 bucket.
Resources syntax
Yaml SyntaxResources:
|
JSON Syntax"Resources" : {
|
When defining resources, you need to know about the type and that type’s properties. An example of a single EC2 instance follows. If you see !Ref NameOfSomething, think of it as a placeholder for what is referenced by the name. You can reference parameters and resources to create dependencies.
Resource fields
Logical ID
The logical ID must be alphanumeric (A-Za-z0-9) and unique within the template. Use the logical name to reference the resource in other parts of the template. For example, if you want to map an Amazon Elastic Block Store volume to an Amazon EC2 instance, you reference the logical IDs to associate the block stores with the instance.
In addition to the logical ID, certain resources also have a physical ID, which is the actual assigned name for that resource, such as an EC2 instance ID or an S3 bucket name. Use the physical IDs to identify resources outside of AWS CloudFormation templates, but only after the resources have been created. For example, suppose you give an EC2 instance resource a logical ID of MyEC2Instance. When AWS CloudFormation creates the instance, AWS CloudFormation automatically generates and assigns a physical ID (such as i-28f9ba55) to the instance. You can use this physical ID to identify the instance and view its properties (such as the DNS name) by using the Amazon EC2 console. For resources that support custom names, you can assign your own names (physical IDs) to help you quickly identify resources. For example, you can name an S3 bucket that stores logs as MyPerformanceLogs. For more information, see Name type.
Resource type
The resource type identifies the type of resource that you are declaring. For example, AWS::EC2::Instance declares an EC2 instance. For a list of all resource types, see AWS resource and property types reference.
Resource properties
Resource properties are additional options that you can specify for a resource. For example, for each EC2 instance, you must specify an Amazon Machine Image (AMI) ID for that instance. You declare the AMI ID as a property of the instance, as shown in the following example:
Each resource type will be having its own set of properties, example AWS::EC2::Instance type has properties which you can refer from AWS documents here AWS::EC2::Instance Properties.
Resource Examples
The following example shows a resource declaration. It defines two resources. The MyInstance resource includes the MyQueue resource as part of its UserData property:
Resources:
|
Outputs (optional)
A CloudFormation template’s output includes at least a name (like parameters and resources) and a value, but we encourage you to add a description as well. You can use outputs to pass data from within your template to the outside.
Resources syntax
Yaml SyntaxOutputs:
|
JSON Syntax"Outputs" : {
|
Outputs fields
The Outputs section can include the following fields.
Logical ID
An identifier for the current output. The logical ID must be alphanumeric (a–z, A–Z, 0–9) and unique within the template.
Description (optional)
A String type that describes the output value. The value for the description declaration must be a literal string that's between 0 and 1024 bytes in length. You can't use a parameter or function to specify the description. The description can be a maximum of 4 K in length.
Value (required)
The value of the property returned by the aws cloudformation describe-stacks command. The value of an output can include literals, parameter references, pseudo-parameters, a mapping value, or intrinsic functions.
Export (optional)
The name of the resource output to be exported for a cross-stack reference.
You can use intrinsic functions to customize the Name value of an export. The following examples use the Fn::Join function.
Export: ------------------ "Export" : {
|
Outputs Example
Outputs:
|
Mappings (optional)
The optional Mappings section matches a mapping Key to a corresponding array of key values.
Yaml SyntaxMappings:
|
JSON Syntax“Mappings”: {
|
You use the Fn::FindInMap intrinsic function to retrieve values in a map. For example, if you want to set values based on a region, you can create a mapping that uses the region name as a key and contains the values you want to specify for each specific region. You can't include parameters, pseudo parameters, or intrinsic functions in the Mappings section.
Mappings Example
The following example template contains an Amazon EC2 resource whose ImageId property is assigned by the FindInMap function. The FindInMap function specifies key as the region where the stack is created (using the AWS::Region pseudo parameter) and HVM64 as the name of the value to map to.
AWSTemplateFormatVersion: "2010-09-09"
|
Conditions (optional)
The optional Conditions section is used to conditionally create resource or output in cloud formation. After you define all your conditions, you can associate them with resources and resource properties in the Resources and Outputs sections of a template. At stack creation or stack update, AWS CloudFormation evaluates all the conditions in your template before creating any resources. Resources that are associated with a true condition are created. Resources that are associated with a false condition are ignored. AWS CloudFormation also re-evaluates these conditions at each stack update before updating any resources. Resources that are still associated with a true condition are updated. Resources that are now associated with a false condition are deleted.
JSON Syntax"Conditions": {
|
Yaml SyntaxConditions:
|
Condition intrinsic functions
You can use the following intrinsic functions to define conditions:
Fn::And
Fn::Equals
Fn::If
Fn::Not
Fn::Or
For the syntax and information about each function, see Condition functions.
Conditions Example
{ ------------------------ Parameters:
|
Transform (optional)
Transform section is used to define macro with set of processable content. A macro is a single instruction that expands automatically into a set of instructions to perform a particular task. AWS CloudFormation executes macros in the order that they're specified. When you create a change set, AWS CloudFormation generates a change set that includes the processed template content. You can then review the changes and execute the change set. For more information, see Using AWS CloudFormation macros to perform custom processing on templates.
AWS CloudFormation also supports transforms, which are macros hosted by AWS CloudFormation. AWS CloudFormation treats these transforms the same as any macros you create in terms of execution order and scope. For detailed information regarding specific transforms, see Transform reference.
To declare multiple macros, use a list format and specify one or more macros.
For example, in the template sample below, AWS CloudFormation evaluates MyMacro and then AWS::Serverless, both of which can process the contents of the entire template because of their inclusion in the Transform section.
// Start of processable content for MyMacro and AWS::Serverless
|
All Chapters