hahn

[Terraform]VPC, Subnet, IGW, EC2 생성 본문

클라우드/Terraform

[Terraform]VPC, Subnet, IGW, EC2 생성

hahn 2024. 8. 6. 11:41
728x90
반응형
provider "aws" {
  region = "ap-northeast-2"
}

resource "aws_instance" "example" {
  ami           = "ami-XXXXXXXXXXXXXXX"
  instance_type = "t2.micro"

  subnet_id                 = aws_subnet.public.id
  vpc_security_group_ids    = [aws_security_group.sg.id]
  associate_public_ip_address = true

  user_data = <<-EOF
              #!/bin/bash
              sudo apt-get update -y
              sudo apt-get install -y apache2
              echo "terraform-apache-test" | sudo tee /var/www/html/index.html
              EOF

  tags = {
    Name = "terraform-ec2"
  }
}

resource "aws_vpc" "vpc_init" {
  cidr_block           = "172.16.0.0/16"
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Name = "terraform-vpc"
  }
}

resource "aws_subnet" "public" {
  vpc_id            = aws_vpc.vpc_init.id
  cidr_block        = "172.16.1.0/24"
  availability_zone = "ap-northeast-2a"

  tags = {
    Name = "terraform-public"
  }
}

resource "aws_route_table" "rt" {
  vpc_id = aws_vpc.vpc_init.id

  tags = {
    Name = "terraform-rt"
  }
}

resource "aws_route_table_association" "rt-association" {
  subnet_id      = aws_subnet.public.id
  route_table_id = aws_route_table.rt.id
}

resource "aws_route" "addrole" {
  route_table_id         = aws_route_table.rt.id
  destination_cidr_block = "0.0.0.0/0"
  gateway_id             = aws_internet_gateway.igw.id
}

resource "aws_subnet" "private" {
  vpc_id            = aws_vpc.vpc_init.id
  cidr_block        = "172.16.2.0/24"
  availability_zone = "ap-northeast-2a"

  tags = {
    Name = "terraform-private"
  }
}

resource "aws_internet_gateway" "igw" {
  vpc_id = aws_vpc.vpc_init.id

  tags = {
    Name = "terraform-igw"
  }
}

resource "aws_security_group" "sg" {
  vpc_id = aws_vpc.vpc_init.id
  name   = "terraform-sg"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 80
    to_port     = 80
    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"]
  }
}

 

728x90
반응형

'클라우드 > Terraform' 카테고리의 다른 글

[Terraform]Mutable, Immutable  (0) 2024.08.06
[Terraform]state  (0) 2024.08.06
[Terraform] 변수 사용하기  (0) 2024.08.06
[Terraform] VPC 생성  (0) 2024.08.06
[Terraform] AWS provider 생성  (0) 2024.08.06