본문 바로가기

퍼블릭 클라우드

[Terraform] 테라폼 인스턴스(public) 생성

반응형

테라폼 인스턴스(public) 생성

메인 모듈

$ vim main.tf
#####웹 서버
module "webserver" {
    source = "../../../modules/ec2/instance/"
    prefix = module.vpc.out_prefix
    suffix = module.vpc.out_suffix
    env = module.vpc.out_env
    region = module.vpc.out_region
    instance_count = 2
    name = "web1"
    group_name = "web"
    #aws_amis = "ami-03ca998611da0fe12"   
    instance_type = "t3a.medium"
    disk_size = "8"
    key_name = "keypem"
    subnet_id = module.vpc.out_public
    vpc_security_group_ids = ["sg-013dc", "sg-05f6f"]
    associate_public_ip_address = true
    customer_tags = {
        Environment = "env-prod",
        CreateUser = "terraform",
        Owner = "sangchul",
        Project = "blog",
        Role = "ec2",
        Service = "instance",
        CreatedDate = timestamp()
    }
}

인스턴트 모듈

$ vim instence.tf
resource "aws_instance" "this" {
  count = var.instance_count
  instance_type = var.instance_type
  ami = lookup(var.aws_amis, var.region)
  key_name = var.key_name
  subnet_id = element(var.subnet_id, count.index)
  vpc_security_group_ids = var.vpc_security_group_ids
  associate_public_ip_address = var.associate_public_ip_address
  monitoring = true
  root_block_device {
    volume_size = var.disk_size
  }
  connection {
    host = self.private_ip
    #host = self.public_ip
    type = "ssh"
    user = "ec2-user"
    private_key = file("~/aws-key/keypem.pem")
    #key_file = var.ssh_key_file
  }
  provisioner "remote-exec" {
    inline = [
      "sudo yum update -y",
      "sudo yum install -y httpd",
      "sudo service httpd start",
    ]
  }
  lifecycle {
    create_before_destroy = true
  }
  tags = merge(
    var.customer_tags, {
      Name = "${var.name}${count.index+1}",
      Group = "group-${var.group_name}"
    }
  )
}

$ vim vars.tf
variable "env" {}
variable "prefix" {}
variable "suffix" {}
variable "region" {}
variable "private_key_path" {}
variable "aws_amis" {
  type = map
  default = {
    "ap-southeast-1" = "ami-03ca998611da0fe12"
    "ap-northeast-2" = "ami-09282971cf2faa4c9"
    "us-east-1" = "ami-0742b4e673072066f"
  }
}
variable "disk_size" {}
variable "instance_count" {}
variable "name" {}
variable "group_name" {}
variable "instance_type" {}
variable "key_name" {}
variable "subnet_id" {}
variable "vpc_security_group_ids" {}
variable "associate_public_ip_address" {}
variable "customer_tags" {}

 

 

728x90
반응형