Skip to main content

Command Palette

Search for a command to run...

Day 65 - Working with Terraform Resources

Updated
2 min read

Prerequisite :

If you have not installed terraform please follow my last few blogs.

Task 1: Create a security group

To start off, let's create a security group using Terraform. Open your security_group.tf file and add the following code:

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"]
  }
}

Make sure you have the provider.tf file configured as well:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
  }
}

# Configure the AWS Provider
provider "aws" {
  region = "us-east-2"
}

Now, let's run terraform init to initialize the project

followed by terraform plan to review the changes

and finally terraform apply to create the security group.

Congratulations! You have successfully created a security group for your EC2 instances.

Task 2: Create an EC2 instance

  • In the main.tf file, let's add the code to create an EC2 instance:
resource "aws_instance" "web_server" {
  ami           = "ami-024e6efaf93d85776"
  instance_type = "t2.micro"
  key_name      = "admin-ajay"
  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
}

Once again, let's run terraform plan to review the changes

followed by terraform apply to create the EC2 instance.

After the provisioning process completes, you can check the IP address of your newly created instance. You will find your website up and running.

That's all for today! If you have any queries or suggestions, please leave them in the comments. Stay tuned for more exciting challenges in the future.

More from this blog

Ajay Patel

116 posts