2. 변수
변수
varivale "NAME" {
[CONFIG ...]
}변수 선언의 본문에는 3개의 매개 변수가 포함된다.
description : 변수 설명
default : 변수에 값 전달, 파일 또는 환경 변수를 통해 변수에 값을 전달할 수 있다.
type : 변수의 유형으로 string(문자열), number(숫자), bool(불리언), list(리스트), map(맵), set(집합), object(객체), tuple(튜플) 등의 제약조건이 있다. 유형을 지정하지 않으면 any로 간주한다.
1. number
variable "number_example" {
description = "숫자 변수"
type = number
default = 42
}2. list
variable "list_example" {
description = "리스트 변수"
type = list
default = ["a", "b", "c"]
}3. list(number)
variable "list_numberic_example" {
description = "리스트의 모든 항목이 number"
type = list(number)
default = [1, 2, 3]
}4. map (모든 값이 string)
variable "map_example" {
description = "모든 값이 string인 map"
type = map(string)
default = {
key1 = "value1"
key2 = "value2"
key3 = "value3"
}
}5. object or tuple
variable "object_example" {
description = "구조적 유형"
type = object({
name = string
age = number
tags = list(string)
enable = bool
})
default = {
name = "value1"
age = 42
tags = ["a", "b", "c"]
enable = true
}
}사용 예제
variable "server_port" {
description = "HTTP 서비스"
type = number
default = 8080
}테라폼에서 입력 변수의 값을 사용할 때 아래의 표현식을 사용할 수 있다.
var.<VARIABLE_NAME>보안 그룹의 from_port 및 to_port 매개 변수를 server_port 변수의 값으로 설정
resource "aws_security_group" "instance" {
name = "terraform-example-instance"
ingress {
from_port = var.server_port
to_port = var.server_port
protocol = "tcp"
cidr_blocks = [ "0.0.0.0/0" ]
}
}또한 user_data에서 사용한 스크립트에서 포트를 설정할 때도 동일한 변수를 사용할 때 보간 (interpolcation)이라는 유형의 표현식을 사용해야 한다.
${var.<VARIABLE_NAME>}user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p 8080 &
EOF출력 변수
output "NAME" {
vlaue = <VALUE>
[CONFIG...]
}NAME은 출력 변수의 이름
VALUE는 출력하려는 테라폼 표현식
CONFIG는 2가지 매개변수를 추가로 포함할 수 있다.
description : 출력 변수에 어떤 유형의 데이터가 포함되어 있는지 알려준다.
sensitive : terrafrom apply 실행이 끝날 때 출력을 기록하지 않도록 지시하려면 sensitive 매개 변수를 true로 설정한다.
예제
생성한 EC2의 IP 주소를 찾는 출력 변수
output "public_ip" {
vlaue = aws_instance.example.public.ip
description = "인스턴스 공인 IP"
}PS C:\terraform_code> terraform apply
aws_security_group.instance: Refreshing state... [id=sg-011dcd15e128e905f]
aws_instance.example: Refreshing state... [id=i-019451b92b6530626]
Changes to Outputs:
+ public_ip = "...."terrafrom apply 명령어를 실행하면 콘솔에 출력 변수 표시 됨
terraform output <output_name>을 실행하여 특정 변수 값을 확인 할 수도 있다.
PS C:\terraform_code> terraform output
public_ip = "...."Last updated