Day 65 - Working with Terraform Resources ๐Ÿš€

ยท

2 min read

Day 65 - Working with Terraform Resources ๐Ÿš€

Yesterday, we delved into the basics of Terraform script creation with Blocks and Resources. Today, let's deepen our understanding of Terraform resources and unleash their potential.

Understanding Terraform Resources

In Terraform, a resource symbolizes a vital component of your infrastructure, be it a physical server, a virtual machine, a DNS record, or an S3 bucket. Each resource comes with attributes defining its properties and behaviors, such as the size and location of a virtual machine or the domain name of a DNS record. When defining a resource in Terraform, you specify its type, a unique name, and the attributes that characterize it, utilizing the resource block within your Terraform configuration.

Task 1: Creating a Security Group

To enable traffic to your EC2 instance, establishing a security group is essential. Here's how to do it:

  1. In your main.tf file, insert the following code snippet to create a security group:
hclCopy coderesource "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"]
  }
}
  1. Run terraform init to initialize the Terraform project.

  2. Run terraform apply to create the security group.

Task 2: Creating an EC2 Instance

Now, let's proceed to create an EC2 instance with Terraform:

  1. In your main.tf file, add the following code snippet to define an EC2 instance:
hclCopy coderesource "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
}
  1. Replace the ami and key_name values with your own.

  2. Run terraform apply to create the EC2 instance.

Task 3: Accessing Your Website

Now that your EC2 instance is up and running, you can access the website hosted on it:

Happy Terraforming! ๐ŸŒ

Thank you for reading this Blog. Hope you learned something new today! If you found this blog helpful, please like, share, and follow me for more blog posts like this in the future.

You can connect with me at: https://www.linkedin.com/in/davendersingh/

ย