Variables
- terraform에는 변수가 존재한다.
- 변수의 타입은 string, number, bool, list, tuple, map, object가 있다.
- 코드의 재사용 측면에서 static하게 값을 넣은 코드보다는 변수를 사용하는 것이 좋다.
그리고 변수도 default 값 보다는 실제 입력을 받을 수 있는 부분은 받게끔 하는 것이 좋다.
[String]
- 문자열 값을 갖는다.
variable "vpc_name" {
type = string
default = "dev_vpc"
}
|
[number]
- 숫자 값을 갖는다.
variable "http_port" {
type = number
default = "8080"
}
|
[bool]
- boolean이다. true/false 값을 갖는다.
variable "sub_pub" {
type = bool
default = "true"
}
|
[list]
- 말 그대로 index 0 부터 시작하는 list 타입이다.
- type을 하나만 지정 가능하므로, list(string), list(number) 식으로 사용 가능하다.
variable "azs" {
type = list(string)
default = ["ap-northeast-2a", "ap-northeast-2c"]
}
|
[tuple]
- list처럼 사용하나, 여러 type을 사용할 수 있다.
variable "tuple" {
type = tuple([string, string, number])
default = ["ap-northeast-2a", "ap-northeast-2c",1]
}
|
[map]
- key = value로 저장할 수 있는 타입이다.
variable "availability_zones" {
type = map
default = {
"ap-northeast-2" = "ap-northeast-2a, ap-northeast-2b, ap-northeast-2c, ap-northeast-2d"
"ap-northeast-1" = "ap-northeast-1a, ap-northeast-1c, ap-northeast-1d"
}
}
|
[object]
- java의 class와 유사하다. object로 원하는 변수를 작성할 수 있다.
- map과 비슷하게 작성하나, 타입을 미리 지정한다는 차이가 있다.
variable "tf_sg" {
type = object({name = string, port = list(number)})
default = {
name = "tf_sg"
port = [22, 80, 443]
}
}
|
[input]
- default를 입력하지 않으면 외부로 부터 입력값을 받게 된다.
variable "vpc_name" {}
|
[validation]
그리고 variable 내부에서 validation block을 이용해서 유효성 체크를 할 수 있다.
validation 의 condition을 보면 var.image_id 값이 4글자 이상이고, 0번째 부터 4개의 문자열 값이 ami-와 일치하는지 체크한다. 그렇지 않다면 error_message 인수 값이 출력된다.
variable "image_id" {
type = string
description = "The id of the machine image (AMI) to use for the server."
validation {
condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
}
}
|
condition에 부합하면, True를 반환
부합하지 않는다면, false를 반환하면서 error_message 호출함
Input Variable
[1. 환경변수로 값 전달]
윈도우의 cmd의 set command는 먹히지 않음.ㅠ
다만, powershell의 set-item command는 먹힘
#linux
$ export TF_VAR_image_id = "ami-0eddbd81024d3fbdd"
#windows - powershell Set-Item -Path env:TF_VAR_image_id -Value “ami-0eddbd81024d3fbdd“
|
[2. .tfvars or .tfvars.json 으로 값 전달]
별도의 변수값 저장 파일을 생성하고, cmd에서 terraform apply -var-file "testkimtest.tfvar"
or terraform plan -var-file "testkimtest.tfvars" 형식으로 입력
사실 입력 안해도 해당 파일들을 알아서 읽어 온다.
그래도 한번 -var-file로 명시해서 적용해보자
- .tfvars
#testkimtest.tfvars
image_id = "ami-0eddbd81024d3fbdd"
|
- .tfvars.json
#testkimtest.tfvars.json
{
"image_id" : "ami-0eddbd81024d3fbdd"
}
|
[3. cmd에서 직접 입력]
값을 읽는 순서는 1.환경변수 > 2.[.tfvars 파일 > .tfvars.json 파일] > 3.cmd -var or -var-file 이다.
다만, 환경변수 값을 읽고 .tfvars파일을 읽을 때 값이 overwrite 된다.
결국 cmd -var로 input한 값이 최종 값이 되나, 환경변수부터 계속 overwrite 한다.
<자세한 내용은 공식문서 확인>
https://developer.hashicorp.com/terraform/language/values
실습
- 간단하게 variable을 이용해서 vpc와 az를 생성해보자. 큰 의미는 없지만 억지로 변수화 시켜서 진행해봤다.
실제론 이렇게 모든 부분을 변수로 하지 않는다.
variable.tf
variable "a_region" {
description = "seoul : ap-northeast-2, tokyo : ap-northeast-1"
type = string
}
variable "c_vpc_cidr" {
description = "10.x.x.x/16"
type = string
}
variable "d_sub_cidr" {}
variable "b_az" {
description = "az = a, b, c, d"
type = string
}
variable "e_pub_ip" {
description = "pub ip allocate : true/false"
type = bool
}
|
main.tf
provider "aws" {
region = "${var.a_region}"
}
resource "aws_vpc" "tf_test_vpc" {
cidr_block = "${var.c_vpc_cidr}"
}
resource "aws_subnet" "tf_test_subnet" {
vpc_id = aws_vpc.tf_test_vpc.id
availability_zone = "${var.a_region}${var.b_az}"
cidr_block = "${var.d_sub_cidr}"
map_public_ip_on_launch = "${var.e_pub_ip}"
}
|
input
PS C:\Terraform> terraform apply
var.a_region seoul : ap-northeast-2, tokyo : ap-northeast-1 Enter a value: ap-northeast-1 var.b_az az = a, b, c, d Enter a value: a var.c_vpc_cidr 10.x.x.x/16 Enter a value: 10.0.0.0/16 var.d_sub_cidr Enter a value: 10.0.0.0/24 var.e_pub_ip pub ip allocate : true/false Enter a value: true |
결과
'네트워크 & 클라우드 > 자동화' 카테고리의 다른 글
Terraform 기초 8 - Local (0) | 2022.12.02 |
---|---|
Terraform 기초 7 - Output (0) | 2022.12.01 |
Terraform 기초 5 - Data Block (0) | 2022.12.01 |
Terraform 기초 4 - Resource Block (0) | 2022.12.01 |
Terraform 기초 3 - Backend (1) | 2022.12.01 |