count
parameter
Used for conditional resources.
Syntax of Terraform conditional expression:
<CONDITION> ? <TRUE_VAL> : <FALSE_VAL>
Example how this and count
can be utilized to conditionally create a resource:
Example of if-else:
data
sources can be referenced like so:
How to access attributes of conditionally created resources
A safer approach is to take advantage of the concat
and one
functions. The concat
function takes two or more lists as inputs and combines them into a single list. The one
function takes a list as input and if the list has 0 elements, it returns null
; if the list has 1 element, it returns that element; and if the list has more than 1 element, it shows an error. Putting these two together, and combining them with a splat expression, you get the following:
Limitations
You cannot reference any resource outputs in count
.
will produce:
Error: Invalid count argument
on main.tf line 30, in resource "aws_instance" "example_3":
30: count = random_integer.num_instances.result
The "count" value depends on resource attributes that cannot be determined
until apply, so Terraform cannot predict how many instances will be created.
To work around this, use the -target argument to first apply only the
resources that the count depends on.
Terraform requires that it can compute count
and for_each
during the plan
phase, before any resources are created or modified. This means that count
and for_each
can reference hardcoded values, variables, data sources, and even lists of resources (so long as the length of the list can be determined during plan
), but not computed resource outputs.
for_each
and for
expressions
Used for conditional resources and inline blocks within a resource.
Limitations
You cannot reference any resource outputs in for_each
, same as in [[Terraform conditionals#count
parameter#Limitations|count]].
if
string directive
Used for conditionals within a string
Syntax:
%{ if <CONDITION> }<TRUEVAL>%{ endif }
%{ if <CONDITION> }<TRUEVAL>%{ else }<FALSEVAL>%{ endif }
where CONDITION
is any expression that evaluates to a boolean and TRUEVAL
is the expression to render if CONDITION
evaluates to true, and FALSEVAL
is the expression to render if CONDITION
evaluates to false.
Example: