variable는 입력변수로 적절하게 우선순위를 이용해서 환경에 따른 정의를 해줄 수 있습니다.
항목
우선순위
Env
1 제일 낮음
terraform.tfvars
2
terraform.tfvars.json
3
.auto.tfvars
4
-var 혹은 -var-file
5 제일 높음
1. env (실행 후 입력)
var.my_var
Enter a value: var1
2. default 값
variable "my_var" {
default = "var2"
}
3. 환경 변수 (TF_VAR 변수 이름)
export TF_VAR_my_var=var3
echo $TF_VAR_my_var
4. terraform.tfvars에 정의된 변수 선언
echo 'my_var="var4"' > terraform.tfvars
cat terraform.tfvars
5. *.auto.tfvars에 정의된 변수 선언
echo 'my_var="var5_b"' > b.auto.tfvars
ls *.tfvars
6. *.auto.tfvars.json에 정의된 변수 선언
# a.auto.tfvars.json 파일 생성
cat <<EOF > a.auto.tfvars.json
{
"my_var" : "var6_a"
}
EOF
ls *.tfvars ; ls *.json
7. CLI 실행 시 -var 인수에 지정 또는 -var-file로 파일 지정
terraform apply -auto-approve -var=my_var=var7
cat abc.txt ; echo
3. local 지역 값
A. local 선언
local 변수는 외부에서 입력되지 않고, 코드 내에서만 동작하는 값으로 사용됩니다.
// 1. 선언되는 블록은 locals로 시작 (로컬 변수 이름은 전체 루트 모듈 내에서 유일)
locals {
content = "${var.prefix} ${local.name}"
}
locals {
content = "content2" // 중복 선언되어서는 안된다.
}
data "aws_ami" "my_amazonlinux2" {
most_recent = true
filter {
name = "owner-alias"
values = ["amazon"]
}
filter {
name = "architecture"
values = ["x86_64"]
}
owners = ["amazon"]
}
resource "aws_instance" "myec2" {
ami = data.aws_ami.my_amazonlinux2.id
instance_type = "t2.micro"
vpc_security_group_ids = ["${aws_security_group.mysg.id}"]
subnet_id = aws_subnet.mysubnet1.id
user_data = <<-EOF
#!/bin/bash
wget https://busybox.net/downloads/binaries/1.31.0-defconfig-multiarch-musl/busybox-x86_64
mv busybox-x86_64 busybox
chmod +x busybox
nohup ./busybox httpd -f -p 80 &
EOF
user_data_replace_on_change = true
tags = {
Name = "t101-myec2"
}
}
output "myec2_public_ip" {
value = aws_instance.myec2.public_ip
description = "The public IP of the Instance"
}
B. AWS IAM User 3명 생성/ 반복문 실습
```
provider "aws" {
region = "ap-northeast-2"
}
resource "aws_iam_user" "myiam" {
count = 3
name = "myuser.${count.index}"
}
```
iamuser를 3명 생성합니다.
```
variable "user_names" {
description = "Create IAM users with these names"
type = list(string)
default = ["gasida", "akbun", "hyungwook"]
}
provider "aws" {
region = "ap-northeast-2"
}
resource "aws_iam_user" "myiam" {
count = length(var.user_names)
name = var.user_names[count.index]
}
```
위와 같이 length 와 index를 활용해서 리소스 배열에 대한 IAM 유저를 생성할 수 있습니다.
variable "user_names" {
description = "Create IAM users with these names"
type = list(string)
default = ["gasida", "akbun", "hyungwook"]
}
// 위에서 밑으로 'AKBUN'을 제거하고 PLAN 하게 되면
// 모든 리소스를 삭제한 다음 해당 리소스를 처음부터 다시 만듬.
variable "user_names" {
description = "Create IAM users with these names"
type = list(string)
default = ["gasida", "hyungwook"]
}
// User with name hyungwook already exists -> 오류가 생성되면서 리소스 재생성함
``` variables.tf
variable "vpc_cidr" {
type = string
}
variable "subnets" { // 3. 다음과 같이 subnet에 대한 object를 생성해주기
type = list(object({ // subnet 설정 변수를 한 변수로 설정하도록 설정
cidr = string
az = string
tags = map(string)
}))
}
```
다음과 같이 깔끔하게 변수들로 vpc를 생성할 수 있습니다.
D. 주의사항: COUNT로 생성한 그룹은 임의로 변경하게 되면 모두 삭제되고 재 생성됩니다.
예시
subnets = [
#
# {
# cidr = "192.168.1.0/24",
# az = "ap-northeast-2a",
# tags = {
# Name = "public-subnet"
# Environment = "dev"
# }
# },
# {
# cidr = "192.168.5.0/24",
# az = "ap-northeast-2a",
# tags = {
# Name = "public-subnet"
# Environment = "dev"
# }
# },
{
cidr = "192.168.2.0/24",
az = "ap-northeast-2a",
tags = {
Name = "private-subnet"
Environment = "dev"
}
},
// 만약 다음과 같이 두개의 요소들에 대해서 주석처리하고 terraform apply 하게 되면
밑의 그림과 같이 인덱스값이 한칸씩 땡겨온다.
// 그로인해, RESOURCE 값이 제대로 생성되있지 않은것으로 보고, 모두 재생성하게 됩니다.
예상치 못한 장애 요소를 만날 수 있으니 foreach를 사용하라는 조언과 함께 2주차의 스터디는 마무리가 됐다.