Sub topic 6
Recreating infrastructure with infrastructure as code
This chapter assumes you can read CloudFormation or similar templates, know how Auto Scaling groups and launch templates work, and have seen the recovery targets (RTO and RPO) from the earlier chapters. The examples use CloudFormation, but the same ideas apply to Terraform and the AWS CDK.
Why recovery depends on code, not memory
Backups and replicated data restore your state. They do not restore the compute, network, and permissions that surround that state. If the primary Region is gone, someone has to produce a VPC, subnets, load balancers, Auto Scaling groups, IAM roles, and alarms in the recovery Region.
You can do that by hand from a wiki page, but it is slow and error-prone, and it happens during an incident. Infrastructure as code (IaC) is a description of your infrastructure in files that a tool turns into real resources. It gives you three things for DR:
- Repeatability. The recovery Region is built from the same definition as production, so it behaves the same way.
- Speed. A tool creates resources in parallel and in dependency order. A person clicking through a console does not.
- Reviewability. The DR design lives in version control, where you can diff and test it.
IaC is what makes the lower-cost strategies workable. In backup and restore, IaC is the only way to build the environment within your RTO. In pilot light, IaC scales a dormant core up to full size. Even in warm standby, it keeps the two Regions from drifting apart.
Where IaC fits in each strategy
| Strategy | What IaC does during recovery |
|---|---|
| Backup and restore | Creates the whole environment, then restores data into it |
| Pilot light | Creates the missing application tier, or raises capacity of resources that already exist |
| Warm standby | Raises capacity and keeps both Regions identical between disasters |
| Multi-site active/active | Deploys every change to all Regions, so no recovery build is needed |
The further you move toward active/active, the less recovery-time IaC you run. Routine deployments to every Region matter more.
Design the template to be Region-neutral
A template that works only in us-east-1 cannot recreate anything in us-west-2. Most failures at recovery time come from hard-coded, Region-specific values.
Values that differ between Regions include:
- AMI IDs. The same image has a different ID in each Region.
- Availability Zone names and subnet IDs.
- ARNs, which contain the Region name.
- KMS keys. A key in one Region cannot decrypt data in another unless it is a multi-Region key or the data was re-encrypted.
- S3 bucket names, which are global, so a replica bucket needs its own name.
- Service quotas, which are set per Region.
Pass these values in as parameters. Resolve them at deploy time where you can, for example with SSM parameters for public AMIs, or Region-keyed Mappings for your own image IDs. Do not paste them into the template body.
The following template defines an application tier whose size is a parameter. With AppCapacity set to 0 it is dormant, which is the pilot light setting. With a production-sized value it is a full fleet.
AWSTemplateFormatVersion: "2010-09-09"
Description: Application tier that can run dormant or at full size
Parameters:
LatestAmiId:
Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
SubnetIds:
Type: List<AWS::EC2::Subnet::Id>
AppCapacity:
Type: Number
Default: 0
MaxCapacity:
Type: Number
Default: 12
Resources:
AppLaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Properties:
LaunchTemplateData:
ImageId: !Ref LatestAmiId
InstanceType: t3.medium
AppGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
MinSize: !Ref AppCapacity
DesiredCapacity: !Ref AppCapacity
MaxSize: !Ref MaxCapacity
VPCZoneIdentifier: !Ref SubnetIds
LaunchTemplate:
LaunchTemplateId: !Ref AppLaunchTemplate
Version: !GetAtt AppLaunchTemplate.LatestVersionNumberIf you run your own AMIs, replace the SSM parameter with a parameter that takes the AMI ID, and copy each new image to the DR Region as part of your image pipeline. An AMI that exists only in the failed Region cannot launch anything.
Deploy the dormant stack ahead of time, then raise capacity during failover:
# Day to day: dormant DR stack
aws cloudformation deploy \
--region us-west-2 \
--stack-name app-dr \
--template-file app.yaml \
--parameter-overrides SubnetIds=subnet-0aaa1111,subnet-0bbb2222 AppCapacity=0
# During failover: same template, production-sized capacity
aws cloudformation deploy \
--region us-west-2 \
--stack-name app-dr \
--template-file app.yaml \
--parameter-overrides SubnetIds=subnet-0aaa1111,subnet-0bbb2222 AppCapacity=4Replace the subnet IDs with real ones from your DR VPC. Using the same stack and template for both runs keeps the dormant and active states from diverging.
Deploy to both Regions from one pipeline
The safest way to keep a DR Region current is to never treat it as a special case. Your delivery pipeline should deploy the same artifact to every target Region, with only parameters changing.
flowchart TDThe diagram follows. It is written in the required format below.
Two tools help here:
- CloudFormation StackSets deploy one template to many Regions and accounts in a single operation.
- A pipeline with one stage per Region works with any IaC tool. Terraform users typically do this with one workspace or backend state per Region.
Keep the pipeline itself out of the blast radius. If your CI/CD system runs only in the primary Region, you cannot deploy during a Region failure. Either run the pipeline in a separate Region, or keep a documented way to run the same deployment from an operator's workstation or a second pipeline.
Things IaC does not cover
IaC rebuilds resources. It does not rebuild everything an application needs.
- Data. A template can create an empty database. It cannot make that database contain last night's records. Restore from a backup or promote a replica as a separate step.
- Secrets. Do not put secret values in templates. Replicate secrets to the DR Region (Secrets Manager supports Region replication), and reference them by name.
- Manual changes. A setting changed in the console in production and never written back to code will be missing in the recovery build. This is configuration drift, the gap between what the code says and what is running. CloudFormation drift detection and periodic plan or diff jobs find these gaps.
- Quotas. A fleet of 40 instances fails to launch if the DR Region's vCPU quota allows only 10. Raise quotas ahead of time, and check them as part of testing.
- Capacity. Capacity in a Region is not guaranteed on demand. For strict RTOs, use On-Demand Capacity Reservations in the DR Region, which cost money while idle.
Ordering and dependencies
Some resources must exist before others, and some take a long time. Plan the order in your runbook and reflect it in separate stacks:
- Foundation: VPC, subnets, security groups, KMS keys, IAM roles. These are fast and rarely change.
- Data tier: database restore or replica promotion. This is usually the slowest step.
- Application tier: launch templates, Auto Scaling groups, load balancers.
- Traffic: DNS or Global Accelerator changes, done last, after health checks pass.
Splitting into layered stacks lets you deploy the foundation permanently (it costs almost nothing), and build only the later layers during an event. It also keeps a failed application deployment from rolling back your network.
Common errors
- Hard-coded AMI or subnet IDs. The stack fails with "image does not exist" in the new Region. Use parameters.
- Global name collisions. An S3 bucket or IAM role with a fixed name in the template fails because the name already exists (buckets) or the stack is deployed twice in one account (IAM roles are global). Let CloudFormation generate names, or include the Region in them.
- Customer-managed KMS key ARNs from another Region. Encrypted snapshot restores fail. Use a key in the DR Region, and specify it when copying or restoring.
- A DR template that nobody has changed in months. Production moved on, and the template no longer matches. Deploy through the same pipeline as production.
- State stored only in the failed Region. Terraform state in an S3 bucket in the primary Region is unreachable during an outage. Replicate it or keep a state backend per Region.
Exercise
Your DR stack template contains the line ImageId: ami-0abc1234def567890, copied from the production Region. It deploys without errors in a test, but the same deployment in the DR Region fails. Why, and what are two ways to fix it?
Show answer
AMI IDs are Region-specific, so an ID that is valid in the primary Region does not exist in the DR Region. Fix it by passing the AMI ID as a parameter (or resolving it from an SSM parameter or a Region-keyed Mappings table), and by copying your own AMIs to the DR Region in your image pipeline so a valid ID exists there.
Exercise
A team deploys its application with CloudFormation only to us-east-1 and says its DR plan is "run the template in us-west-2 if there is a disaster." Name three problems with this plan that IaC alone does not solve.
Show answer
Any three of these: the data is not restored or replicated by the template, so the new environment is empty; secrets and KMS keys do not exist in the DR Region; the pipeline or state backend may be unreachable during a primary Region outage; service quotas or instance capacity in the DR Region may be too low; and a template that has never been deployed in the DR Region probably contains Region-specific values and has never been tested.