[0] Set와 Map형 변수
set : 유일한 값의 요소들로 이루어진 list
ex) [1, 2, 3]
map : Key-Value 형식의 데이터, key 값은 string이여야함
ex) { k : v, k2 : v2 }
[1] count를 이용한 방식
resource "aws_iam_user" "example" {
count = 3
name = "user${count.index}"
}
[2] foreach를 이용한 방식
Set 예제
variable "server_name" {
type = list(any)
default = ["web_1", "web_2", "web_3"]
}
resource "aws_instance" "app_server" {
ami = var.app_server_ami
instance_type = var.app_server_type
vpc_security_group_ids = ["sg-0250fa136bea5d3ba"]
for_each = toset(var.server_name)
tags = {
Name = "${each.value}"
}
}
output "app_server_public_ip" {
description = "aws instance public ip"
value = [ for server in aws_instance.app_server : server.public_ip]
}
Map 예제
variable "sg_list" {
type = map
default = {"ssh_sg":22, "web_sg":80, "was_sg":8009}
}
resource "aws_security_group" "my-sg" {
for_each = tomap(var.sg_list)
name = "${each.key}"
ingress {
from_port = "${each.value}"
to_port = "${each.value}"
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"]
ipv6_cidr_blocks = ["::/0"]
}
tags = {
Name = "${each.key}"
}
}
resource "aws_instance" "app_server" {
ami = var.app_server_ami
instance_type = var.app_server_type
for_each = tomap(var.sg_list)
vpc_security_group_ids = ["${each.key}"]
tags = {
Name = "${each.key}"
}
}
특정 영역에서만 반복하는 예제 (dynamic)
variable "ec2_ingress_ports_default" {
description = "Allowed Ec2 ports"
type = map
default = {
"22" = ["192.168.1.0/24"]
"443" = ["0.0.0.0/0"]
}
}
resource "aws_security_group" "ec2_allow_rule" {
dynamic ingress {
for_each = var.ec2_ingress_ports_default
content {
from_port = ingress.key
to_port = ingress.key
cidr_blocks = ingress.value
protocol = "tcp"
}
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "ec2_allow_rule"
}
}
output "ec2_allow_rule" {
description = "ec2_allow_rule_id"
value = aws_security_group.ec2_allow_rule.id
}
[1] count를 이용한 방법
variable "create_ec2" {
type= bool
default = 1
}
resource "aws_instance" "app_server" {
count = var.create_ec2 ? 1 : 0
ami = "ami-068a0feb96796b48d"
instance_type = "t2.micro"
key_name = "cloudkey"
tags = {
Name = "server"
}
}
terraform apply -var create_ec2=0
[2] 삼항연산자를 이용한 방법
조건 ? 조건이 참일때 : 조건이 거짓일 때
variable "create_ec2" {
type= string
default = "web"
}
var.create_ec2 == "web" ? 참일 때 : 거짓일 때