Terraform modules
terraform/
├── modules/
│ └── networking/
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ └── README.md
├── main.tf
modules/networking/main.tf
resource "aws_security_group" "networking" {
name = "${var.vpc_name}"
description = "Allow public ports"
ingress = [
{
description = "HTTP"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
self = false
security_groups = []
prefix_list_ids = []
},
{
description = "SSH"
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
self = false
security_groups = []
prefix_list_ids = []
},
{
description = "ICMP"
from_port = -1
to_port = -1
protocol = "icmp"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
self = false
security_groups = []
prefix_list_ids = []
},
{
description = "Internal All"
from_port = 0
to_port = 0
protocol = -1
cidr_blocks = ["172.31.0.0/20"]
ipv6_cidr_blocks = ["::/0"]
self = false
security_groups = []
prefix_list_ids = []
}
]
egress {
description = "Outside All"
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
tags = {
Name = "${var.vpc_name}"
}
}modules/networking/variables.tf
variable "vpc_name" { type = string }modules/networking/outputs.tf
output "vpc_id" { value = aws_security_group.networking.id }main.tf
(...)
# Add module here
module "networking" {
source = "./modules/networking"
vpc_name = var.instance_prefix
}
resource "aws_instance" "instance" {
count = length(var.instance_name)
instance_type = var.instance_type
ami = data.aws_ami.rhel.id
user_data = data.template_file.user_data.rendered
vpc_security_group_ids = [ module.networking.vpc_id ] # <--- change here
tags = {
Name = "${var.instance_prefix}-${var.instance_name[count.index]}"
Group = "${var.instance_prefix}"
Role = "${var.instance_name[count.index]}"
}
}