参考文献: Terraform Up & Running (Yevgeniy Brikman著)
https://dev.to/hi_artem/terraform-interpolation-vs-directives-45f0
[1] countパラメータ
[2] if String Directive
[1] countパラメータ
cat <<-'EOF' > variables.tf
variable "apply" {
description = "apply"
type = bool
}
EOF
cat <<-'EOF' > main.tf
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_iam_user" "users01" {
count = var.apply ? 1 : 0
name = "user01"
}
EOF
terraform init
terraform fmt
terraform apply -auto-approve -var "apply=true"
terraform apply -auto-approve -var "apply=false"
export TF_VAR_apply=true
terraform apply -auto-approve
export TF_VAR_apply=false
terraform apply -auto-approve
terraform destroy -auto-approve
[2] if String Directive
cat <<-'EOF' > variables.tf
variable "names" {
description = "names"
type = list(string)
default = [ "user01", "user02" ]
}
variable "content" {
description = "content"
type = string
default = ""
}
EOF
cat <<-'EOF' > main.tf
resource "local_file" "file01" {
content = <<EOT
%{ if var.content != "" }${var.content}%{ else }NO CONTENT PROVIDED!%{ endif }
EOT
filename = "file01.txt"
}
EOF
cat <<-'EOF' > outputs.tf
output "outputnames" {
value = <<EOT
%{~ for i,name in var.names ~}
${name}%{ if i < length(var.names) - 1 }, %{ else }.%{ endif }
%{~ endfor ~}
EOT
}
EOF
terraform init
terraform fmt
terraform apply -auto-approve -var "content=AAA"
cat file01.txt
terraform apply -auto-approve
cat file01.txt
export TF_VAR_content=AAA
terraform apply -auto-approve
cat file01.txt
export -n TF_VAR_content
terraform apply -auto-approve
cat file01.txt
terraform destroy -auto-approve