Show
AWS CloudFormation is a service that allows you to manage, configure and provision your AWS infrastructure as code. AWS CloudFormation provides a common language for you to describe and provision all the infrastructure resources in your cloud environment. Resources are defined using a CloudFormation template. CloudFormation interprets the template and makes the appropriate API calls to create the resources you have defined. Supports YAML or JSON. CloudFormation can be used to provision a broad range of AWS resources. Think of CloudFormation as deploying infrastructure as code. CloudFormation has some similarities with AWS Elastic Beanstalk though they are also quite different as detailed in the table below:
Key BenefitsInfrastructure is provisioned consistently, with fewer mistakes (human error). Less time and effort than configuring resources manually. You can use version control and peer review for your CloudFormation templates. Free to use (you’re only charged for the resources provisioned). It can be used to manage updates and dependencies. It can be used to rollback and delete the entire stack as well. Key ConceptsThe following table describes the key concepts associated with AWS CloudFormation:
TemplatesA template is a YAML or JSON template used to describe the end-state of the infrastructure you are either provisioning or changing. After creating the template, you upload it to CloudFormation directly or using Amazon S3. CloudFormation reads the template and makes the API calls on your behalf. The resulting resources are called a “Stack”. Logical IDs are used to reference resources within the template. Physical IDs identify resources outside of AWS CloudFormation templates, but only after the resources have been created. Template elementsMandatory:
Not mandatory:
Template componentsResources – the required Resources section declares the AWS resources that you want to include in the stack, such as an Amazon EC2 instance or an Amazon S3 bucket.
The following example YAML code declares an EC2 instance as a resource: Resources: MyEC2Instance: Type: "AWS::EC2::Instance" Properties: ImageId: "ami-0ff8a91507f77f867"ParametersUse 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.
The following example declares a parameter named InstanceTypeParameter. This parameter lets you specify the Amazon EC2 instance type for the stack to use when you create or update the stack. Note: the InstanceTypeParameter has a default value of t2.micro. This is the value that AWS CloudFormation uses to provision the stack unless another value is provided. Parameters: InstanceTypeParameter: Type: String Default: t2.micro AllowedValues: - t2.micro - m1.small - m1.large Description: Enter t2.micro, m1.small, or m1.large. Default is t2.micro.Pseudo ParametersPseudo parameters are parameters that are 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 for the Ref function. Examples include:
MappingsThe optional Mappings section matches a key to a corresponding set of named values.
The following example has region keys that are mapped to two sets of values: one named HVM64 and the other HVMG2. RegionMap: us-east-1: HVM64: ami-0ff8a91507f77f867 HVMG2: ami-0a584ac55a7631c0c us-west-1: HVM64: ami-0bdb828fd58c52235 HVMG2: ami-066ee5fd4a9ef77f1Exam tip: with mappings you can, for example, 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. OutputsThe optional Outputs section declares output values that you can import into other stacks (to create cross-stack references), return in response (to describe stack calls), or view on the AWS CloudFormation console.
In the following example YAML code, the output named StackVPC returns the ID of a VPC, and then exports the value for cross-stack referencing with the name VPCID appended to the stack’s name Outputs: StackVPC: Description: The ID of the VPC Value: !Ref MyVPC Export: Name: !Sub "${AWS::StackName}-VPCID"ConditionsThe optional Conditions section contains statements that define the circumstances under which entities are created or configured.
In the sample YAML code below, resources are created only if the EnvType parameter is equal to prod: Conditions: CreateProdResources: !Equals [ !Ref EnvType, prod ]TransformThe optional Transform section specifies one or more macros that AWS CloudFormation uses to process your template. The transform section can be used to reference additional code stored in S3, such as Lambda code or reusable snippets of CloudFormation code. The AWS::Serverless transform, which is a macro hosted by AWS CloudFormation, takes an entire template written in the AWS Serverless Application Model (AWS SAM) syntax and transforms and expands it into a compliant AWS CloudFormation template. In the following example, the template uses AWS SAM syntax to simplify the declaration of a Lambda function and its execution role: Transform: AWS::Serverless-2016-10-31 Resources: MyServerlessFunctionLogicalID: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs8.10 CodeUri: 's3://testBucket/mySourceCode.zip'Intrinsic FunctionsAWS CloudFormation provides several built-in functions that help you manage your stacks. Use intrinsic functions in your templates to assign values to properties that are not available until runtime. EXAM TIP: At a minimum, know the intrinsic functions listed below for the exam. The full list can be found at: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html Ref
The following resource declaration for an Elastic IP address needs the instance ID of an EC2 instance and uses the Ref function to specify the instance ID of the MyEC2Instance resource: MyEIP: Type: "AWS::EC2::EIP" Properties: InstanceId: !Ref MyEC2InstanceFn::GetAtt
The following example template returns the SourceSecurityGroup.OwnerAlias and SourceSecurityGroup.GroupName of the load balancer with the logical name myELB. AWSTemplateFormatVersion: 2010-09-09 Resources: myELB: Type: AWS::ElasticLoadBalancing::LoadBalancer Properties: AvailabilityZones: - eu-west-1a Listeners: - LoadBalancerPort: '80' InstancePort: '80' Protocol: HTTP myELBIngressGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: ELB ingress group SecurityGroupIngress: - IpProtocol: tcp FromPort: '80' ToPort: '80' SourceSecurityGroupOwnerId: !GetAtt myELB.SourceSecurityGroup.OwnerAlias SourceSecurityGroupName: !GetAtt myELB.SourceSecurityGroup.GroupNameFn::FindInMap
The following example shows how to use Fn::FindInMap for a template with a Mappings section that contains a single map, RegionMap, that associates AMIs with AWS regions: Mappings: RegionMap: us-east-1: HVM64: "ami-0ff8a91507f77f867" HVMG2: "ami-0a584ac55a7631c0c" us-west-1: HVM64: "ami-0bdb828fd58c52235" HVMG2: "ami-066ee5fd4a9ef77f1" Resources: myEC2Instance: Type: "AWS::EC2::Instance" Properties: ImageId: !FindInMap - RegionMap - !Ref 'AWS::Region' - HVM64 InstanceType: m1.smallFn::ImportValue
Fn::Join
The following example uses Fn::Join to construct a string value. It uses the Ref function with the Partition parameter and the AWS::AccountId pseudo parameter. !Join - '' - - 'arn:' - !Ref Partition - ':s3:::elasticbeanstalk-*-' - !Ref 'AWS::AccountId'Fn::Sub
The following example uses a mapping to substitute the ${Domain} variable with the resulting value from the Ref function: Name: !Sub - www.${Domain} - { Domain: !Ref RootDomainName }Stacks and Stack SetsStacksDeployed resources based on templates. Create, update, and delete stacks using templates. Deployed through the Management Console, CLI or APIs. Stack creation errors:
Updating stacks:
Stack SetsAWS CloudFormation StackSets extends the functionality of stacks by enabling you to create, update, or delete stacks across multiple accounts and regions with a single operation. Using an administrator account, you define and manage an AWS CloudFormation template, and use the template as the basis for provisioning stacks into selected target accounts across specified regions. An administrator account is the AWS account in which you create stack sets. A stack set is managed by signing in to the AWS administrator account in which it was created. A target account is the account into which you create, update, or delete one or more stacks in your stack set. Before you can use a stack set to create stacks in a target account, you must set up a trust relationship between the administrator and target accounts. Nested StacksNested stacks allow re-use of CloudFormation code for common use cases. For example standard configuration for a load balancer, web server, application server etc. Instead of copying out the code each time, create a standard template for each common use case and reference from within your CloudFormation template. Best PracticesAWS provides Python “helper scripts” which can help you install software and start services on your EC2 instances.
Serverless Application Model (SAM)Use SAM for deploying serverless applications using CloudFormation. SAM is an extension to CloudFormation used to define serverless applications. Simplified syntax for defining serverless resources: APIs, Lambda Functions, DynamoDB Tables etc. Use the SAM CLI to package your deployment code, upload it to S3 and deploy your serverless application. User data with EC2User data can be included in CloudFormation. The script is passed into Fn::Base64 The user data script logs are stored in /var/log/cloud-init-output.log Binary is available on Amazon EC2 at /opt/aws/bin/cfn-init CloudFormation Helper Scriptscfn-init:
cfn-signal:
Troubleshooting errors:
Creation Policies and Wait Conditions
The following CloudFormation resources support creation policies: DeletionPolicy attribute:
DependsOn attribute:
WaitCondition:
UpdatePolicy Attribute (WaitOnResourceSignals) Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the following resources: UpdateReplacePolicy attribute:
Rollbacks and Creation FailuresStack creation failures:
Stack update failures:
Monitoring and ReportingYou can monitor the progress of a stack update by viewing the stack’s events. The console’s Events tab displays each major step in the creation and update of the stack sorted by the time of each event with latest events on top. For resources created by CloudFormation, use AWS monitoring and reporting tools applicable to the service. Authorization and Access ControlYou can use IAM with AWS CloudFormation to control what users can do with AWS CloudFormation, such as whether they can view stack templates, create stacks, or delete stacks. In addition to AWS CloudFormation actions, you can manage what AWS services and resources are available to each user. That way, you can control which resources users can access when they use AWS CloudFormation. For example, you can specify which users can create Amazon EC2 instances, terminate database instances, or update VPCs. Those same permissions are applied anytime they use AWS CloudFormation to do those actions. ChargesThere is no additional charge for AWS CloudFormation. You pay for AWS resources (such as Amazon EC2 instances, Elastic Load Balancing load balancers, etc.) created using AWS CloudFormation in the same manner as if you created them manually. You only pay for what you use, as you use it; there are no minimum fees and no required upfront commitments. Snippetshttps://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/CHAP_TemplateQuickRef.html |