# EC2 Instance for Docker Compose deployment resource "aws_security_group" "sysmonstm" { name_prefix = "${var.project_name}-" description = "Security group for System Monitor Platform" # HTTP/HTTPS ingress { from_port = 80 to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] description = "HTTP" } ingress { from_port = 443 to_port = 443 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] description = "HTTPS" } # gRPC for collectors ingress { from_port = 50051 to_port = 50051 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] description = "gRPC Aggregator" } # SSH (restricted) dynamic "ingress" { for_each = length(var.allowed_ssh_cidrs) > 0 ? [1] : [] content { from_port = 22 to_port = 22 protocol = "tcp" cidr_blocks = var.allowed_ssh_cidrs description = "SSH" } } egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] description = "Allow all outbound" } tags = { Name = "${var.project_name}-sg" } } resource "aws_iam_role" "ec2" { name_prefix = "${var.project_name}-ec2-" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "ec2.amazonaws.com" } } ] }) } resource "aws_iam_role_policy_attachment" "ec2_ssm" { role = aws_iam_role.ec2.name policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" } resource "aws_iam_instance_profile" "ec2" { name_prefix = "${var.project_name}-" role = aws_iam_role.ec2.name } resource "aws_instance" "sysmonstm" { ami = data.aws_ami.amazon_linux_2023.id instance_type = var.ec2_instance_type key_name = var.ec2_key_name != "" ? var.ec2_key_name : null vpc_security_group_ids = [aws_security_group.sysmonstm.id] iam_instance_profile = aws_iam_instance_profile.ec2.name root_block_device { volume_size = 20 volume_type = "gp3" encrypted = true } user_data = <<-EOF #!/bin/bash set -e # Install Docker dnf update -y dnf install -y docker git systemctl enable docker systemctl start docker # Install Docker Compose curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" \ -o /usr/local/bin/docker-compose chmod +x /usr/local/bin/docker-compose # Add ec2-user to docker group usermod -aG docker ec2-user # Clone and start the application cd /home/ec2-user git clone https://github.com/yourusername/sysmonstm.git || true cd sysmonstm # Create .env file cat > .env <