Bu örnekte Postgres with Terraform için bir AWS RDS örneği oluşturacağız. Test amacıyla yerel makinemizden herkesin erişimine açık olacaktır. Aslına bakarsanız AWS RDS örneklerini doğrudan internet trafiğinden korumak için özel alt ağlarda sağlamanız gerekir. Bu şekilde genel bir alt ağda çalışan uygulamanız, özel alt ağda bulunan RDS'ye erişmiş olur.


Önkoşullar


IAM grubunuzun veya kullanıcınızın iam:*,ec2:*,rds:*,rds:* izinlerine sahip olduğundan emin olun. Ancak, ideal olarak minimum izinleri kullanmalısınız. Kesin izinleri belirlemek için iamlive gibi araçları kullanabilirsiniz.


export TF_VAR_username=SecretUsername
export TF_VAR_password=SecretPassword

[default]
region = eu-west-1
output = json

[profile development]
source_profile = default
role_session_name = github-actions
role_arn = arn:aws:iam::1234567890:role/devops-provisioner

[default]
aws_access_key_id = QWERTYUIO12345678
aws_secret_access_key = sdfg23456/DFGHJKL9876543+plv/dft543

Yapı


blog
└── terraform
└── development
├── aws_db_instance.tf
├── aws_security_group.tf
├── main.tf
├── outputs.tf
├── providers.tf
└── variables.tf

Dosyalar


variables.tf


variable "username" {
description = "The master username for the database."
type = string
sensitive = true
}

variable "password" {
description = "The master password for the database."
type = string
sensitive = true
}

main.tf


terraform {
required_version = "~> 1.4.4"

required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.30.0"
}
}
}

providers.tf


provider "aws" {
profile = "development"
region = "eu-west-1"
}

aws_security_group.tf


resource "aws_security_group" "postgres" {
name = "postgres-security-group"
description = "Security group for Postgres database"

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

egress {
protocol = -1
from_port = 0
to_port = 0
cidr_blocks = ["0.0.0.0/0"]
}
}

aws_db_instance.tf


resource "aws_db_instance" "blog" {
allocated_storage = 5
storage_type = "gp2"
instance_class = "db.t2.micro"
identifier = "blog"
engine = "postgres"
engine_version = "12.10"
parameter_group_name = "default.postgres12"

db_name = "blog"
username = var.username
password = var.password

vpc_security_group_ids = [aws_security_group.postgres.id]
publicly_accessible = true # Only for testing!
skip_final_snapshot = true
}

outputs.tf


output "blog_database" {
value = aws_db_instance.blog.endpoint
}

Çalıştırmak


RDS örneği oluşturmanın biraz zaman alacağını unutmayın.


$ terraform apply
...
aws_db_instance.blog: Creation complete after 3m37s [id=blog]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

blog_database = "blog.qwert12345.eu-west-1.rds.amazonaws.com:5432"

Örnek bağlantı dizeleri


postgres://SecretUsername:SecretPassword@blog.qwert12345.eu-west-1.rds.amazonaws.com:5432/blog
postgres://SecretUsername:SecretPassword@blog.qwert12345.eu-west-1.rds.amazonaws.com:5432/blog?sslmode=disable