Suppose an AWS instance module should support Systems Manager without requiring every user to enable it. A boolean input can control that optional feature, giving users a simple on/off setting instead of asking them to choose a resource count. section 4.2.4
A Terraform conditional expression has the form `condition ? true_result : false_result`. The condition resolves to a boolean. Terraform returns the second expression when it is true and the third when it is false. This three-part form is also called a ternary operator; it can be used wherever an expression is allowed, not just with `count`. section 4.2.4
Toggle an optional resource
Set `count = var.enable_systems_manager ? 1 : 0` on a Systems Manager policy attachment. A true input creates one attachment; a false input creates none. The same pattern can select between a NAT Instance module and a NAT Gateway module by giving them opposite counts, then choosing the corresponding output. section 4.2.4 section 4.8.1
Listing 4.47 dynamic block toggle
resource "aws_security_group" "dynamic" {
name = "${var.name}-sg"
description = "The security group for an AWS Instance."
vpc_id = var.vpc_id
dynamic "ingress" { #1
for_each = var.enable_public_https ? ["placeholder"] : [] #2
#B
content {
description = "Enable global access to port 443 (HTTPS)."
from_port = 443 #3
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"] #4
}
}
egress { #5
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
ipv6_cidr_blocks = ["::/0"]
}
}
An optional HTTPS ingress block needs a different toggle: its `for_each` receives a one-item list when enabled and an empty list when disabled. The list item merely causes the block to exist; its value is not used. section 4.10
Not every `if` uses ternary syntax. In string templates, `%{ if ... }`, `%{ else }`, and `%{ endif }` select which text is emitted. In a `for` expression, a trailing `if` filters a collection, such as retaining only non-null values. Choose the form that matches the task: select a value, include template text, or filter items. section 4.4.3 section 4.9.3




















