# Day 65 - Working with Terraform Resources

Prerequisite :

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

%[https://hashnode.com/post/cljbzmnad000109mv11753vyu] 

**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:

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687877933777/61b6b548-9bbf-47c7-9c24-51b260090fb2.png align="center")

Make sure you have the [`provider.tf`](http://provider.tf) file configured as well:

```bash
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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687878058618/34af93ba-d8f5-494b-9149-8f73eea90494.png align="center")

followed by `terraform plan` to review the changes

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687878154534/be67fda8-df86-4676-b815-a15dcdc4eede.png align="center")

and finally `terraform apply` to create the security group.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687878213530/ca9011d5-6481-4d10-8a89-7994a0a75bb1.png align="center")

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

**Task 2: Create an EC2 instance**

* In the [`main.tf`](http://main.tf) file, let's add the code to create an EC2 instance:
    

```bash
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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687878909964/6b822a68-adf2-4f6c-a6e1-abf5012a2160.png align="center")

followed by `terraform apply` to create the EC2 instance.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687878997731/42316f91-f4af-4b7b-b666-b2bd098f9ff8.png align="center")

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.
