hahn

[Terraform] 참조 본문

클라우드/Terraform

[Terraform] 참조

hahn 2024. 8. 6. 03:44
728x90
반응형
terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "2.5.1"
    }
  }

  required_version = ">= 1.4"
}

resource "local_file" "test" {
  content  = "helloworld"
  filename = "helloworld.txt"
}

resource "local_file" "test1" {
  content  = local_file.test.content
  filename = "test.txt"
}

resource "local_file" "test2" {
  content  = "test2"
  filename = "test2.txt"
}

 

content = local_file.test.content

 

js의 this와 비슷한 느낌

 

 

실행결과 보면 test.txt에서 helloworld의 contents를 참조한걸 확인 가능

 

terraform graph > graph.dot

 

 

graphviz interactive preview를 extension하면 시각화 가능

 

 

추가로 실행 순서를 의도적으로 변경가능

 

terraform {
  required_providers {
    local = {
      source  = "hashicorp/local"
      version = "2.4.0"
    }
  }

  required_version = ">= 1.4"
}

resource "local_file" "test" {
  content  = "helloworld"
  filename = "helloworld.txt"
}

resource "local_file" "test1" {
  content  = local_file.test.content
  filename = "test.txt"
}

resource "local_file" "test2" {
  content  = "test2"
  filename = "test2.txt"

  depends_on = [local_file.test1]
}

 

 

depends_on = [local_file.test1] 

 

test1 block이 끝난 후 실행

 

 

추가로 

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

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

  subnet_id                 = "subnet-XXXXXXXXXXXXXX"
  vpc_security_group_ids    = [aws_security_group.example.id]
  associate_public_ip_address = true

  user_data = <<-EOF
              #!/bin/bash
              echo "terraformstudy" > index.html
              nohup busybox httpd -f -p 8080 &
              EOF
              
  tags = {
    Name = "terraform-ec2"
  }
}

resource "aws_security_group" "example" {
  vpc_id = "vpc-XXXXXXXXXXXXXX"
  name   = "example-security-group"

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

  ingress {
    from_port   = 8080
    to_port     = 8080
    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] VPC 생성  (0) 2024.08.06
[Terraform] AWS provider 생성  (0) 2024.08.06
[Terraform] helloworld 파일 생성  (0) 2024.08.06
[Terraform] 실행 준비, 적용, 삭제  (0) 2024.08.05
[Terraform] Install on Windows 10  (0) 2024.08.05