Skip to content

Commit 30d57bf

Browse files
committed
Clarify math operations available for interpolation
As reported in hashicorp#2782, the math operations, specifically subtraction, can cause unexpected behavior when resource or variable names use hyphens. I added clarification about using spaces with math operators as well as which operations are available.
1 parent 41c732d commit 30d57bf

1 file changed

Lines changed: 33 additions & 2 deletions

File tree

website/source/docs/configuration/interpolation.html.md

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ The interpolation syntax is powerful and allows you to reference
1717
variables, attributes of resources, call functions, etc.
1818

1919
You can also perform simple math in interpolations, allowing
20-
you to write expressions such as `${count.index+1}`.
20+
you to write expressions such as `${count.index + 1}`.
2121

2222
You can escape interpolation with double dollar signs: `$${foo}`
2323
will be rendered as a literal `${foo}`.
@@ -92,7 +92,7 @@ The supported built-in functions are:
9292
format. The syntax for the format is standard `sprintf` syntax.
9393
Good documentation for the syntax can be [found here](http://golang.org/pkg/fmt/).
9494
Example to zero-prefix a count, used commonly for naming servers:
95-
`format("web-%03d", count.index+1)`.
95+
`format("web-%03d", count.index + 1)`.
9696

9797
* `formatlist(format, args...)` - Formats each element of a list
9898
according to the given format, similarly to `format`, and returns a list.
@@ -201,3 +201,34 @@ resource "aws_instance" "web" {
201201

202202
With this, we will build a list of `template_file.web_init` resources which we can
203203
use in combination with our list of `aws_instance.web` resources.
204+
205+
## Math
206+
207+
Simple math can be performed in interpolations:
208+
209+
```
210+
variable "count" {
211+
default = 2
212+
}
213+
214+
resource "aws_instance" "web" {
215+
// ...
216+
count = "${var.count}"
217+
218+
// tag the instance with a counter starting at 1, ie. web-001
219+
tags {
220+
Name = "${format("web-%03d", count.index + 1)}"
221+
}
222+
}
223+
```
224+
225+
The supported operations are:
226+
227+
- *Add*, *Subtract*, *Multiply*, and *Divide* for **float** types
228+
- *Add*, *Subtract*, *Multiply*, *Divide*, and *Modulo* for **integer** types
229+
230+
-> **Note:** Since Terraform allows hyphens in resource and variable names,
231+
it's best to use spaces between math operators to prevent confusion or unexpected
232+
behavior. For example, `${var.instance-count - 1}` will subtract **1** from the
233+
`instance-count` variable value, while `${var.instance-count-1}` will interpolate
234+
the `instance-count-1` variable value.

0 commit comments

Comments
 (0)