๐Ÿ“‚ IaC/Terraform

TF 101 Study 3์ฃผ์ฐจ ๋„์ „ ๊ณผ์ œ - ์กฐ๊ฑด์‹, ํ•จ์ˆ˜, ํ”„๋กœ๋น„์ €๋„ˆ, ํ™˜๊ฒฝ ๋ณ€์ˆ˜, ํ”„๋กœ๋ฐ”์ด๋”

dhyuck 2023. 7. 23. 03:47
๋ฐ˜์‘ํ˜•
  • CloudNeta์˜ ๊ฐ€์‹œ๋‹ค๋‹˜์ด ์ง„ํ–‰ํ•˜์‹œ๋Š” Terraform 101 Study์— ์ฐธ๊ฐ€ํ•˜๋ฉฐ ์ž‘์„ฑํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.
  • ์Šคํ„ฐ๋”” ๊ต์žฌ โ†’ ํ…Œ๋ผํผ์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š” IaC

[3์ฃผ์ฐจ ๋„์ „๊ณผ์ œ] 1. ์กฐ๊ฑด๋ฌธ์„ ํ™œ์šฉํ•˜์—ฌ AWS ๋ฆฌ์†Œ์Šค ๋ฐฐํฌ


# ์ž…๋ ฅ ๋ณ€์ˆ˜๋กœ ๋ฐฐํฌ ํ™˜๊ฒฝ(dev, prod)๋ฅผ ๊ตฌ๋ถ„ํ•˜์—ฌ EC2 ์ธ์Šคํ„ด์Šค์˜ ์‚ฌ์ด์ฆˆ ์กฐ์ •ํ•˜๊ธฐ
variable "env" {}

resource "aws_instance" "app" {
  # ๋ฐฐํฌ ํ™˜๊ฒฝ์„ ์˜๋ฏธํ•˜๋Š” env ๋ณ€์ˆ˜๊ฐ€ prod๊ฐ€ ์•„๋‹ˆ๋ฉด EC2 ์ธ์Šคํ„ด์Šค๋Š” t3.micro๋กœ ๋ฐฐํฌํ•œ๋‹ค.
  instance_type = var.env != "prod" ? "t3.micro" : "m5.xlarge"
  ami           = "ami-0c9c942bd7bf113a2"
  tags = {
    Name = "app"
    env  = var.env
  }
}

[3์ฃผ์ฐจ ๋„์ „๊ณผ์ œ] 2. ๋‚ด์žฅ ํ•จ์ˆ˜๋ฅผ ํ™œ์šฉํ•˜์—ฌ AWS ๋ฆฌ์†Œ์Šค๋ฅผ ๋ฐฐํฌํ•˜๋Š” ์˜ˆ์ œ


  • cidrhost(๋‚ด์žฅ ํ•จ์ˆ˜)์™€ count๋ฅผ ์ด์šฉํ•˜์—ฌ 2๊ฐœ์˜ ENI๋ฅผ ์ƒ์„ฑํ•˜๊ณ  EC2์— attach ์‹œํ‚ค๊ธฐ
  • cidrhost : ์ฃผ์–ด์ง„ cidr ๋ธ”๋Ÿญ์—์„œ ์ธ๋ฑ์Šค์— ํ•ด๋‹นํ•˜๋Š” IP ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜
  • cidrhost("172.20.255.0/24", 10)์€ 172.20.255.10๋ฅผ ๋ฐ˜ํ™˜
# cidrhost(๋‚ด์žฅ ํ•จ์ˆ˜)์™€ count๋ฅผ ์ด์šฉํ•˜์—ฌ 2๊ฐœ์˜ ENI๋ฅผ ์ƒ์„ฑํ•˜๊ณ  EC2์— attach ์‹œํ‚ค๊ธฐ
resource "aws_instance" "app" {
  instance_type = "t3.medium"
  ami           = "ami-0c9c942bd7bf113a2"
  subnet_id     = "subnet-018bd7027b82d5e8e"
}

resource "aws_network_interface" "app_eni" {
  count     = 2
  subnet_id = "subnet-018bd7027b82d5e8e"

  # cidrhost : ์ฃผ์–ด์ง„ cidr ๋ธ”๋Ÿญ์—์„œ ์ธ๋ฑ์Šค์— ํ•ด๋‹นํ•˜๋Š” IP ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜
  # cidrhost("172.20.255.0/24", 10) -> 172.20.255.10
  private_ips = [
    cidrhost("172.31.255.0/24", (count.index * 5) + 10),
    cidrhost("172.31.255.0/24", (count.index * 5) + 11),
    cidrhost("172.31.255.0/24", (count.index * 5) + 12),
    cidrhost("172.31.255.0/24", (count.index * 5) + 13),
    cidrhost("172.31.255.0/24", (count.index * 5) + 14),
  ]

  attachment {
    instance     = aws_instance.app.id
    device_index = count.index + 1
  }
}

[3์ฃผ์ฐจ ๋„์ „๊ณผ์ œ] 6. provider alias๋กœ 2๊ฐœ์˜ ๋ฆฌ์ „(seoul, tokyo)์— S3 ๋ฐฐํฌํ•˜๊ธฐ


# provider alias๋กœ 2๊ฐœ์˜ ๋ฆฌ์ „(seoul, tokyo)์— S3 ๋ฐฐํฌํ•˜๊ธฐ
provider "aws" {
  region = "ap-northeast-1"
  alias  = "tokyo"
}

provider "aws" {
  region = "ap-northeast-2"
  alias  = "seoul"
}

resource "aws_s3_bucket" "hyuckang_tokyo" {
  provider = aws.tokyo
  bucket   = "hyuckang-bucket-tokyo"
}

resource "aws_s3_bucket" "hyuckang_seoul" {
  provider = aws.seoul
  bucket   = "hyuckang-bucket-seoul"
}

๋ฐ˜์‘ํ˜•