= Terraform AWS WebServer = **Summary**: This is a terraform deployment for an EC2 instance with a security group and the loading of user data. \\ **Date**: Around 2021 \\ **Refactor**: 26 January 2025: Checked links and formatting. \\ {{tag>aws terraform}} * Create a EC2 web server and output the public IP * Create a security group for the webserver opening port 80 and 443 * Run a script (user data) on the webserver == Uer Data == First the script to run, this needs to be in the same directory as the config file: #!/bin/bash sudo yum update sudo yum install -y httpd sudo systemctl start httpd sudo systemctl enable httpd echo "

Hello from Terraform

" | sudo tee /var/www/html/index.html
And now the config file: provider "aws" { profile = "terraform" } variable "ingressrules" { type = list(number) default = [80,443] } variable "egressrules" { type = list(number) default = [80,443] } resource "aws_instance" "web" { ami = "ami-0d1bf5b68307103c2" instance_type = "t2.micro" security_groups = [aws_security_group.webtraffic.name] user_data = file("server-script.sh") tags = { Name = "WebServer" Terraform = "True" } } resource "aws_eip" "elasticeip" { instance = aws_instance.web.id } resource "aws_security_group" "webtraffic" { name = "Allow Web Traffic" dynamic "ingress" { iterator = port for_each = var.ingressrules content { from_port = port.value to_port = port.value protocol = "TCP" cidr_blocks = ["0.0.0.0/0"] } } dynamic "egress" { iterator = port for_each = var.egressrules content { from_port = port.value to_port = port.value protocol = "TCP" cidr_blocks = ["0.0.0.0/0"] } } } output "webip" { value = aws_eip.elasticeip.public_ip }