Conditions et boucles 20 min de lecture

Count, for_each et conditions

Creer plusieurs ressources

count — Par nombre

resource "aws_instance" "web" {
  count         = 3
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"

  tags = {
    Name = "web-${count.index + 1}"
  }
}

# Acceder : aws_instance.web[0], aws_instance.web[1]

for_each — Par collection

variable "environments" {
  default = {
    dev  = "t2.micro"
    staging = "t2.small"
    prod = "t2.medium"
  }
}

resource "aws_instance" "env" {
  for_each      = var.environments
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = each.value

  tags = {
    Name        = "server-${each.key}"
    Environment = each.key
  }
}

# Acceder : aws_instance.env["dev"], aws_instance.env["prod"]

Condition ternaire

variable "environment" {
  default = "dev"
}

resource "aws_instance" "web" {
  instance_type = var.environment == "prod" ? "t2.large" : "t2.micro"
}

# Creation conditionnelle
resource "aws_cloudwatch_metric_alarm" "cpu" {
  count = var.environment == "prod" ? 1 : 0
  # ...
}

Blocs dynamiques

variable "ports" {
  default = [80, 443, 8080]
}

resource "aws_security_group" "web" {
  name = "web-sg"

  dynamic "ingress" {
    for_each = var.ports
    content {
      from_port   = ingress.value
      to_port     = ingress.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}
Regle : Preferez for_each a count quand les ressources ne sont pas interchangeables. Avec count, supprimer un element au milieu reindexe tout.