This Terraform script is designed to create an AWS infrastructure for a simple web application. The infrastructure includes a Virtual Private Cloud (VPC), two subnets in different availability zones, an Internet Gateway, a Route Table, a Security Group, an S3 bucket, two EC2 instances, and an Application Load Balancer (ALB).
- AWS CLI configured with the necessary credentials.
- Terraform installed on your machine.
main.tf
: Defines the main infrastructure components.variables.tf
: Defines input variables used in the script.userdata.sh
: User data script for the first EC2 instance.userdata1.sh
: User data script for the second EC2 instance.
- Resource:
aws_vpc.myvpc
- Creates a Virtual Private Cloud (VPC) with the specified CIDR block.
- Resources:
aws_subnet.subnet1
andaws_subnet.subnet2
- Creates two subnets in different availability zones within the VPC.
- Resource:
aws_internet_gateway.igw
- Attaches an Internet Gateway to the VPC for internet access.
- Resources:
aws_route_table.RT
,aws_route_table_association.rta1
, andaws_route_table_association.rta2
- Creates a route table and associates it with the subnets for routing internet-bound traffic through the Internet Gateway.
- Resource:
aws_security_group.websg
- Creates a security group to control inbound and outbound traffic for the EC2 instances.
- Allows inbound traffic on ports 80 (HTTP) and 22 (SSH).
- Allows all outbound traffic.
- Resources:
aws_instance.webserver1
andaws_instance.webserver2
- Resources:
aws_lb.myalb
,aws_lb_listener.listener
,aws_lb_target_group.tg
,aws_lb_target_group_attachment.attach1
, andaws_lb_target_group_attachment.attach2
- Output:
loadbalancerdns
- Ran
terraform init
to initialize the working directory. - Ran
terraform plan
to see what the changes and infra will be made. - Ran
terraform apply
to create the AWS infrastructure. - Confirmed the changes by typing
yes
when prompted. - After completion, the DNS name of the ALB is displayed in the output.
To destroy the created infrastructure, run:
terraform destroy
Confirm the destruction by typing yes
when prompted.
- Ensure that sensitive information such as AWS credentials and private keys are handled securely.
- Review the AWS regions, availability zones, and AMI IDs based on your requirements.