AWS CloudFormation allows you to model, provision, and manage AWS and third-party resources by treating your infrastructure as code (IaC). Instead of manually clicking through the AWS Management Console to create servers, databases, and networks, you define these resources in a JSON or YAML template. CloudFormation then reads that template and automatically deploys the resources in the correct order, ensuring that your environment is consistent, repeatable, and easy to version control.
What You'll Need
- An active AWS Account with administrative access or the necessary IAM permissions to create CloudFormation stacks and the specific resources you intend to deploy (e.g., EC2, S3, RDS).
- A text editor for writing your templates (Visual Studio Code with the AWS Toolkit extension is highly recommended for syntax highlighting and validation).
- Basic familiarity with YAML or JSON syntax.
- Access to the AWS Management Console via a web browser.
Step-by-Step
- Choose Your Template Format: Decide whether to use YAML or JSON. YAML is generally preferred for CloudFormation because it is more human-readable, supports comments, and is less verbose than JSON. Ensure your file extension is .yaml or .json.
- Define the Template Structure: Start your template with the
AWSTemplateFormatVersion. This tells AWS which version of the CloudFormation language you are using. For most modern projects, use "2010-09-09". - Set Up Parameters: Use the
Parameterssection to make your template flexible. Parameters allow you to input values at runtime, such as the instance type of an EC2 server or the name of a bucket. For example, you can create a parameter forKeyNameso that different users can specify their own SSH key pair without editing the code. - Define Resource Properties: The
Resourcessection is the core of your template. This is where you declare the actual AWS components you want to create. Each resource must have a logical name (a unique identifier within the template) and aType. For instance, to create an S3 bucket, you would use the typeAWS::S3::Bucket. Under thePropertieskey, you define the specific configurations for that resource, such asBucketNameorAccessControl. - Implement Dependencies: CloudFormation usually determines the order of creation automatically. However, if one resource must exist before another can be created (e.g., a security group must exist before an EC2 instance can use it), use the
DependsOnattribute to explicitly define that relationship. - Create Outputs: Use the
Outputssection to export values that you will need after the stack is deployed. Common outputs include the Public DNS of an EC2 instance or the ARN of an S3 bucket. These values are displayed in the AWS Console once the stack reaches theCREATE_COMPLETEstate. - Upload the Template: Log into the AWS Management Console. Navigate to the CloudFormation service. Click
Create stackand thenWith new resources (standard). You can either upload your template file from your local machine or provide a URL to a template stored in an S3 bucket. - Configure Stack Details: Give your stack a unique name. This name helps you identify the group of resources in your account. If you defined parameters in your template, the console will prompt you to enter values for them now. Choose the IAM role that CloudFormation should use to create the resources; if you leave this blank, it uses your current user permissions.
- Review and Submit: Review the capabilities section. If your template creates IAM users or roles, you must explicitly check the box acknowledging that the template might create resources that affect permissions. Click
Submitto begin the deployment. - Monitor the Event Log: Navigate to the
Eventstab of your new stack. Here, you can see a real-time log of every resource being created. The status will move fromCREATE_IN_PROGRESStoCREATE_COMPLETE. If a resource fails, the status will change toCREATE_FAILED, and the event log will provide an error message explaining why.
Common Mistakes
One of the most frequent errors is a syntax mistake in the YAML file, such as incorrect indentation. Because YAML relies on whitespace, a single misplaced space can cause the entire template to fail validation. Always use a linter or a dedicated IDE plugin to verify your indentation before uploading.
Another common mistake is failing to handle resource naming. If you hardcode a name for a resource (like an S3 bucket name), you cannot deploy the same template twice in the same region because AWS resource names must be globally or regionally unique. To avoid this, omit the name property and let CloudFormation generate a unique physical ID for you.
Users often forget to grant the CloudFormation service role the necessary permissions. If your template tries to create an RDS database but the role executing the stack doesn't have the rds:CreateDBInstance permission, the stack will fail. Ensure the identity creating the stack has a policy that covers every resource type listed in the template.
Finally, many beginners overlook the difference between Update and Replace. Some changes to a resource's properties cannot be updated in place and require the resource to be destroyed and recreated. This can lead to unexpected downtime or data loss if you are not aware that a property change triggers a replacement.
Tips
Use Ref and Fn::GetAtt to create dynamic links between resources. Instead of hardcoding an ID, use Ref to reference the physical ID of another resource in the same template. Use Fn::GetAtt to retrieve specific attributes, such as the private IP address of an instance.
Leverage Mappings to make your templates multi-region. You can create a map that associates a region (e.g., us-east-1) with a specific AMI ID. By using the Fn::FindInMap function, your template can automatically select the correct AMI based on the region where the stack is being deployed.
Implement DeletionPolicy for critical resources. By default, deleting a stack deletes all its resources. If you have a production database, set the DeletionPolicy to Retain. This ensures that even if the CloudFormation stack is deleted, the actual database instance remains intact in your account.
Utilize Conditions to control whether certain resources are created. For example, you can create a condition that only deploys a high-availability load balancer if the EnvironmentType parameter is set to "Production", while skipping it for "Development" to save costs.
Troubleshooting
If your stack fails to create, the first step is to check the Events tab. Look for the first resource that entered the CREATE_FAILED state. The Status reason column usually contains the exact API error returned by AWS, such as "LimitExceeded" or "InvalidParameterValue".
When a stack fails, CloudFormation initiates a ROLLBACK_IN_PROGRESS state, which deletes all resources created up to that point. To debug the exact cause of a failure without the resources being deleted, you can disable the automatic rollback. In the Create stack wizard, go to Stack options and select Preserve successfully provisioned resources (or Disable rollback on failure in older versions). This allows you to inspect the failed resource in the console before manually deleting the stack.
If you encounter a UPDATE_ROLLBACK_FAILED state, it usually means a resource was manually modified or deleted outside of CloudFormation, and the service cannot return the resource to its previous state. To fix this, you must manually identify the problematic resource and mark it as "skipped" during the continue-update-rollback process.
For issues related to permissions, check the IAM role associated with the stack. Ensure that the role has a trust relationship with cloudformation.amazonaws.com and that the attached policies are not overly restrictive. If you are using a Service-Managed role, verify that the permissions are updated to include any new resource types you've added to your template.
Frequently Asked Questions
Can I use CloudFormation for resources I already created manually?
Yes, you can use the resource import feature. This allows you to bring existing AWS resources under CloudFormation management by providing their identifiers and adding them to a template.
What is the difference between a Stack and a StackSet?
A Stack manages resources in a single account and a single region. A StackSet allows you to deploy the same template across multiple AWS accounts and multiple regions simultaneously from a central administrator account.
Does CloudFormation cost extra to use?
The CloudFormation service itself is free for most AWS resources. You only pay for the resources (EC2, S3, etc.) that the template creates and manages.
Can I use CloudFormation with third-party resources?
Yes, via the CloudFormation Registry. You can create or use "Resource Providers" to manage resources outside of AWS or custom resources using AWS Lambda functions.
What happens if I manually delete a resource that was created by a stack?
This creates "drift". The stack still thinks the resource exists, but the actual state in AWS differs. You can use the Detect drift feature to identify these discrepancies and then update the stack or the resource to resolve them.
How do I handle secrets like passwords in templates?
Never hardcode passwords in templates. Use AWS Secrets Manager or Systems Manager Parameter Store and reference them in your template using dynamic references, which CloudFormation resolves at runtime.