Friday 10 December 2021

Terraform script to create a PostgreSQL database on AWS

This script will create a PostgreSQL database instance using the aws_db_instance resource. The aws_security_group resource is used to allow inbound traffic on port 5432, which is the default port used by PostgreSQL. The output block will display the endpoint of the database instance created.

You will need to set the appropriate values for the region, identifier, engine_version, instance_class, allocated_storage, username, and password parameters to match your specific requirements. You can also customize the security group rules and tags as needed.

Once you have saved this script to a .tf file, you can run terraform init, terraform plan, and terraform apply commands to provision the PostgreSQL database instance on AWS.

 

Terraform scripts:

provider "aws" {
  region = "us-west-2"
}

resource "aws_security_group" "postgres" {
  name_prefix = "postgres"
  ingress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_db_instance" "postgres" {
  identifier            = "my-postgres-db"
  engine                = "postgres"
  engine_version        = "12.4"
  instance_class        = "db.t2.micro"
  allocated_storage     = 10
  storage_type          = "gp2"
  username              = "postgres"
  password              = "mysecretpassword"
  skip_final_snapshot   = true
  vpc_security_group_ids = [aws_security_group.postgres.id]

  tags = {
    Name = "My PostgreSQL DB"
  }
}

output "database_endpoint" {
  value = aws_db_instance.postgres.endpoint
}


No comments:

Post a Comment