Domain 2 of the DVA-C02 exam tests your ability to write templates, manage stacks, and use change sets for deployments. Without Infrastructure as Code, setting up AWS resources would be like building a sandcastle with a thousand clicks - fragile, error-prone, and impossible to reproduce. This chapter will teach you how to define your entire AWS setup as a single text file, so you can deploy, update, and delete environments with the precision of a master clockmaker.
Jump to a section
Have you ever watched someone renovate a restaurant kitchen without a blueprint? The chef keeps shouting 'Move the stove!', the plumber drills a hole in the wrong wall, and the electrician guesses where the sockets should go. The result is chaos, rework, and a health inspection nightmare.
Now imagine this instead: the head chef writes a single, detailed document called a 'kitchen specification file'. This file says exactly where every oven, sink, and fridge goes, what gas pressure each burner needs, and how many exit signs are required. The chef hands this file to a single person - the general contractor. The contractor reads the file, orders all the parts, and calls in the plumber, electrician and tiler. They all work from the same plan. If the chef wants to change the stove position, she edits the file and gives the contractor the new version. The contractor figures out what changed (the stove moved) and only redoes the gas line - not the whole kitchen. No shouting, no guesswork, no wasted pizzas.
AWS CloudFormation works exactly like that general contractor. Your 'kitchen specification file' is a JSON or YAML template. The 'stove' and 'sink' are AWS resources like EC2 instances or databases. The general contractor is the CloudFormation service. When you update the template, CloudFormation automatically builds a 'change set' - a summary of exactly what will be altered - before it touches a single thing. That change set is your safety net, just like the contractor's written estimate before he starts drilling.
Infrastructure as Code (IaC) is the practice of managing your IT infrastructure - servers, databases, networks, and security settings - using machine-readable definition files, rather than clicking around in a web console or running manual shell commands. AWS CloudFormation is Amazon's native IaC service. It lets you describe all the AWS resources you want (like EC2 instances, RDS databases, S3 buckets, and IAM roles) in a single text file called a template. You submit that template to CloudFormation, and the service takes responsibility for provisioning, configuring, and linking those resources together in the correct order.
To understand why IaC matters, you need to know what it replaces. Before IaC, system administrators would manually log into each server, install software, configure networking, and set permissions. This was slow, error-prone, and impossible to reproduce exactly. Two different admins would set up the same application differently, leading to the infamous 'it works on my machine' problem. If a server crashed, rebuilding it from scratch could take days. CloudFormation eliminates all of this. Your template is the single source of truth. If you need a new environment for testing, you run the same template. If a server fails, you delete the old stack and recreate it from the template. Consistency becomes automatic.
Now let us break down the key components. A CloudFormation template is a JSON or YAML file. It contains several sections, but the most critical one is Resources. This is where you define every AWS service you want to create. Each resource has a logical name (like 'MyWebServer') and a type (like 'AWS::EC2::Instance'). You also provide properties - for example, the Amazon Machine Image (AMI) ID, instance type, and security group IDs. CloudFormation uses this information to call the AWS APIs on your behalf, in the right order. For instance, if your template defines a security group and an EC2 instance that references that group, CloudFormation creates the security group first, then the EC2 instance.
A collection of resources managed together is called a stack. Think of a stack as a single unit of deployment. You create a stack from a template. You can update a stack by submitting a modified template. You can delete a stack, and CloudFormation will tear down all the resources in the correct order. Stacks give you lifecycle management. If you need to clone a production environment for a staging test, you create a new stack from the same template. If you want to decommission the staging environment, you delete that stack, and everything disappears cleanly. No orphaned resources, no forgotten S3 buckets.
One of the most important features for the DVA-C02 exam is the change set. When you want to update a running stack (for example, to change the instance type from t2.micro to t3.medium), you do not just edit the template and re-upload it. Instead, you generate a change set. A change set is a summary of the changes CloudFormation will make - which resources will be added, modified, or deleted. You review the change set, and only if you approve it does CloudFormation execute the changes. This is your safety net. It prevents accidental deletions or modifications. For example, if you accidentally remove a database resource from your template, the change set will show 'Remove: MyDatabase'. You can spot the mistake before any data is lost.
CloudFormation also supports parameters, which are inputs you supply when you create or update a stack. For example, you can have a parameter called 'InstanceType' with a default of 't2.micro'. When you launch the stack, you can override it to 't3.medium' without editing the template. This makes templates reusable across environments. You can also use outputs to export information from one stack and import it into another - for example, export the VPC ID from a network stack and import it into an application stack.
To pass the DVA-C02 exam, you must understand the following core concepts:
Template: the JSON/YAML file defining resources.
Stack: the collection of resources created from a template.
Change set: a preview of changes before execution.
Parameters: inputs that customise a template at runtime.
Outputs: values that a stack exports for use by other stacks.
Intrinsic functions: built-in functions like Ref, Fn::GetAtt, and Fn::Join that let you reference resource properties dynamically.
Stack updates: the process of modifying a running stack by submitting an updated template.
Stack drift: when the actual resource configuration differs from what the template says. You can detect drift using the AWS Console or CLI.
CloudFormation is not the only IaC tool - Terraform and Pulumi are popular alternatives - but for the DVA-C02 exam, you only need to master CloudFormation. It is the native AWS solution and the one you will encounter most in the exam and in real AWS-centric workplaces.
Write the Template
Create a JSON or YAML file that declares the AWS resources you need. Include the Resources section with each resource's type (e.g., AWS::EC2::Instance) and properties (e.g., ImageId, InstanceType). For the DVA-C02 exam, you must be able to write a valid template that references parameters and outputs correctly.
Validate the Template
Use the AWS CLI command 'aws cloudformation validate-template' or the CloudFormation Designer to check for syntax errors. The exam expects you to know that validation checks for JSON/YAML syntax and resource type recognition, but it does not verify that AMI IDs or parameter values exist.
Create the Stack
Run 'aws cloudformation create-stack --stack-name MyApp --template-body file://template.yaml'. CloudFormation then provisions the resources in the correct dependency order. You can also specify parameters, tags, and a stack policy during creation. The stack enters the CREATE_IN_PROGRESS state, then becomes CREATE_COMPLETE.
Generate a Change Set for Updates
When you need to modify the stack (e.g., change an instance type), generate a change set: 'aws cloudformation create-change-set --stack-name MyApp --template-body file://new-template.yaml --change-set-name UpdateInstance'. This set lists every resource addition, modification, and deletion. You review it to ensure nothing unintended will be deleted.
Execute the Change Set
After reviewing the change set and confirming it is safe, execute it: 'aws cloudformation execute-change-set --change-set-name UpdateInstance --stack-name MyApp'. CloudFormation applies the changes incrementally, respecting dependencies. If it fails, the stack rolls back to its previous state by default.
Delete the Stack
When you no longer need the stack, run 'aws cloudformation delete-stack --stack-name MyApp'. CloudFormation deletes all resources in the stack in the correct order. For the exam, remember that you cannot delete a stack that has termination protection enabled unless you first disable it.
Detect and Correct Drift
Periodically run 'aws cloudformation detect-stack-drift --stack-name MyApp' to check if any resources have been changed outside of CloudFormation. If drift is detected, you can either update the template to match the changed resource, or use 'aws cloudformation import-resources-to-stack' to bring the resource back under CloudFormation management.
An IT professional at a company called 'ShopNow' manages a web application that runs on AWS. The application uses an EC2 instance running a Node.js server, an RDS MySQL database, an S3 bucket for static assets, and an Elastic Load Balancer (ELB) to distribute traffic. Currently, the junior admin sets up each new environment by logging into the AWS Console and clicking through dozens of screens. It takes four hours, and every single time she forgets to enable termination protection on the RDS instance. The CTO is furious because an accidental deletion could lose customer data.
The senior DevOps engineer steps in and moves everything to CloudFormation. He writes a single YAML template containing:
An AWS::EC2::Instance resource with the correct AMI, security group, and user data script.
An AWS::RDS::DBInstance with Multi-AZ enabled and deletion protection on.
An AWS::S3::Bucket with versioning and encryption.
An AWS::ElasticLoadBalancingV2::LoadBalancer with a target group pointing to the EC2 instance.
Now, to create a new staging environment, the junior admin opens the AWS CLI and runs 'aws cloudformation create-stack --stack-name shopnow-staging --template-body file://template.yaml'. The entire provisioning completes in 12 minutes. The RDS instance automatically has deletion protection because the template specifies it. No forgotten settings. No four-hour manual marathons.
When the team needs to update the EC2 instance type from t2.micro to t3.medium for better performance, the engineer does not just change it in the console. Instead, he edits the template, runs 'aws cloudformation create-change-set --stack-name shopnow-staging --template-body file://updated-template.yaml --change-set-name upgrade-instance'. The change set tells him: 'Modify: EC2Instance - InstanceType from t2.micro to t3.medium'. He reviews it, sees no unintended deletions, and then executes the change set. The instance is updated with zero downtime if it is behind a load balancer. The junior admin learns that change sets are not optional - they are essential for safe deployments.
A month later, the company decides to decommission the staging environment after a project ends. Instead of manually terminating each resource and risking leaving an S3 bucket behind with sensitive data, the engineer simply runs 'aws cloudformation delete-stack --stack-name shopnow-staging'. CloudFormation tears down everything in the correct order - it first deletes the EC2 instance, then the load balancer, then the database, and finally the S3 bucket (which it empties if configured). No orphaned resources. The CTO sleeps better.
The practical skills the engineer uses daily are:
Writing and validating YAML templates using the AWS CloudFormation Designer or the 'cfn-lint' tool.
Using parameters to make templates reusable across dev, staging, and production.
Implementing stack policies to prevent accidental updates to critical resources like databases.
Creating nested stacks to organise large infrastructure into modular, reusable components.
Using 'aws cloudformation describe-stack-drift-detection-status' to check if anyone has manually changed a resource outside of CloudFormation.
The DVA-C02 exam tests Infrastructure as Code with CloudFormation heavily. You can expect at least 8-12 questions across the exam covering templates, stacks, change sets, and intrinsic functions. The exam does not test your ability to write a 500-line template from scratch. Instead, it tests your understanding of CloudFormation mechanics, the correct syntax for common scenarios, and your ability to spot the right approach among distractors.
The specific question types you will see are:
Scenario-based questions: They describe a business requirement (e.g., 'a developer wants to deploy a web application that must be repeatable across three AWS regions'). The answer choices offer different CloudFormation features. You must pick the correct feature - often using a single template with parameters and nested stacks across regions.
Syntax/code completion questions: They show a snippet of a CloudFormation template with a blank line. You must choose the correct YAML or JSON syntax to complete it. These test your knowledge of intrinsic functions like Ref, Fn::GetAtt, and Fn::Join, as well as the correct structure of a Parameters section.
Change set reasoning: They present a scenario where a developer updates a template and asks what happens next. The trap is that some answers suggest the change happens immediately. The correct answer always involves generating and reviewing a change set first.
Stack update failures: A question describes a stack update that fails partway through (e.g., a database replacement fails). The exam tests whether you know that CloudFormation rolls back the stack to its last known good state by default, and that you can disable rollback on failure using the '--disable-rollback' flag.
Drift detection: They test that drift occurs when someone modifies a resource outside CloudFormation (e.g., through the console). The correct approach is to run drift detection and then correct the resource to match the template.
The traps the exam sets are:
Confusing 'change set' with 'stack policy'. A change set previews changes; a stack policy prevents changes to specific resources. They are not the same.
Assuming CloudFormation automatically handles dependencies. It does for most cases, but you must explicitly list dependencies using the DependsOn attribute when the implicit dependency is not obvious.
Mixing up intrinsic functions: 'Ref' returns a resource's primary identifier (like an instance ID), while 'Fn::GetAtt' returns attribute values (like the public IP of an EC2 instance). The exam loves to offer 'Ref' when 'Fn::GetAtt' is needed.
Forgetting that CloudFormation templates are region-specific. A template that creates a VPC in us-east-1 cannot be run in eu-west-1 without changing the AMI IDs and other region-specific values. This is where parameters and mappings (Mappings section) come in.
The key definitions you must memorise are:
Template: the declarative file (JSON/YAML) that defines resources.
Stack: a collection of AWS resources managed as a single unit.
Change set: a summary of modifications to a stack before execution.
Stack policy: a JSON document defining which resources can be updated or deleted.
Drift: the difference between the actual resource state and the template definition.
Nested stack: a stack within another stack, created from a separate template URL.
Cross-stack reference: using Outputs to export values and Fn::ImportValue to import them.
You must also know the exam's favourite CloudFormation features:
AWS::CloudFormation::Interface: to organise parameters in the console.
Condition: using the Conditions section and Fn::If to conditionally create resources.
StackSets: to deploy stacks across multiple accounts and regions from a single template.
Custom resources: to invoke a Lambda function during stack creation/update/deletion for anything CloudFormation does not natively support.
CloudFormation is a declarative IaC service: you tell it what you want the end state to be, not how to get there.
Every CloudFormation resource lives inside a stack, which is the fundamental unit of management, deployment, and deletion.
Always create and review a change set before executing updates on a production stack to prevent unintended resource deletions or modifications.
Drift occurs when someone modifies a resource outside of CloudFormation; use the drift detection feature to identify and correct mismatches.
You can make templates reusable across environments by using Parameters and the Mappings section, avoiding hard-coded values.
Nested stacks and cross-stack references (via Outputs and Fn::ImportValue) let you organise large infrastructures into modular, manageable components.
CloudFormation automatically handles resource dependencies in most cases, but you can enforce an explicit ordering using the DependsOn attribute.
If a stack update fails, CloudFormation rolls back to the last stable state by default, not leaving partial resources behind.
Stack policies are separate from IAM policies; they control which resources in a stack can be updated or deleted, not who can perform actions.
The intrinsic function 'Ref' returns a resource's primary identifier (e.g., instance ID), while 'Fn::GetAtt' returns a specific attribute (e.g., PublicIp).
These come up on the exam all the time. Here's how to tell them apart.
CloudFormation Template
A file (JSON/YAML) that describes the desired infrastructure.
It is the blueprint, not the building.
You can reuse the same template to create many stacks.
Stack
The live collection of AWS resources created from a template.
It is the actual building that exists in your AWS account.
Each stack has its own lifecycle (create, update, delete).
Change Set
A preview of changes that will be made to a stack.
Used before executing an update to review what will be added, modified, or deleted.
It is a read-only summary; it does not prevent anything.
Stack Policy
A JSON document that defines which resources can be updated or deleted.
Used to protect critical resources (like a database) from accidental changes.
It actively enforces rules during any update or delete operation.
Ref Intrinsic Function
Returns the primary identifier of a resource (e.g., the physical ID of an EC2 instance).
Simpler syntax: !Ref LogicalName
Common use: passing an instance ID into another resource.
Fn::GetAtt Intrinsic Function
Returns a specific attribute of a resource (e.g., the PublicIp of an EC2 instance).
More precise syntax: !GetAtt LogicalName.AttributeName
Common use: getting the DNS name of a load balancer.
Nested Stack
A stack created inside another stack using a separate template URL.
All nested stacks are managed as part of the root stack's lifecycle.
Best for modularising a single application's infrastructure.
Cross-Stack Reference
Uses Outputs (with Export) in one stack and Fn::ImportValue in another.
Stacks remain independent but share values.
Best for sharing infrastructure across multiple applications (e.g., a shared VPC).
Stack Creation (CREATE_COMPLETE)
All resources are created from scratch.
Failure causes automatic rollback, deleting all created resources.
No change set is required; creation is a single operation.
Stack Update (UPDATE_COMPLETE)
Only changed resources are modified; unchanged ones remain.
Failure causes rollback to the previous state before the update.
Best practice is to first generate and review a change set.
Mistake
Once a stack is created, I can manually change any resource in the AWS Console and CloudFormation will automatically update the template to match.
Correct
Manually changing a resource through the console creates 'drift' - the actual resource differs from the template. CloudFormation does not update the template; you must either import the resource back into CloudFormation or correct the resource to match the template.
Beginners assume CloudFormation is a bi-directional sync tool like Google Drive. It is not. It only applies the template to AWS; it never reads changes made outside itself. This confusion leads to disaster in production.
Mistake
To update a running stack, I just edit the template and re-upload it. The changes take effect immediately.
Correct
You must create a change set first to preview the changes, then execute it. Direct template upload without a change set is possible via the CLI with '--capabilities' flags, but best practice is to always review a change set, especially in production.
In the exam and real life, the default behaviour of the 'aws cloudformation update-stack' command does actually execute immediately if you supply the template directly. Beginners see this and assume change sets are optional. The exam wants you to know the safe, recommended path: create a change set, review it, then execute.
Mistake
CloudFormation can create resources across multiple AWS accounts from a single stack without any special setup.
Correct
A single stack operates within one AWS account and one region. To deploy across accounts, you must use CloudFormation StackSets or organisations. A stack cannot cross account boundaries natively.
Beginners often confuse 'stack' (single account/region) with 'StackSet' (multi-account/region). The exam exploits this by offering StackSets as the correct answer for cross-account deployment scenarios.
Mistake
If a stack update fails, CloudFormation leaves all partially created resources in place so you can troubleshoot them.
Correct
By default, CloudFormation automatically rolls back a failed stack update to the last known good state, deleting any resources it created during the failed update. You can disable rollback with '--disable-rollback', but that leaves the failed resources in place.
Newcomers assume failure behaviour matches manual troubleshooting (leave things as they are to inspect). CloudFormation's rollback is designed for safety, not debugging, which catches people off guard.
Mistake
A CloudFormation template can only create resources, not update or delete them.
Correct
A template describes the desired end state. If you remove a resource from the template and update the stack, CloudFormation deletes that resource. If you change a property, CloudFormation updates it. The template is the full declaration of what the stack should look like, including removal.
Beginners think of templates as 'creation scripts' rather than 'desired state documents'. This misunderstanding leads to accidental deletions when they remove a resource from the template and are surprised it gets deleted.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
CloudFormation is AWS's native IaC service, free to use (you only pay for the resources it creates), and deeply integrated with AWS. Terraform is a multi-cloud tool from HashiCorp that can manage AWS, Azure, GCP, and on-premise infrastructure using a different language called HCL. For the DVA-C02 exam, you only need to know CloudFormation.
Yes, but you need to import them into CloudFormation using the `resource import` feature. You must have a template that describes the existing resource exactly as it is, and then run `aws cloudformation create-stack` or `update-stack` with the `--resources-to-import` parameter. The exam tests this scenario.
CloudFormation will refuse to delete the stack. You must first disable termination protection using the console or CLI (`aws cloudformation update-termination-protection --stack-name MyApp --enable-termination-protection false`), and then delete the stack. This is a common exam trap.
Use stack outputs in the source stack with the `Export` field, and then in the destination stack use the intrinsic function `Fn::ImportValue` to import the exported value. This is called a cross-stack reference. The exam loves to test this pattern.
A nested stack is a stack that is created inside another stack by referencing a separate template URL. You use it to break a large, complex template into smaller, reusable components (e.g., a network template, a database template). The outer stack is called the root stack. CloudFormation manages the nested stacks as part of the root stack's lifecycle.
Yes, by default, if a stack creation fails (e.g., an EC2 instance fails to launch), CloudFormation automatically rolls back and deletes any resources it created before the failure. You can disable this behaviour with `--disable-rollback`, but that leaves the partially created resources in place for debugging.
It explicitly tells CloudFormation to create a specific resource only after another resource has been created. For example, if your EC2 instance needs an Elastic IP that is not naturally referenced, you add `DependsOn: MyElasticIP` to the EC2 resource. The exam tests this when dependency ordering is not automatically inferred.
You've just covered Infrastructure as Code with AWS CloudFormation — now see how well it sticks with free DVA-C02 practice questions. Full explanations included, no account needed.
Done with this chapter?