ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Terraform] 테라폼 변수 Variables (8)
    공부 2025. 11. 18. 13:48

    Terraform에서 변수(Variables)란?

    • Terraform은 변수 블록(variable block) 통해 자주 사용하는 값을 재사용할 있게 해줌
    • 변수는 모듈에 인자를 전달하거나, 실행 시점에 값을 바꿔서 유연하게 인프라를 정의할 있음
    • 변수 타입은 string, number, bool, list, map, object 등 다양하게 지정 가능
    • terraform.tfvars 파일을 만들어 변수 값을 관리할 수도 있음
    • 여러 환경(dev, staging, prod)을 운영할 때 tfvars 파일을 분리해서 쓰면 편리함
    • 공식 문서: Terraform Input Variables

     

    변수 초기화

    당연한거지만 테라폼 변수는 초기화(initialization), 값을 넣어줘야 사용할 수 있다. 

    기본값이 안 들어간 상태로 variable block만 정의한 후, terraform plan명령어를 실행하면 변수를 초기화하는 프롬포트 창이 나온다.

    변수에 기본값을 지정 안하면 실행할 때 무엇으로 할지 물어본다.

    변수를 정의하는 방법에는 크게 두 가지가 있다. 

    1. 환경변수로 등록

    # 리눅스 환경변수 정의
    export TF_VAR_server_port=8080
    export TF_VAR_security_group_name="security_hello"
    
    #등록된 환경변수를 제거하고 싶다면 다음 명령어로 삭제
    # 리눅스 환경변수 삭제 방법
    # unset <환경변수 이름>

     

    2.기본값 설정

    variable "server_port" {
      description = "The port the server will use for HTTP requests"
      type        = number
      default = 80
    }
    
    variable "security_group_name" {
      description = "The name of the security group"
      type        = string
      default = "security_hello"
    }

     

    3.테라폼 인자 설정 

    plan 명령어 뒤에 변수 값을 설정 할 수 있다.

    terraform plan -var "security_group_name=security_hello" -var "server_port=80"

     

    변수 사용방법(입력, Input)

    1. 리소스에서 변수참조

    테라폼 코드에서 변수사용은 리소스 입력으로 사용

    리소스를 참조하는 방법은 var.{변수이름}을 참조하면 변수를 사용할 수 있다.

     

    2. 리소스 속성 안에서 변수 참조

    cat <<EOT > main.tf
    variable "server_port" {
      description = "The port the server will use for HTTP requests"
      type        = number
      default     = 8080
    }
    
    resource "local_file" "test" {
        content  = <<-EOF
                  #!/bin/bash
                  echo "My Web Server - var test" > index.html
                  nohup busybox httpd -f -p var.server_port &
                  EOF
        filename = "test.bar"
    }
    EOT

     

    위와 같이 선언해버리면 파일에는 지정한 포트넘버가 아닌, 변수가 문자열 그대로 입력되버린다.

    따라서 리소스 속성 안에서 변수를 참조할 때는 반드시  ${var.변수이름}으로 참조해야 한다.

     

     

Designed by Tistory.