terraform.aws-baseline-infra/modules/compute/ec2/main.tf

64 lines
2.1 KiB
HCL

resource "aws_instance" "ec2-instance" {
ami = var.ami-id
instance_type = var.instance-type
associate_public_ip_address = var.asso-public-ip
// availability_zone = var.az
iam_instance_profile = var.instance-profile
key_name = var.key-name
private_ip = var.private-ip
root_block_device {
encrypted = var.ebs-encrypted
volume_size = var.root-volume-size
volume_type = var.root-volume-type
kms_key_id = var.kms-key-id
delete_on_termination = var.delete-on-termination
}
ebs_optimized = true
subnet_id = var.subnet-id
vpc_security_group_ids = var.security-groups
tags = merge(var.additional_tags, var.default-tags,
{ Name = var.instance-name }
)
volume_tags = merge(var.additional_tags, var.default-tags,
{ Name = var.instance-name }
)
# IMDSv2 requirement
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 2
}
}
resource "aws_ebs_volume" "data-volumes" {
for_each = var.data-volumes
availability_zone = aws_instance.ec2-instance.availability_zone
size = each.value["size"]
type = each.value["type"]
kms_key_id = aws_instance.ec2-instance.root_block_device[0].kms_key_id
encrypted = aws_instance.ec2-instance.root_block_device[0].encrypted
tags = merge(var.default-tags, { "Name" : "${var.instance-name}-${each.key}" })
}
locals {
# limited to 26 volumes
a_to_z = split(",", "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z")
}
resource "aws_volume_attachment" "data-volume-attachments" {
count = length(aws_ebs_volume.data-volumes)
volume_id = [for v in aws_ebs_volume.data-volumes : v.id][count.index]
instance_id = aws_instance.ec2-instance.id
device_name = "/dev/xvda${element(local.a_to_z, count.index)}"
}
resource "aws_eip" "ec2-eip" {
count = var.asso-eip ? 1 : 0
instance = aws_instance.ec2-instance.id
vpc = true
tags = merge(var.default-tags,
{ Name = var.instance-name }
)
}