Skip to main content
  1. Posts/

Creating RDS DB Instance from Snapshot using Terraform for DR

·2 mins

Here, we are going to see how to write Terraform configuration scripts to create a new RDS database instance using the latest snapshot which is created by the system as daily snapshots.

The main purpose of this configuration script is to use it in a Disaster Recovery situation, where the main RDS databases are down and we need to create a new RDS database instance using the latest snapshot created by the system — whether daily or weekly.

Provider block #

First we need the mandatory resource block known as the Provider block:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "3.74.1"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

Here we mention the provider we are using (AWS, GCP, Azure, etc.) and the region we are going to perform the task in.

Data block — fetch the latest snapshot #

Once the provider block is complete, we create the data block. It is used to fetch data from the cloud provider so we can use it in our Terraform script. In our task we are going to fetch the latest snapshot of our RDS DB, which is created on a scheduled interval:

# Get latest snapshot from RDS DB
data "aws_db_snapshot" "db_snapshot" {
  most_recent            = true
  db_instance_identifier = "<DB instance or cluster name>"
}
  • aws_db_snapshot — the resource we are fetching data from.
  • db_snapshot — the name of the data block we are creating.
  • most_recent — pull the latest RDS DB snapshot.
  • db_instance_identifier — the RDS snapshot DB instance or cluster name.

Resource block — create the new RDS instance #

Then we create a DB instance resource using the snapshot id fetched by the data block above:

# Create RDS instance from snapshot
resource "aws_db_instance" "recovered_db" {
  identifier          = "name-of-the-new-RDS"
  snapshot_identifier = data.aws_db_snapshot.db_snapshot.id
  skip_final_snapshot = true
}
  • aws_db_instance — the resource used to create a new RDS DB instance.
  • recovered_db — the name of the resource block we are creating.
  • identifier — the name of the new RDS DB instance.
  • snapshot_identifier — the snapshot id from the data block above.
  • skip_final_snapshot:
    • If true, when destroying the RDS DB, Terraform will skip taking a final snapshot.
    • If false, Terraform will take a final snapshot on destroy, and you must also specify:
      final_snapshot_identifier = "snapshot_name"
      

That’s it for the resource block for our use case.

By planning and applying this Terraform configuration script, we can create a new RDS DB instance using the latest RDS DB snapshot.

Thanks for reading — catch you in the next post.