Create a PostgreSQL DB on AWS With Terraform

PostgreSQL is one of the most powerful and widely used databases in the world. This post will show how to create one on AWS with Terraform.

With Terraform infrastructure-as-a-code and the maturity level of AWS with Terraform creating resources on AWS with Terraform is very convenient and worth learning.

The following configuration will create a PostgreSQL version 13 database. The configuration also uses the random Terraform provider to create the password (password will be available in terraform.tfstate file). The DB instance will run on T3 medium instance.


To run the configuration, save the file below into a .tf file and run.

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "3.47.0"

provider "aws" {
  region = "ap-southeast-2"

provider "random" {
  # Configuration options

resource "random_password" "password" {
  length = 20
  special = false
  override_special = "_%@"

resource "aws_db_instance" "default" {
  allocated_storage    = 20
  engine               = "postgres"
  identifier           =  "dev-db"     
  engine_version       = "13"
  instance_class       = "db.t3.medium"
  name                 = "ntweeklydb001"
  username             = "dbadmin1"
  password             = random_password.password.result
  skip_final_snapshot  = true
  publicly_accessible  = true


Once you run the configuration, log in to the AWS console and copy the server address. To access the database, I am using pgadmin, as shown below.