CloudFormation code is a JSON or YAML template that describes the AWS resources you want, which CloudFormation then creates and manages as one unit called a stack. The shortest working path is: write a YAML template declaring at least one resource, validate it with aws cloudformation validate-template, preview the changes with a change set, then deploy with aws cloudformation deploy (or create the stack in the console). Everything after that — updates, deletions, rollbacks — is driven by editing the same template rather than clicking through the console.
The rest of this guide assumes the AWS CLI is installed and configured with credentials that can create the resource types you plan to use. Menu and flag names in the CLI and console can differ slightly between versions, so treat the exact wording as a guide.
What You'll Need
- An AWS account and an IAM identity with permission to create, update and delete the resources in your template, plus CloudFormation itself.
- The AWS CLI installed and configured (
aws configure) and ideally a named profile per environment. - A template file saved as
.yamlor.json— YAML is the common choice because comments are allowed. - A text editor with YAML or JSON syntax highlighting, and an S3 bucket only if a template is too large to pass inline (the CLI uses a local file path for normal sizes).
- Basic knowledge of the one or two resource types you are creating, for example an S3 bucket or a Lambda function.
Step-by-Step
- Sketch the resources before writing code. List what the application needs: a bucket, a function, a table, a role. Each becomes one entry under
Resourcesin the template. Grouping related resources in one stack means they are created and deleted together, so decide the boundary deliberately — a stack per environment is typical. - Start the template with the template format version. The first line is
AWSTemplateFormatVersion: "2010-09-09". This is the only accepted value; it tells CloudFormation which template syntax to expect. - Add a
Descriptionline. Keep it short and factual:Description: S3 bucket and Lambda function for image resizing. It appears in the stack details and saves guesswork later. - Declare parameters only for things that change per environment. A parameter has a
Type(for exampleString), optionalDefault,AllowedValuesand aDescription. Environment name, instance class and CIDR ranges are good parameters. Values hard-coded into a single deployment are better as plain literals. - Define each resource with a logical ID and a type. The logical ID is your name for it and must be alphanumeric —
ImageBucket, notimage-bucket. The type is the full AWS name, such asAWS::S3::Bucket. UnderProperties, set only what you need; CloudFormation fills in defaults for the rest but you should set deletion and versioning behaviour explicitly for anything holding data. - Wire resources together with references instead of literal names. Use
!Refto pass one resource's identifier to another, and!GetAttfor attributes like an ARN or domain name. This lets CloudFormation work out creation order automatically and avoids hard-coded ARNs that break in another account or region. - Expose useful values under
Outputs. Each output has aValue, usually a!Refor!GetAtt, and optionally anExportname so another stack can import it. Outputs are how you find the bucket name or endpoint after deployment. - Validate the template before touching the account. Run
aws cloudformation validate-template --template-body file://template.yaml. It catches syntax errors and bad property names but not everything, so also check indentation carefully — YAML fails silently on misplaced spaces. - Create a change set. Run
aws cloudformation deploy --template-file template.yaml --stack-name my-app-dev --capabilities CAPABILITY_IAM --no-execute-changeset. This produces a change set you can inspect. The--capabilities CAPABILITY_IAMflag is required whenever the template creates IAM roles or policies, because you are confirming you accept the permission changes. - Review the change set, then execute it. In the console, open the stack, go to the change set and read the resource actions (Add, Modify, Remove). With the CLI, run
aws cloudformation execute-change-set --change-set-name NAME --stack-name my-app-dev. On the first deployment every action should be Add; anything surprising means the template is wrong. - Watch the stack events until it completes. Use
aws cloudformation describe-stack-events --stack-name my-app-devor the Events tab. If a resource fails, the failure reason is on the event for that resource, and CloudFormation rolls the whole stack back. - Read the outputs. Run
aws cloudformation describe-stacks --stack-name my-app-dev --query "Stacks[0].Outputs". Confirm the values match what you expect before pointing an application at them. - Update by editing the template, not the console. Change the file, run validate-template, deploy again with a change set, and review. Any manual edits made in the console drift from the template and will be overwritten or cause conflicts on the next update.
- Delete test stacks when finished. Run
aws cloudformation delete-stack --stack-name my-app-devand watch the events. Resources whose deletion policy isRetain, and non-empty S3 buckets, will survive — check for leftovers.
Common Mistakes
- Hard-coding names and ARNs. Resource names that include account IDs or region suffixes collide on a second deployment. Omit explicit names and let CloudFormation generate them, then reference the generated name through
!Ref. - Using the wrong logical ID style. Hyphens and spaces are rejected; use PascalCase or similar alphanumerics.
- Forgetting capabilities. Templates creating IAM resources fail immediately without a capabilities acknowledgment.
- Assuming a rollback undoes data changes. Rollback restores resource configuration, but data written after creation — objects in a bucket, records in a table — is generally not restored.
- Mixing YAML and JSON syntax. Shorthand tags like
!Refonly work in YAML; in JSON you must write full objects such as{"Ref": "ResourceName"}. - Editing resources in the console after deploying. The template no longer matches reality, and the next update may revert or fail on the drift.
- Putting everything in one enormous stack. One failing resource rolls back unrelated changes. Split stacks along lifecycle boundaries and connect them with exports or parameters.
Tips
- Keep templates under version control and treat every environment as a separate stack of the same template with different parameters.
- Add a
DeletionPolicy: Retainto anything holding data you cannot regenerate, and anUpdateReplacePolicytoo where replacement would destroy it. - Use the pseudo parameters
AWS::Region,AWS::AccountIdandAWS::StackNamerather than typing those values. - Tag resources through the template so cost and ownership reporting stays accurate.
- Name change sets descriptively, including what is being changed, so the review process is quick.
- Keep secrets out of templates and parameters with defaults — store them in a secrets service and reference them from the resource.
- Test templates in a scratch account or with a small stack first; a rollback in production is slow and noisy.
Troubleshooting
Start with the stack events: the first event marked with a failure status carries the real error, and later events are only the rollback. A validation error usually means a typo in a property name or wrong indentation; re-check the resource type against the official reference. A failure with a permission message means the deploying identity lacks an action, not that the template is wrong — compare the required actions with the IAM policy attached to your user or role. If a resource reports that it already exists, you are probably using a hard-coded name that is taken; remove the name and redeploy.
When a stack is stuck in an update-rollback-failed state, the usual cause is a resource that could not be reverted, often an IAM role or a bucket with contents. Inspect the failed resource, resolve it manually, then continue the rollback. If a template is too large or contains nested stacks, upload it to S3 and pass the URL instead of the body. Persistent issues are often drift: run drift detection on the stack, compare the result with the template, and bring the template in line rather than patching the console. If you truly need an existing stack recreated, deleting it destroys everything in it — export or back up data first, and confirm what will be retained by deletion policies.
Frequently Asked Questions
Should I write CloudFormation in YAML or JSON?
Either works. YAML is easier to read and supports comments and shorthand tags like !Ref. JSON is stricter and sometimes easier to generate from tooling.
Do I need to upload my template to S3?
Not for normal template sizes. The CLI accepts a local file path. S3 is used for templates that exceed the inline size limit or for nested stacks.
Why does my deployment ask for capabilities?
Because the template creates IAM resources. CloudFormation requires you to acknowledge that the stack will create or modify permissions before it proceeds.
What happens to my resources if a stack fails?
CloudFormation rolls back to the last successful state by default and deletes resources it created during the failed operation. Resources with a retain policy are kept.
Can I change a resource name later?
Changing a property that requires replacement causes CloudFormation to create a new resource and delete the old one, which can lose data. Check the resource type's replacement behaviour before editing such properties.
How do I stop someone editing the stack in the console?
Use IAM policies to restrict console changes and treat the template as the only source of truth. Drift detection will flag manual changes, but prevention is through permissions.