Terraform Project Structure

In this blog, we going variablise the files that we created in previous blogs.

let's modify the provider.tf with the below content.

provider "aws" {
  region     = "us-east-1"
  access_key = var.access_key
  secret_key = var.secret_key
}

modify instance.tf with the below content.

# creating instance.
resource "aws_instance" "web" {
  ami                    = var.image_id
  instance_type          = var.instance_type
  key_name               = aws_key_pair.key-tf.key_name
  vpc_security_group_ids = ["${aws_security_group.allow_tls.id}"]
  tags = {
    Name = "first-tf-instance"
  }
  user_data = file("${path.module}/script.sh")
}

modify aws-kp.tf with below content.

# creating ssh-key.
resource "aws_key_pair" "key-tf" {
  key_name   = "key-tf"
  public_key = file("${path.module}/id_rsa.pub")
}

modify aws-sg.tf with below content

# creating security group
resource "aws_security_group" "allow_tls" {
  name        = "allow_tls"
  description = "Allow TLS inbound traffic"
  dynamic "ingress" {
    for_each = var.ports
    iterator = port
    content {
      description = "TLS from VPC"
      from_port   = port.value
      to_port     = port.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
  egress {
    from_port        = 0
    to_port          = 0
    protocol         = "-1"
    cidr_blocks      = ["0.0.0.0/0"]
    ipv6_cidr_blocks = ["::/0"]
  }
}

create a new file variable.tf with the below content

variable "ports" {
  type = list(number)
}

variable "instance_type" {
  type = string
}

variable "access_key" {
  type = string
}

variable "secret_key" {
  type = string
}

variable "image_name" {
  type = string
}

now create a file terraform.tfvars file with the below contents.

ports         = [22, 80, 443, 3306, 27017, 1080]
instance_type = "t2.micro"
image_id      = "ami-0b0ea68c435eb488d"
access_key    = "YOUR_AWS_ACCESS_KEY"
secret_key    = "YOUR_AWS_SECRET_KEY"

Demo Video