Step 1: Create a Security Group
Open your main.tf file and add the following code:
Terraform
resource "aws_security_group" "web_server" {
  name_prefix = "web-server-sg"
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
Save the file.
Run terraform init to initialize the Terraform project.
Step 2: Initialize Terraform Project
Run terraform init in your terminal:
$ terraform init
This will initialize the Terraform project and download the necessary providers.
Step 3: Create the Security Group
Run terraform apply to create the security group:
$ terraform apply
Review the changes and type yes to confirm.
Step 4: Create an EC2 Instance
Add the following code to your main.tf file:
resource "aws_instance" "web_server" {
  ami           = "ami-0557a15b87f6559cf"
  instance_type = "t2.micro"
  key_name      = "my-key-pair"
  security_groups = [
    aws_security_group.web_server.name
  ]
  user_data = <<-EOF
              #!/bin/bash
              echo "<html><body><h1>Welcome to my website!</h1></body></html>" > index.html
              nohup python -m SimpleHTTPServer 80 &
              EOF
}
Replace the ami and key_name values with your own.
Save the file.
Step 5: Create the EC2 Instance
Run terraform apply to create the EC2 instance:
$ terraform apply
Review the changes and type yes to confirm.
Step 6: Access Your Website
Find the public IP address of your EC2 instance:
- Go to the AWS Management Console.
- Navigate to the EC2 dashboard.
- Find your instance and copy its public IP address.
- Open a web browser and navigate to http://:80. we should see the website we have created!
 

 
    
Top comments (0)