상세 컨텐츠

본문 제목

[테라폼/Terraform]단일 웹 서버 배포

Development/테라폼

by J-Developer 2022. 5. 31. 14:20

본문

반응형

▶ main.tf 작성

- GCP 기준

provider "google" {
  credentials = file("key.json")
  project = "terraform-348208"
  region = "asia-northeast3"
}

resource "google_compute_instance" "example" {
  name = "webserver"
  machine_type = "f1-micro"
  zone = "asia-northeast3-a"

  boot_disk {
    initialize_params {
      image = "gcr.io/google-containers/busybox"
    }
  }

  network_interface {
    network = "default"
    access_config {}
  }

  tags = ["web"]

  metadata_startup_script = <<-EOF
              #!/bin/bash
              echo "Hello, World" > index.html
              nohup busybox httpd -f -p 8080 &
              EOF
}

resource "google_compute_firewall" "default" {
  name    = "webserver-firewall"
  network = "default"

  allow {
    protocol = "tcp"
    ports    = ["8080"]
  }

  source_tags = ["web"]
  target_tags = ["web"]
}

- AWS 기준

provider "aws" {
  region = "us-east-2"
}

resource "aws_instance" "example" {
  ami                    = "ami-xxxxxxxxxxx"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]

  user_data = <<-EOF
              #!/bin/bash
              echo "Hello, World" > index.html
              nohup busybox httpd -f -p 8080 &
              EOF

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

resource "aws_security_group" "instance" {

  name = var.security_group_name

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

variable "security_group_name" {
  description = "The name of the security group"
  type        = string
  default     = "terraform-example-instance"
}

output "public_ip" {
  value       = aws_instance.example.public_ip
  description = "The public IP of the Instance"
}

 

위의 소스는 인스턴스 생성 시 HTML 파일 생성 및 실행할 수 있도록 ‘metadata_startup_script’ 스크립트 작성을 합니다.

GCP에는 현재 busybox가 포함된 이미지가 없어서 예제로만 생각을 하면 됩니다.

그리고 tcp프로토콜로 8080포트를 허용하는 방화벽을 생성하여 인스턴스와 맵핑하였습니다.

책에서는 AWS 기준 인스턴스와 보안그룹을 생성하여 인스턴스에 보안그룹을 표현식으로 참조하고 있습니다.

 

더보기

※ 테라폼의 표현식

다른 리소스를 참조하기 위해서는 테라폼의 표현식을 알아야 합니다.

<PROVIDER>_<TYPE>.<NAME>.<ATTRIBUTE>

ex) aws_security_group.instance.id, google_compute_subnetwork.default.id

하나의 리소스에서 다른 리소스로 참조를 추가하면 내재된 종속성이 작성됩니다.

테라폼은 이러한 종속성 구문을 분석하여 그래프를 작성하고 이를 사용하여 리소스를 생성하는 순서를 자동으로 결정합니다.

아래 코드와 같이 graph 명령어를 실행하여 테라폼 종속성 그래프를 표시할 수 있습니다.

 

$ terraform graph

digraph {
        compound = "true"
        newrank = "true"
        subgraph "root" {
                "[root] google_compute_firewall.default (expand)" [label = "google_compute_firewall.default", shape = "box"]
                "[root] google_compute_instance.example (expand)" [label = "google_compute_instance.example", shape = "box"]
                "[root] provider[\"registry.terraform.io/hashicorp/google\"]" [label = "provider[\"registry.terraform.io/hashicorp/google\"]", shape = "diamond"]
                "[root] google_compute_firewall.default (expand)" -> "[root] provider[\"registry.terraform.io/hashicorp/google\"]"
                "[root] google_compute_instance.example (expand)" -> "[root] provider[\"registry.terraform.io/hashicorp/google\"]"
                "[root] provider[\"registry.terraform.io/hashicorp/google\"] (close)" -> "[root] google_compute_firewall.default (expand)"
                "[root] provider[\"registry.terraform.io/hashicorp/google\"] (close)" -> "[root] google_compute_instance.example (expand)"
                "[root] root" -> "[root] provider[\"registry.terraform.io/hashicorp/google\"] (close)"
        }
}

 

결과값으로는 DOT라는 언어로 되어 있으며, 그래프비즈 혹은 그래프비즈온라인(https://dreampuf.github.io/GraphvizOnline/) 같은 앱을 사용하면 그래프 이미지로 확인할 수 있습니다.

 

graph 결과

apply 명령어를 실행하면 새로운 인스턴스로(기존에 생성한 같은 인스턴스가 있을 시) 교체하고 방화벽을 생성합니다.

plan의 결과값에서 대체 작업을 찾으려면 ‘forces replacement’라는 문구를 찾으면 됩니다.

 

forces replacement

 

참조 : https://book.naver.com/bookdb/book_detail.naver?bid=20489970
 

테라폼 업앤러닝

이 책은 예제 소개를 뛰어넘어 실제 환경에서 테라폼을 사용하는 방법에 중점을 두고 만들어졌다. 외국어에 능통해지려면 원어민과 대화하고, 외국어 TV 쇼를 보고, 외국 음악을 듣는데 시간을

book.naver.com

 

반응형

관련글 더보기

댓글 영역