Content of provider.tf

provide.tf

provider "aws" {
    access_key = "${var.AWS_ACCESS_KEY}"
    secret_key = "${var.AWS_SECRET_KEY}"
    region = "${var.AWS_REGION}"
}

Content of vars.tf

Declaring your variables before using them. You can xpect those definitions to be in your vars.tf file or variables.tf. that the file can be named anything, since Terraform loads all files ending in .tf in a directory.

variable "AWS_ACCESS_KEY" {}
variable "AWS_SECRET_KEY" {}
variable "AWS_REGION" {
  default = "ap-south-1"
}
variable "AMIS" {
  type = "map"
  default = {
    ap-south-1 = "ami-5b673c34"
    us-west-2 = "ami-06b94666"
    eu-west-1 = "ami-844e0bf7"
  }
}

variable "PATH_TO_PRIVATE_KEY" {
  default = "final"
}
variable "PATH_TO_PUBLIC_KEY" {
  default = "final.pub"
}
variable "INSTANCE_USERNAME" {
  default = "ec2-user"
}

Content of terraform.tfvars

Assigning Variables using file. To persist variable values, create a file and assign variables within this file. Create a file named terraform.tfvars. For all files which match terraform.tfvars or *.auto.tfvars present in the current directory, Terraform automatically loads them to populate variables.

AWS_ACCESS_KEY = ""
AWS_SECRET_KEY = ""
AWS_REGION = ""

Content of instance.tf

resource "aws_key_pair" "mykey" {
  key_name = "mykey"
  public_key = "${file("${var.PATH_TO_PUBLIC_KEY}")}"
}
# Currently this resource requires an existing user-supplied key pair. This key pair's public key will be registered with AWS to allow logging-in to EC2 instances.

resource "aws_instance" "example" {
  ami = "${lookup(var.AMIS, var.AWS_REGION)}"
  instance_type = "t2.micro"
  key_name = "${aws_key_pair.mykey.key_name}"

  provisioner "file" {
    source = "script.sh"
    destination = "/tmp/script.sh"
  }
  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/script.sh",
      "sudo /tmp/script.sh"
    ]
  }
  connection {
    user = "${var.INSTANCE_USERNAME}"
    private_key = "${file("${var.PATH_TO_PRIVATE_KEY}")}"
  }
}

Content of script.sh

#!/bin/bash

# sleep until instance is ready
until [[ -f /var/lib/cloud/instance/boot-finished ]]; do
  sleep 1
done

# install nginx
yum update
yum -y install httpd

# make sure nginx is started
systemctl start httpd

Content of final.pub


ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCEIpfG61pvbsViVeTQfJYarf9WYiRWi7KuDS6XKV0C
t4AXpex7T8MPVGH1OZPTg7Y0kti+R0J0S+cRfTePfpbfi230PEJjJ/S9fVJx/BVohcYJUNHqWPXq9pkO
I1i41PywiX2u9P2KtCUdZFOIUznSan55RZS+0weURMijieBLGwzUHJWXYqbwB0M+3hLosiQQxpEqA7Nw
+65/Ir7phKZM8IX/W6RstilI//qfEZ1bRwDoIJ3wifTHI9gpj1MF3hEfq8N18XEeB9woPuz99RfOU4yj
xM5dod2qoHR39emQ/n5ORmhOTphobhWpMn99DvQrcSpJ6wPyKeI7IpxbcQ1N final