[1] リソースのループ
[2] モジュールのループ
[1] リソースのループ
cat <<-'EOF' > main.tf
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_iam_user" "users01" {
for_each = toset(var.user_names)
name = each.value
}
EOF
cat <<-'EOF' > variables.tf
variable "user_names" {
description = "user_names"
type = list(string)
default = ["user01","user02","user03"]
}
EOF
cat <<-'EOF' > outputs.tf
output "all_users" {
value = aws_iam_user.users01
description = "all_users"
}
output "all_arns" {
value = values(aws_iam_user.users01)[*].arn
description = "all_arns"
}
EOF
terraform init
terraform fmt
terraform apply
terraform destroy
[2] モジュールのループ
-- メイン作成
cat <<-'EOF' > main.tf
provider "aws" {
region = "ap-northeast-1"
}
module "users" {
source = "./iamuser"
for_each = toset(var.user_names)
user_name = each.value
}
EOF
cat <<-'EOF' > variables.tf
variable "user_names" {
description = "user_names"
type = list(string)
default = ["user01","user02","user03"]
}
EOF
cat <<-'EOF' > outputs.tf
output "user_arn" {
value = values(module.users)[*].user_arn
description = "user_arn"
}
EOF
-- モジュール作成
mkdir -p iamuser
cat <<-'EOF' > ./iamuser/main.tf
resource "aws_iam_user" "moduleusers" {
name = "moduleusers_${var.user_name}"
}
EOF
cat <<-'EOF' > ./iamuser/variables.tf
variable "user_name" {
description = "user_name"
type = string
}
EOF
cat <<-'EOF' > ./iamuser/outputs.tf
output "user_arn" {
value = aws_iam_user.moduleusers.arn
description = "user_arn"
}
EOF
terraform init
terraform fmt
terraform apply
terraform destroy