Create Server on AWS EC2 Instance with Terraform

Photo by Sigmund on Unsplash

Create Server on AWS EC2 Instance with Terraform

module/main.tf

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

provider "aws" {
  region     = var.region
  access_key = var.access_key
  secret_key = var.secret_key
}

resource "aws_instance" "default" {
  ami           = var.ami
  instance_type = var.instance_type

  tags = {
    Name = var.name
  }

  associate_public_ip_address = var.public_ip
  subnet_id                   = var.subnet_id
  key_name                    = var.key_name
  vpc_security_group_ids      = var.vpc_security_group_ids
}

Module/Output.tf

output "instance_id" {
  value = aws_instance.default.id
}

output "public_ip" {
  value = aws_instance.default.public_ip
}

Module/Vars.tf

variable "region" {
  type    = string
  default = "ap-southeast-1" //Region Jakarta
}

variable "access_key" {
  type    = string
  default = "AKIA4KA*********" //buat User di IAM AWS
}

variable "secret_key" {
  type    = string
  default = "6klZ95kRV+OZWC**********" //buat User di IAM AWS
}

variable "ami" {
  type    = string
  default = "ami-082b1f4237bd816a1" //lihat AMI ID saat create instance EC2 AWS
}

variable "instance_type" {
  type    = string
  default = "t2.medium" //lihat Instance Type saat create instance EC2 AWS
}

variable "name" {
  type = string
}

variable "public_ip" {
  type    = bool
  default = true
}

variable "subnet_id" {
  type    = string
  default = "subnet-0af42ddc7c8b1182f" //lihat di VPC AWS bagian subnet group
}

variable "key_name" {
  type    = string
  default = "****" //create Key di bagian IAM AWS
}

variable "vpc_security_group_ids" {
  type    = list(any)
  default = ["sg-03527e3d13cc3706c"] //lihat di bagian VPC AWS
}

server.tf

module "Jenkins-server" {
  source = "./module"
  name   = "Jenkins-server"
}

output "Jenkins_server_id" {
  value = module.Jenkins-server.instance_id
}

output "Jenkins_server_public_ip" {
  value = module.Jenkins-server.public_ip
}
$ terraform init
$ terraform plan
$ terraform apply