Build a complete web application infrastructure
This guide builds the complete infrastructure for a two-tier web application — a web tier and a database tier — with a single terraform apply command. You can use this configuration as a starting point for a real project. Every environment-specific value is in a variable, so you only need to edit one file to build a new environment.
Architecture
Internet
│
Floating IP │ Floating IP
┌──────────┴──────────┐
┌────────────────┼─────────────────────┼──────────── VPC ─┐
│ shop-staging-web-subnet (NAT_ROUTED, 10.50.1.0/24) │
│ shop-staging-web-sg (ACL): 80, 443, 22 from the office │
│ ┌──────────┴─────────┐ ┌─────────┴──────────┐ │
│ │ shop-staging-web-01│ │ shop-staging-web-02│ │
│ └──────────┬─────────┘ └─────────┬──────────┘ │
│ └──────────┬──────────┘ │
│ │ 5432, 22 │
│ shop-staging-db-subnet (ISOLATED, 10.50.2.0/24) │
│ shop-staging-db-sg (ACL): 5432, 22 from web subnet │
│ ┌──────────┴──────────┐ │
│ │ shop-staging-db-01 │── shop-staging- │
│ │ (10.50.2.10) │ db-data 100 GB │
│ └─────────────────────┘ │
└──────────────────────────────────────────────────────────┘
| Component | Purpose |
|---|---|
| Web subnet | Subnet for the web servers, with outbound Internet access through a NAT gateway. |
| Database subnet | Isolated Subnet for the database, with no route to the Internet. |
| 2 web Instances | Run the web application. Each Instance has a Floating IP. |
| 1 database Instance | Runs the database. The data is on a separate 100 GB disk. |
| Web Security Group | Allows HTTP and HTTPS from the Internet, and SSH only from the office network. |
| Database Security Group | Allows only the web servers to connect to the database and to SSH. |
| Tag | Attaches environment and project to every resource to track costs. |
Prerequisites
- ✅ You have completed Set up and configure.
- ✅ The VPC has enough quota for 2 Subnets, 3 Instances, 1 disk, 2 Floating IPs and 2 Security Groups.
- ✅ You have an RSA SSH key pair on your machine, for example
~/.ssh/id_rsa.pub. - ✅ You know the public address range of the office network, so that you can allow SSH only from there.
Folder structure
Create a folder named shop-infra with the following files. Splitting the files by function makes each part easy to find and review:
shop-infra/
├── versions.tf # Terraform and provider versions
├── variables.tf # variable declarations
├── terraform.tfvars # variable values of the environment
├── data.tf # VPC, image, flavor and storage policy lookups
├── tags.tf # shared tags
├── network.tf # Subnets
├── compute.tf # SSH key and Instances
├── storage.tf # data disk
├── security.tf # Security Groups and rules
├── public-ip.tf # Floating IPs
└── outputs.tf # information printed after apply
Declare versions and variables
# versions.tf
terraform {
required_version = ">= 1.5"
required_providers {
fptcloud = {
source = "fpt-corp/fptcloud"
version = "~> 0.3"
}
}
}
provider "fptcloud" {
timeout = 30
}
timeout = 30 makes Terraform wait up to 30 minutes for each operation, which suits creating many Instances at once.
# variables.tf
variable "vpc_name" {
description = "Name of the VPC to deploy to."
type = string
}
variable "environment" {
description = "Name of the environment, for example staging or production."
type = string
}
variable "project" {
description = "Name of the project, used as the prefix of resource names."
type = string
}
# variables.tf
variable "office_cidr" {
description = "Public IP range of the office, allowed to SSH to the web servers."
type = string
}
variable "ssh_public_key_path" {
description = "Path to the SSH public key."
type = string
default = "~/.ssh/id_rsa.pub"
}
variable "web_count" {
description = "Number of web Instances."
type = number
default = 2
}
# variables.tf
variable "attach_security_groups" {
description = "Set to false before destroy to detach the Security Groups from the Instances."
type = bool
default = true
}
The values of the environment are in terraform.tfvars. Replace the values below with your own information:
# terraform.tfvars
vpc_name = "example-vpc"
environment = "staging"
project = "shop"
office_cidr = "203.0.113.0/24"
web_count = 2
Look up information
Flavors are selected by hardware configuration, so the configuration runs in another VPC without changes:
# data.tf
data "fptcloud_vpc" "this" {
name = var.vpc_name
}
# data.tf
data "fptcloud_image" "ubuntu" {
vpc_id = data.fptcloud_vpc.this.id
filter {
key = "name"
values = ["UBUNTU-22.04"] # Replace with an image available in your VPC
match_by = "substring"
}
}
# data.tf
data "fptcloud_flavor" "web" {
vpc_id = data.fptcloud_vpc.this.id
filter {
key = "cpu"
values = ["2"]
}
filter {
key = "memory_mb"
values = ["4096"]
}
}
# data.tf
data "fptcloud_flavor" "db" {
vpc_id = data.fptcloud_vpc.this.id
filter {
key = "cpu"
values = ["4"]
}
filter {
key = "memory_mb"
values = ["8192"]
}
}
# data.tf
data "fptcloud_storage_policy" "ssd" {
vpc_id = data.fptcloud_vpc.this.id
filter {
key = "name"
values = ["Premium-SSD"] # Replace with a storage policy available in your VPC
}
}
Tags and name prefix
# tags.tf
resource "fptcloud_tagging" "environment" {
key = "environment"
value = var.environment
scope_type = "ORG"
}
resource "fptcloud_tagging" "project" {
key = "project"
value = var.project
scope_type = "ORG"
}
locals {
name_prefix = "${var.project}-${var.environment}"
tag_ids = [fptcloud_tagging.environment.id, fptcloud_tagging.project.id]
image_name = data.fptcloud_image.ubuntu.images[0].name
policy_id = data.fptcloud_storage_policy.ssd.storage_policies[0].id
}
If your organization already has the environment and project tags, read those tags with the fptcloud_tagging data source instead of creating new ones. See Tag examples.
Network
# network.tf
resource "fptcloud_subnet" "web" {
vpc_id = data.fptcloud_vpc.this.id
name = "${local.name_prefix}-web-subnet"
type = "NAT_ROUTED"
cidr = "10.50.1.0/24"
gateway_ip = "10.50.1.1"
tag_ids = local.tag_ids
}
resource "fptcloud_subnet" "db" {
vpc_id = data.fptcloud_vpc.this.id
name = "${local.name_prefix}-db-subnet"
type = "ISOLATED"
cidr = "10.50.2.0/24"
gateway_ip = "10.50.2.1"
tag_ids = local.tag_ids
}
Choose two CIDR ranges that do not overlap with the existing Subnets in the VPC.
Instance
# compute.tf
resource "fptcloud_ssh_key" "deployer" {
name = "${local.name_prefix}-deployer"
public_key = file(pathexpand(var.ssh_public_key_path))
}
resource "fptcloud_instance" "web" {
count = var.web_count
vpc_id = data.fptcloud_vpc.this.id
name = format("%s-web-%02d", local.name_prefix, count.index + 1)
image_name = local.image_name
flavor_name = data.fptcloud_flavor.web.flavors[0].name
subnet_id = fptcloud_subnet.web.id
storage_size_gb = 40
storage_policy_id = local.policy_id
ssh_key = fptcloud_ssh_key.deployer.public_key
status = "POWERED_ON"
tag_ids = local.tag_ids
}
# compute.tf
resource "fptcloud_instance" "db" {
vpc_id = data.fptcloud_vpc.this.id
name = "${local.name_prefix}-db-01"
image_name = local.image_name
flavor_name = data.fptcloud_flavor.db.flavors[0].name
subnet_id = fptcloud_subnet.db.id
private_ip = "10.50.2.10"
storage_size_gb = 40
storage_policy_id = local.policy_id
ssh_key = fptcloud_ssh_key.deployer.public_key
status = "POWERED_ON"
tag_ids = local.tag_ids
}
The database Instance has the fixed IP 10.50.2.10, so that the application configuration on the web servers points to an address that does not change.
Data disk
# storage.tf
resource "fptcloud_storage" "db_data" {
vpc_id = data.fptcloud_vpc.this.id
name = "${local.name_prefix}-db-data"
type = "EXTERNAL"
size_gb = 100
storage_policy_id = local.policy_id
instance_id = fptcloud_instance.db.id
tag_ids = local.tag_ids
}
Security Group
The private IPs of the Instances are read through the fptcloud_instance data source, because a newly created Instance may not report its IP right away:
# security.tf
data "fptcloud_instance" "web" {
count = var.web_count
vpc_id = data.fptcloud_vpc.this.id
id = fptcloud_instance.web[count.index].id
}
data "fptcloud_instance" "db" {
vpc_id = data.fptcloud_vpc.this.id
id = fptcloud_instance.db.id
}
# security.tf
resource "fptcloud_security_group" "web" {
vpc_id = data.fptcloud_vpc.this.id
name = "${local.name_prefix}-web-sg"
subnet_id = fptcloud_subnet.web.id
type = "ACL"
apply_to = var.attach_security_groups ? data.fptcloud_instance.web[*].private_ip : []
tag_ids = local.tag_ids
}
resource "fptcloud_security_group" "db" {
vpc_id = data.fptcloud_vpc.this.id
name = "${local.name_prefix}-db-sg"
subnet_id = fptcloud_subnet.db.id
type = "ACL"
apply_to = var.attach_security_groups ? [data.fptcloud_instance.db.private_ip] : []
tag_ids = local.tag_ids
}
# security.tf
locals {
web_rules = {
http = { port = "80", source = "ALL" }
https = { port = "443", source = "ALL" }
ssh = { port = "22", source = var.office_cidr }
}
db_rules = {
postgres = "5432"
ssh = "22"
}
}
# security.tf
resource "fptcloud_security_group_rule" "web" {
for_each = local.web_rules
vpc_id = data.fptcloud_vpc.this.id
security_group_id = fptcloud_security_group.web.id
direction = "INGRESS"
action = "ALLOW"
protocol = "TCP"
port_range = each.value.port
sources = [each.value.source]
description = "Allow ${each.key}"
}
# security.tf
resource "fptcloud_security_group_rule" "db" {
for_each = local.db_rules
vpc_id = data.fptcloud_vpc.this.id
security_group_id = fptcloud_security_group.db.id
direction = "INGRESS"
action = "ALLOW"
protocol = "TCP"
port_range = each.value
sources = [fptcloud_subnet.web.cidr]
description = "Allow ${each.key} from the web subnet"
}
The attach_security_groups variable lets you detach the Security Groups from the Instances before you delete the infrastructure. See Clean up.
Floating IP
# public-ip.tf
resource "fptcloud_floating_ip" "web" {
count = var.web_count
vpc_id = data.fptcloud_vpc.this.id
tag_ids = local.tag_ids
}
resource "fptcloud_floating_ip_association" "web" {
count = var.web_count
vpc_id = data.fptcloud_vpc.this.id
floating_ip_id = fptcloud_floating_ip.web[count.index].id
instance_id = fptcloud_instance.web[count.index].id
}
Outputs
# outputs.tf
output "web_public_ips" {
description = "Public addresses of the web servers."
value = fptcloud_floating_ip.web[*].ip_address
}
output "web_private_ips" {
description = "Private addresses of the web servers."
value = data.fptcloud_instance.web[*].private_ip
}
output "db_private_ip" {
description = "Private address of the database server."
value = data.fptcloud_instance.db.private_ip
}
Deploy
-
Open a terminal in the
shop-infrafolder and declare the connection information as described in Set up and configure. -
Download the provider:
terraform init -
Check the configuration syntax:
terraform validate -
Preview and save the plan:
terraform plan -out=tfplanWith
web_count = 2, the plan showsPlan: 20 to add, 0 to change, 0 to destroy. -
Apply exactly the plan that you reviewed:
terraform apply tfplan
Terraform creates the resources in dependency order: tags and Subnets first, then Instances, the disk, Security Groups and Floating IPs. The process usually takes 10 to 20 minutes. When it finishes, Terraform prints web_public_ips, web_private_ips and db_private_ip.
If web_private_ips or db_private_ip is empty after the first apply, run terraform apply again. The second run reads the IPs and attaches the Security Groups to the Instances.
Check the result
-
Open FPT Cloud Portal and check the following:
- Two Subnets, three Instances in the Running state, and the disk
shop-staging-db-dataattached toshop-staging-db-01. - Two Security Groups applied to the correct Instances.
- Two Floating IPs assigned to the two web servers.
- Two Subnets, three Instances in the Running state, and the disk
-
Log in to a web server from the office network through its Floating IP, with the default user of the image:
ssh -i ~/.ssh/id_rsa <user>@<web_public_ip> -
From the web server, connect to the database server through the private IP
10.50.2.10.
The data disk is empty. Before you install the database, format the disk as described in Storage Disks troubleshooting.
Change the infrastructure after deployment
| You want to | Edit | Result |
|---|---|---|
| Add a web server | web_count = 3 in terraform.tfvars | Adds an Instance and a Floating IP, and the new IP is added to the web Security Group. The existing Instances stay unchanged. |
| Increase the data disk size | size_gb = 200 in storage.tf | The disk is expanded in place. |
| Upgrade the database configuration | The filters of data.fptcloud_flavor.db | The Instance is resized in place. |
| Open another port for the web tier | Add an element to local.web_rules | Only the new rule is created, and the existing rules stay unchanged. |
Always run terraform plan and read the result carefully before you apply. See also Change and scale your infrastructure.
Clean up
FPT Cloud can only delete a Security Group when it is no longer attached to any Instance. For this reason, detach the Security Groups first, then delete the infrastructure:
-
Detach the Security Groups from the Instances:
terraform apply -var="attach_security_groups=false" -
Delete the whole infrastructure:
terraform destroy -var="attach_security_groups=false" -
Enter
yesto confirm.
terraform destroy permanently deletes every Instance, disk and the data on them. Back up the data that you need to keep before you run the command. This action cannot be undone.
Extend the configuration
- Spread the web servers across several physical servers: put the web Instances in an Instance Group with the Soft Anti Affinity policy. See Instance examples.
- Take a Snapshot before an upgrade: see Storage examples.
- Build several environments from the same configuration: see Organize configuration for several environments.