Open5
Terraformメモ
count
指定した数リソースを生成する。
インデックスでアクセス可能
resource "null_resource" "example" {
count = 3
provisioner "local-exec" {
command = "echo ${count.index}"
}
}
null_resource.example[0] (local-exec): 0
null_resource.example[1] (local-exec): 1
null_resource.example[2] (local-exec): 2
listとcountの組み合わせ
listの要素数だけs3バケットを作成
variable "bucket_names" {
description = "Names for the S3 buckets"
type = list(string)
default = ["111-first-bucket", "222-second-bucket", "333-third-bucket"]
}
resource "aws_s3_bucket" "example" {
count = length(var.bucket_names)
bucket = var.bucket_names[count.index]
}
$ terraform state list
aws_s3_bucket.example[0]
aws_s3_bucket.example[1]
aws_s3_bucket.example[2]
for_each
mapやsetから各要素を取り出すことができる
resource "null_resource" "example" {
for_each = {
a = "one"
b = "two"
}
provisioner "local-exec" {
command = "echo ${each.key} - ${each.value}"
}
}
null_resource.example["b"] (local-exec): b - two
null_resource.example["a"] (local-exec): a - one
for_eachを使用して3つのセキュリティグループを作成
セキュリティグループそれぞれを個別に定義する必要がなく、見やすい
provider "aws" {
region = "ap-northeast-1"
}
variable "security_groups" {
description = "A map of security group names and their inbound port numbers"
type = map(number)
default = {
web-sg = 80
ssh-sg = 22
database-sg = 3306
}
}
resource "aws_security_group" "my_security_groups" {
for_each = var.security_groups
name = each.key
description = "Security group for ${each.key}"
vpc_id = "vpc-xxxxxxxxxxxxxxx"
ingress {
from_port = each.value
to_port = each.value
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = each.key
}
}
for
各要素に対し処理を実行する
リスト作成
locals {
numbers = [1, 2, 3, 4]
doubled = [for n in local.numbers : n * 2]
}
output "doubled_numbers" {
value = local.doubled
description = "Numbers multiplied by 2"
}
Outputs:
doubled_numbers = [
2,
4,
6,
8,
]
map生成
locals {
fruit_colors = {
apple = "green"
banana = "yellow"
cherry = "red"
}
capitalized_colors = {for f, c in local.fruit_colors : f => upper(c)}
}
output "fruit_colors" {
value = local.fruit_colors
description = "fruit"
}
Outputs:
fruit_colors = {
"apple" = "green"
"banana" = "yellow"
"cherry" = "red"
}
条件分岐
locals {
numbers = [1, 2, 3, 4, 5]
evens = [for n in local.numbers : n if n % 2 == 0]
}
output "fruit_colors" {
value = local.evens
description = "evens"
}
Outputs:
evens_numbers = [
2,
4,
]