First time at Zeet?

4 Apr
2024
-
20
min read

Terraform AWS RDS: Simplifying Relational Database Management in the Cloud

Simplify your management of relational databases in the cloud with Terraform AWS RDS. Learn to automate tasks and ensure optimal performance.

Jack Dwyer

Product
Platform Engineering + DevOps
Content
heading2
heading3
heading4
heading5
heading6
heading7

Share this article

Overview of Terraform AWS RDS

Terraform AWS RDS: Simplifying Relational Database Management in the Cloud

What is Tarraform AWS RDS? Amazon Relational Database Service (RDS) is a distributed database service from Amazon Web Services (AWS). It simplifies setting up, operating, and scaling relational databases in the cloud. RDS supports popular database engines like MySQL, PostgreSQL, Oracle, and SQL Server. With RDS, you can automate time-consuming tasks like hardware provisioning, database setup, patching, and backups. RDS also provides high availability and durability with automatic failover, read replicas, and backups.

Benefits of Using Terraform for AWS RDS

Infrastructure as Code

What is Terraform? It allows you to define and manage your infrastructure using declarative configuration files. This enables you to manage your AWS RDS resources in a version-controlled, repeatable, and consistent manner.

Version Control

Terraform configurations can be stored in version control systems like Git. This enables collaboration, tracking changes, and reverting to previous versions of your infrastructure.

Automated Deployments

Terraform can automatically provision and manage AWS RDS instances, reducing manual effort and ensuring consistent deployments. This automation speeds up the deployment process and reduces the chance of human error.

Resource Dependency Management

Terraform handles dependencies between resources, ensuring they are created and updated in the correct order. This eliminates the need to manually manage resource dependencies and ensures that your AWS RDS instances are created as expected.

Unlocking Cloud and Kubernetes Potential 

Zeet helps you to get more from your cloud, Kubernetes, and Terraform investments and helps your engineering team become strong individual contributors through our CI/CD & deployment platform. Contact Zeet to learn more about how Zeet help you get seamless cloud deployments every time, and helps your team to become a top-performing engineering team.

Related Reading

Prerequisites for an AWS RDS Database Instance

AWS Access Key and Secret Key

To interact with AWS services like RDS using Terraform, you need to provide valid AWS access credentials (access key and secret key). These credentials authenticate and authorize your requests to AWS.

Steps to create an IAM user and generate an access key and secret key

  • Sign in to the AWS Management Console and navigate to the IAM service.
  • Create a new IAM user or use an existing one with the necessary permissions (e.g., AmazonRDSFullAccess policy).
  • Generate an access key and secret key for the IAM user.
  • Store the access key and secret key securely, as they provide full access to your AWS account.

VPC and Subnets

RDS instances are deployed within a specific Virtual Private Cloud (VPC) and subnet. A VPC is a virtual network dedicated to your AWS account, and subnets are segmented sections within a VPC. Using separate subnets for RDS instances allows for network isolation and control.

The requirement of having a VPC and subnets set up beforehand

Before provisioning an RDS instance, you need to have a VPC and at least two subnets (for multi-AZ deployments) created. Alternatively, you can use the default VPC and subnets provided by AWS, but creating your own is recommended for better control and security.

Security Group

Security groups act as virtual firewalls, controlling inbound and outbound traffic to and from RDS instances. They allow you to specify rules for which IP addresses or security groups can access your RDS instance. Proper security group configuration is crucial for securing your database and limiting access only to authorized sources.

Need to create or have an existing security group for RDS

You must associate an RDS instance with at least one security group during provisioning. You can create a new security group specifically for RDS instances or use an existing one. Common rules include allowing inbound traffic from your application servers or specific IP ranges on the appropriate port (e.g., 3306 for MySQL, 5432 for PostgreSQL).

Zeet Terraform and Helm Product Overview

How to Create an AWS RDS Database Instance Using Terraform

Creating the Directory: Steps to Begin Your Terraform Configuration Journey

  • Open a terminal or command prompt.
  • Navigate to the desired location where you want to create the Terraform configuration directory.
  • Run the command mkdir rds-Terraform to create a new directory named 'rds-Terraform'.

Essential Files: Understand the Backbone of Your Terraform Configuration

  • main.tf: This file will contain the Terraform configuration for defining the RDS instance and other resources.
  • variables.tf: This file will define the variables used in the Terraform configuration, such as the RDS instance type, database name, and credentials.
  • Terraform.tfvars: This file will store the values for the variables defined in variables.tf.

