Day 65 - Working with Terraform Resources 🚀  (Jan 30, 2024)

Day 65 - Working with Terraform Resources 🚀 (Jan 30, 2024)

🙏 Introduction:

In this blog, we will do hands-on practice on Terraform Resources.

🔶What is Terraform Resources?

  • A resource in Terraform represents a component of your infrastructure, such as a physical server, a virtual machine, a DNS record, or an S3 bucket. Resources have attributes that define their properties and behaviors, such as the size and location of a virtual machine or the domain name of a DNS record.

  • When you define a resource in Terraform, you specify the type of resource, a unique name for the resource, and the attributes that define the resource. Terraform uses the resource block to define resources in your Terraform configuration.

🎯Task: 1

Create a security group

  • In your main.tf file, add the following code to create a security group
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"]
  }
}
  • In this configuration, we first configure the AWS provider with the desired region.

  • Configure a security group using the aws_security_group resource block that allows incoming traffic on port 80 from any IP address. This ensures that we can access the website from the public internet.

terraform init

terraform plan

terraform apply

  • Check Security group

🎯Task: 2

Create an EC2 instance

  • In your main.tf file, add the following code to create an EC2 instance
resource "aws_instance" "web_server" {
  ami           = "ami-008fe2fc65df48dac"
  instance_type = "t2.micro"
  key_name      = "terra_key"
  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
}
  • When we launch an EC2 instance using Terraform with this user_data script, it will set up a web server serving the content of index.html on port 80. You can then access the website by navigating to the public IP address of your instance in a web browser

terraform init

terraform plan

terraform apply

  • EC2 instance is created