Main.tf: Building the Foundation of Your AWS RDS Deployment

In this main.tf file, we'll define the AWS provider, RDS instance, and security group for our RDS instance.

Variables.tf: Understanding the Variables in Your Terraform Configuration

This file will define the variables used in the Terraform configuration, such as the RDS instance type, database name, and credentials.

Terraform.tfvars: Storing the Values for Your Variables

In this file, you'll store the values for the variables defined in variables.tf. You can set the values for variables like the RDS instance type, database name, and credentials here.

How to Create a New AWS RDS Database Instance Using Terraform

1. Create a new directory for your Terraform configuration files by following the steps outlined in the "Creating the Directory" section.

2. Now, create a new file named main.tf within the newly created directory.

3. Copy and paste the following code snippet into the main.tf file:

``` provider "aws" {  region = "us-east-1" } resource "aws_db_instance" "example" {  allocated_storage    = 20  storage_type         = "gp2"  engine               = "mysql"  engine_version       = "5.7"  instance_class       = "db.t2.micro"  name                 = "mydb"  username             = "foo"  password             = "bar"  tags = {    Name = "MyDB"  } }



4. Create a new file named variables.tf within the directory and add the following code snippet:

variable "aws_access_key" {} variable "aws_secret_key" {} variable "db_name" {  default = "mydb" } variable "db_username" {  default = "foo" } variable "db_password" {  default = "bar" }



5. Create a new file named Terraform.tfvars within the directory and add the following code snippet:

aws_access_key = "your-access-key" aws_secret_key = "your-secret-key"



6. Replace "your-access-key" and "your-secret-key" with your actual AWS access key and secret key in the Terraform.tfvars file.

Enhancing Cloud Infrastructure with Zeet

Zeet helps you to get more from your cloud, Kubernetes, and Terraform investments and helps your engineering team become strong individual contributors through our CI/CD & deployment platform. Contact Zeet to learn more about how Zeet help you get seamless cloud deployments every time, and helps your team to become a top-performing engineering team.

Configuring the AWS Provider

Configuring the AWS Provider Block in the main.tf file

In the main.tf file, you will need to specify the AWS provider block, which informs Terraform that you intend to use Amazon Web Services as the cloud provider and in which specific region. This block is essential as it defines the configuration for the AWS provider, including the region and access credentials.

Configuring the RDS Instance Resource in the main.tf file

To define the RDS instance resource in the main.tf file, you can utilize the `aws_db_instance` resource block. This block allows you to specify various parameters and options for configuring the RDS instance.

Here is an example code snippet for the `aws_db_instance` resource block:

hcl resource "aws_db_instance" "mydb" {  engine           = "mysql"  engine_version   = "5.7"  instance_class   = "db.t2.micro"  allocated_storage = 20  db_name          = "mydatabase"  username         = "myuser"  password         = "mypassword" }

Configuring Variables

Variables play a significant role in Terraform configurations. They enable parameterization of configurations which enhance reusability and flexibility. Variables can be defined in the `variables.tf` file and their values can be set in the `Terraform.tfvars` file or through other methods.

Here are examples of variables that can be defined in the `variables.tf` file for RDS:

hcl variable "instance_type" {  type    = string  default = "db.t2.micro" } variable "db_name" {  type    = string  default = "mydatabase" } variable "username" {  type    = string  default = "myuser" } variable "password" {  type    = string  default = "mypassword" }

Initializing the Directory

Initializing the Terraform directory

Before you can run Terraform commands, you need to initialize the Terraform directory by running the `Terraform init` command. This command downloads the necessary provider plugins and sets up the working directory.

Expected Output

shell $ Terraform init Initializing the backend... Initializing provider plugins...

Filling Variables in Terraform.tfvars

The `Terraform.tfvars` file is used to store the values for the variables defined in the `variables.tf` file. This separates the variable definitions from their values, making it easier to manage and change values without modifying the Terraform configuration.

Examples of variables to set in the `Terraform.tfvars` file

hcl region = "us-west-1" instance_type = "db.t2.micro" db_name = "mydatabase" username = "admin" password = "secretpassword"

Creating the Infrastructure

Purpose of the Terraform Plan Command

Before applying the Terraform configuration, it's recommended to run the `Terraform plan` command. This command creates an execution plan, showing you the changes that Terraform will make to your infrastructure without actually applying them. It's a good practice to review the plan to ensure that the intended changes are correct.

After running the `Terraform plan` command, Terraform will output an execution plan detailing the actions it will take with the resources on AWS. This output will show you if Terraform plans to create, modify, or delete resources based on the current configuration.

Terraform Apply Command and Its Purpose

After reviewing the execution plan, you can apply the Terraform configuration using the `Terraform apply` command. This command will create or update the specified resources in your AWS account based on the configuration.

It's essential to review the execution plan before applying changes to ensure that no unintended modifications will take place. This step mitigates the risks of applying incorrect configurations to your AWS resources.

Confirm and Execute the Terraform Apply Command

1. Run the `Terraform apply` command.
2. Terraform will prompt you to confirm the execution plan. Type 'yes' to confirm and proceed with the changes.
3. Terraform will start provisioning the resources according to the configuration.

After confirming the execution plan, Terraform will begin creating or updating the resources according to the specified configuration. The output will include details about the resources being modified and the progress of the provisioning process.

Accessing Your RDS Instance

Retrieving the RDS Endpoint from the Terraform Output

After running the Terraform apply command successfully, the Terraform output displays various details regarding the resources created or modified. To fetch the endpoint of the RDS instance, you can utilize this command:

This command will present the endpoint value saved in the Terraform output.

Connecting to Your RDS Instance

To connect to the RDS instance, you must use the endpoint from the Terraform output. Here are the general steps to connect to your RDS instance:

  • Install the appropriate database client tool (e.g., MySQL client, psql for PostgreSQL) on your local machine or application server.
  • Utilize the RDS endpoint and the database credentials (such as username and password) to establish a connection to the RDS instance.

Depending on your database engine and preference, you can utilize tools like the MySQL command-line client, MySQL Workbench, pgAdmin for PostgreSQL, or connect programmatically from your application using language-specific database drivers.

Related Reading

Terraform AWS RDS Provisioning Workflow

Developing and Testing Terraform Code Iteratively

Developing Terraform configurations is an iterative process. You'll likely need to modify your Terraform code multiple times to add or change resources, adjust configurations, or fix issues. It's recommended to follow best practices like writing modular and reusable code, testing your configurations locally before applying them to production environments, and using version control systems like Git to track changes and collaborate with others.

Version control and code reviews are crucial for managing changes to your Terraform code

Version control allows you to track the history of changes, roll back to previous versions if needed, and collaborate with teammates. Code reviews help identify issues, suggest improvements, and ensure that changes adhere to your organization's standards.

Provisioning RDS Instances Using Terraform

To provision an RDS instance using Terraform, follow these steps:

  • Set up the Terraform configuration files (main.tf, variables.tf, Terraform.tfvars)
  • Initialize the Terraform directory using Terraform init
  • Review the execution plan with Terraform plan
  • Apply the configuration with Terraform apply
  • Retrieve the RDS endpoint from the Terraform output

It's crucial to store sensitive information like database credentials securely. Instead of hardcoding them in your Terraform configuration or storing them in plaintext files, it's recommended to use secure storage solutions like AWS Secrets Manager.

Storing RDS Endpoint, Address, and Secret Manager Secret ARN in Terraform Output

Terraform allows you to output values from your configuration, which can be useful for retrieving the RDS endpoint and the ARN (Amazon Resource Name) of the Secret Manager secret containing your database credentials. You can then use these values in your applications or scripts to connect to the RDS instance securely.

Related Reading

Zeet Contact Us

Have Successful Releases Every Time With Zeet's CI/CD & Deployment Platform for Kubernetes and Terraform

Zeet provides a comprehensive solution to enhance your cloud, Kubernetes, and Terraform endeavors. By leveraging Zeet’s CI/CD and deployment platform, your engineering team can transform into powerful contributors in their field. Zeet specializes in streamlining cloud deployments, ensuring seamless transitions every time. 

With Zeet, your team will receive expert guidance on Terraform AWS RDS and other cloud technologies, setting the stage for top-tier performance from your engineers. Allow Zeet to revolutionize your cloud deployments and watch your team thrive in their roles. Contact Zeet today to learn more about how Zeet can help your organization reach new heights in its cloud deployments.

Subscribe to Changelog newsletter

Jack from the Zeet team shares DevOps & SRE learnings, top articles, and new Zeet features in a twice-a-month newsletter.

Thank you!

Your submission has been processed
Oops! Something went wrong while submitting the form.