2014-07-28 19:43:00 +02:00
---
layout: "docs"
page_title: "Interpolation Syntax"
sidebar_current: "docs-config-interpolation"
2014-10-22 05:21:56 +02:00
description: |-
Embedded within strings in Terraform, whether you're using the Terraform syntax or JSON syntax, you can interpolate other values into strings. These interpolations are wrapped in `${}` , such as `${var.foo}` .
2014-07-28 19:43:00 +02:00
---
# Interpolation Syntax
Embedded within strings in Terraform, whether you're using the
2016-07-12 00:37:51 +02:00
Terraform syntax or JSON syntax, you can interpolate other values. These
interpolations are wrapped in `${}` , such as `${var.foo}` .
2014-07-28 19:43:00 +02:00
The interpolation syntax is powerful and allows you to reference
variables, attributes of resources, call functions, etc.
2016-12-08 02:49:13 +01:00
You can perform [simple math ](#math ) in interpolations, allowing
you to write expressions such as `${count.index + 1}` . And you can
also use [conditionals ](#conditionals ) to determine a value based
on some logic.
2015-04-03 16:51:12 +02:00
2015-05-14 05:22:14 +02:00
You can escape interpolation with double dollar signs: `$${foo}`
will be rendered as a literal `${foo}` .
2014-10-03 07:11:53 +02:00
## Available Variables
2016-10-29 02:13:09 +02:00
There are a variety of available variable references you can use.
2016-12-08 02:49:13 +01:00
#### User string variables
2016-10-29 02:13:09 +02:00
Use the `var.` prefix followed by the variable name. For example,
`${var.foo}` will interpolate the `foo` variable value.
2016-12-08 02:49:13 +01:00
#### User map variables
2016-10-29 02:13:09 +02:00
The syntax is `var.MAP["KEY"]` . For example, `${var.amis["us-east-1"]}`
would get the value of the `us-east-1` key within the `amis` map
variable.
2016-12-08 02:49:13 +01:00
#### User list variables
2016-10-29 02:13:09 +02:00
Stop requiring multi-vars (splats) to be in array brackets
Prior to Terraform 0.7, lists in Terraform were just a shallow abstraction
on top of strings with a magic delimiter between items. Wrapping a single
string in brackets in the configuration was Terraform's prompt that it
needed to split the string on that delimiter during interpolation.
In 0.7, when first-class lists were added, this convention was preserved
by flattening lists-of-lists by one level when they were encountered in
configuration. However, there was an oversight in that change where it
did not correctly handle the case where the inner list was unknown.
In #14135 we removed some code that was flattening partially-unknown lists
into fully-unknown (untyped) values. This inadvertently exposed the missed
case from the previous paragraph, causing issues for list-wrapped splat
expressions with unknown members. While this worked fine for resources,
due to some fixup done inside helper/schema, this did not work for other
interpolation contexts such as module blocks.
Various attempts to fix this up and restore the flattening behavior
selectively were unsuccessful, due to a proliferation of assumptions all
over the core code that would be too risky to change just to fix this bug.
This change, then, takes the different approach of removing the
requirement that splats be presented inside list brackets. This
requirement didn't make much sense anymore anyway, since no other
list-returning expression had this constraint and so the rest of Terraform
was already successfully dealing with both cases.
This leaves us with two different scenarios:
- For resource arguments, existing normalization code in helper/schema
does its own flattening that preserves compatibility with the common
practice of using bracketed splats. This change proves this with a test
within the "test" provider that exercises the whole Terraform core and
helper/schema stack that assigns bracketed splats to list and set
attributes.
- For arguments in other blocks, such as in module callsites, the
interpolator's own flattening behavior applies to known lists,
preserving compatibility with configurations from before
partially-computed splats were possible, but those wishing to use
partially-computed splats are required to drop the surrounding brackets.
This is less concerning because this scenario was introduced only in
0.9.5, so the scope for breakage is limited to those who adopted this
new feature quickly after upgrading.
As of this commit, the recommendation is to stop using brackets around
splats but the old form continues to be supported for backward
compatibility. In a future _major_ version of Terraform we will probably
phase out this legacy form to improve consistency, but for now both
forms are acceptable at the expense of some (pre-existing) weird behavior
when _actual_ lists-of-lists are used.
This addresses #14521 by officially adopting the suggested workaround of
dropping the brackets around the splat. However, it doesn't yet allow
passing of a partially-unknown list between modules: that still violates
assumptions in Terraform's core, so for the moment partially-unknown lists
work only within a _single_ interpolation expression, and cannot be
passed around between expressions. Until more holistic work is done to
improve Terraform's type handling, passing a partially-unknown splat
through to a module will result in a fully-unknown list emerging on
the other side, just as was the case before #14135; this change just
addresses the fact that this was failing with an error in 0.9.5.
2017-05-20 02:47:52 +02:00
The syntax is `"${var.LIST}"` . For example, `"${var.subnets}"`
2016-10-29 02:13:09 +02:00
would get the value of the `subnets` list, as a list. You can also
return list elements by index: `${var.subnets[idx]}` .
2016-12-08 02:49:13 +01:00
#### Attributes of your own resource
2016-10-29 02:13:09 +02:00
2017-08-23 18:41:16 +02:00
The syntax is `self.ATTRIBUTE` . For example `${self.private_ip}`
2016-10-29 02:13:09 +02:00
will interpolate that resource's private IP address.
-> **Note** : The `self.ATTRIBUTE` syntax is only allowed and valid within
provisioners.
2016-12-08 02:49:13 +01:00
#### Attributes of other resources
2016-10-29 02:13:09 +02:00
The syntax is `TYPE.NAME.ATTRIBUTE` . For example,
`${aws_instance.web.id}` will interpolate the ID attribute from the
2016-11-04 20:48:44 +01:00
`aws_instance` resource named `web` . If the resource has a `count`
2016-10-29 02:13:09 +02:00
attribute set, you can access individual attributes with a zero-based
index, such as `${aws_instance.web.0.id}` . You can also use the splat
syntax to get a list of all the attributes: `${aws_instance.web.*.id}` .
2017-05-02 16:17:24 +02:00
#### Attributes of a data source
The syntax is `data.TYPE.NAME.ATTRIBUTE` . For example. `${data.aws_ami.ubuntu.id}` will interpolate the `id` attribute from the `aws_ami` [data source ](/docs/configuration/data-sources.html ) named `ubuntu` . If the data source has a `count`
attribute set, you can access individual attributes with a zero-based
index, such as `${data.aws_subnet.example.0.cidr_block}` . You can also use the splat
syntax to get a list of all the attributes: `${data.aws_subnet.example.*.cidr_block}` .
2016-12-08 02:49:13 +01:00
#### Outputs from a module
2016-10-29 02:13:09 +02:00
The syntax is `MODULE.NAME.OUTPUT` . For example `${module.foo.bar}` will
interpolate the `bar` output from the `foo`
2014-10-03 07:11:53 +02:00
[module ](/docs/modules/index.html ).
2016-12-08 02:49:13 +01:00
#### Count information
2016-10-29 02:13:09 +02:00
The syntax is `count.FIELD` . For example, `${count.index}` will
interpolate the current index in a multi-count resource. For more
information on `count` , see the [resource configuration
page](/docs/configuration/resources.html).
2014-07-28 19:43:00 +02:00
2016-12-08 02:49:13 +01:00
#### Path information
2016-10-29 02:13:09 +02:00
The syntax is `path.TYPE` . TYPE can be `cwd` , `module` , or `root` .
`cwd` will interpolate the current working directory. `module` will
interpolate the path to the current module. `root` will interpolate the
path of the root module. In general, you probably want the
`path.module` variable.
2014-10-08 05:15:08 +02:00
2017-03-14 00:39:05 +01:00
#### Terraform meta information
The syntax is `terraform.FIELD` . This variable type contains metadata about
the currently executing Terraform run. FIELD can currently only be `env` to
reference the currently active [state environment ](/docs/state/environments.html ).
2016-12-08 02:49:13 +01:00
## Conditionals
Interpolations may contain conditionals to branch on the final value.
2017-04-05 17:29:27 +02:00
```hcl
2016-12-08 02:49:13 +01:00
resource "aws_instance" "web" {
subnet = "${var.env == "production" ? var.prod_subnet : var.dev_subnet}"
}
```
The conditional syntax is the well-known ternary operation:
2017-04-05 17:29:27 +02:00
```text
CONDITION ? TRUEVAL : FALSEVAL
```
2016-12-08 02:49:13 +01:00
The condition can be any valid interpolation syntax, such as variable
access, a function call, or even another conditional. The true and false
value can also be any valid interpolation syntax. The returned types by
the true and false side must be the same.
The support operators are:
* Equality: `==` and `!=`
* Numerical comparison: `>` , `<` , `>=` , `<=`
* Boolean logic: `&&` , `||` , unary `!`
A common use case for conditionals is to enable/disable a resource by
conditionally setting the count:
2017-04-05 17:29:27 +02:00
```hcl
2016-12-08 02:49:13 +01:00
resource "aws_instance" "vpn" {
count = "${var.something ? 1 : 0}"
}
```
In the example above, the "vpn" resource will only be included if
"var.something" evaluates to true. Otherwise, the VPN resource will
not be created at all.
2014-07-28 19:43:00 +02:00
## Built-in Functions
2016-10-29 02:13:09 +02:00
Terraform ships with built-in functions. Functions are called with the
syntax `name(arg, arg2, ...)` . For example, to read a file:
`${file("path.txt")}` .
### Supported built-in functions
2014-10-03 07:11:53 +02:00
2014-07-28 19:43:00 +02:00
The supported built-in functions are:
2017-09-25 23:19:18 +02:00
* `abs(float)` - Returns the absolute value of a given float.
Example: `abs(1)` returns `1` , and `abs(-1)` would also return `1` ,
whereas `abs(-3.14)` would return `3.14` . See also the `signum` function.
2017-03-27 03:21:48 +02:00
* `basename(path)` - Returns the last element of a path.
2015-10-04 00:12:51 +02:00
* `base64decode(string)` - Given a base64-encoded string, decodes it and
2015-10-03 23:49:50 +02:00
returns the original string.
2015-10-04 00:12:51 +02:00
* `base64encode(string)` - Returns a base64-encoded representation of the
2015-10-03 23:49:50 +02:00
given string.
2015-11-11 09:51:30 +01:00
* `base64gzip(string)` - Compresses the given string with gzip and then
encodes the result to base64. This can be used with certain resource
arguments that allow binary data to be passed with base64 encoding, since
Terraform strings are required to be valid UTF-8.
2016-01-29 13:11:40 +01:00
* `base64sha256(string)` - Returns a base64-encoded representation of raw
SHA-256 sum of the given string.
**This is not equivalent** of `base64encode(sha256(string))`
since `sha256()` returns hexadecimal representation.
2017-05-03 01:35:23 +02:00
* `base64sha512(string)` - Returns a base64-encoded representation of raw
SHA-512 sum of the given string.
**This is not equivalent** of `base64encode(sha512(string))`
since `sha512()` returns hexadecimal representation.
2017-05-22 12:02:32 +02:00
* `bcrypt(password, cost)` - Returns the Blowfish encrypted hash of the string
at the given cost. A default `cost` of 10 will be used if not provided.
2016-10-29 02:13:09 +02:00
* `ceil(float)` - Returns the least integer value greater than or equal
2016-10-28 19:49:31 +02:00
to the argument.
2017-04-06 13:14:09 +02:00
* `chomp(string)` - Removes trailing newlines from the given string.
2015-10-22 17:10:42 +02:00
* `cidrhost(iprange, hostnum)` - Takes an IP address range in CIDR notation
2017-04-19 13:26:49 +02:00
and creates an IP address with the given host number. If given host
number is negative, the count starts from the end of the range.
For example, `cidrhost("10.0.0.0/8", 2)` returns `10.0.0.2` and
`cidrhost("10.0.0.0/8", -2)` returns `10.255.255.254` .
2015-10-22 17:10:42 +02:00
* `cidrnetmask(iprange)` - Takes an IP address range in CIDR notation
and returns the address-formatted subnet mask format that some
systems expect for IPv4 interfaces. For example,
2016-12-15 18:10:01 +01:00
`cidrnetmask("10.0.0.0/8")` returns `255.0.0.0` . Not applicable
2015-10-22 17:10:42 +02:00
to IPv6 networks since CIDR notation is the only valid notation for
2017-01-17 16:40:56 +01:00
IPv6.
2015-10-22 17:10:42 +02:00
* `cidrsubnet(iprange, newbits, netnum)` - Takes an IP address range in
2016-10-29 02:13:09 +02:00
CIDR notation (like `10.0.0.0/8` ) and extends its prefix to include an
2015-10-22 17:10:42 +02:00
additional subnet number. For example,
2016-10-29 02:13:09 +02:00
`cidrsubnet("10.0.0.0/8", 8, 2)` returns `10.2.0.0/16` ;
`cidrsubnet("2607:f298:6051:516c::/64", 8, 2)` returns
`2607:f298:6051:516c:200::/72` .
2016-01-06 22:19:54 +01:00
2015-11-08 07:34:56 +01:00
* `coalesce(string1, string2, ...)` - Returns the first non-empty value from
the given arguments. At least two arguments must be provided.
2015-10-22 17:10:42 +02:00
2017-03-08 21:36:01 +01:00
* `coalescelist(list1, list2, ...)` - Returns the first non-empty list from
the given arguments. At least two arguments must be provided.
2015-10-11 08:59:21 +02:00
* `compact(list)` - Removes empty string elements from a list. This can be
useful in some cases, for example when passing joined lists as module
variables or when parsing module outputs.
Example: `compact(module.my_asg.load_balancer_names)`
2016-08-02 15:34:29 +02:00
* `concat(list1, list2, ...)` - Combines two or more lists into a single list.
2015-07-10 01:04:36 +02:00
Example: `concat(aws_instance.db.*.tags.Name, aws_instance.web.*.tags.Name)`
2014-08-19 22:16:29 +02:00
2017-06-16 20:38:01 +02:00
* `contains(list, element)` - Returns *true* if a list contains the given element
2017-10-17 16:25:09 +02:00
and returns *false* otherwise. Examples: `contains(var.list_of_strings, "an_element")`
2017-06-16 20:38:01 +02:00
2017-03-27 03:21:48 +02:00
* `dirname(path)` - Returns all but the last element of path, typically the path's directory.
2016-06-15 13:24:33 +02:00
* `distinct(list)` - Removes duplicate items from a list. Keeps the first
2016-09-12 08:04:04 +02:00
occurrence of each element, and removes subsequent occurrences. This
2016-07-27 19:47:44 +02:00
function is only valid for flat lists. Example: `distinct(var.usernames)`
2016-06-15 13:24:33 +02:00
2015-03-02 18:40:24 +01:00
* `element(list, index)` - Returns a single element from a list
at the given index. If the index is greater than the number of
elements, this function will wrap using a standard mod algorithm.
2016-07-27 19:47:44 +02:00
This function only works on flat lists. Examples:
* `element(aws_subnet.foo.*.id, count.index)`
* `element(var.list_of_strings, 2)`
2015-03-02 18:40:24 +01:00
2017-10-10 20:56:13 +02:00
* `chunklist(list, size)` - Returns the `list` items chunked by `size` .
Examples:
2017-11-17 01:07:44 +01:00
* `chunklist(aws_subnet.foo.*.id, 1)` : will outputs `[["id1"], ["id2"], ["id3"]]`
* `chunklist(var.list_of_strings, 2)` : will outputs `[["id1", "id2"], ["id3", "id4"], ["id5"]]`
2017-10-10 20:56:13 +02:00
2014-08-19 22:16:29 +02:00
* `file(path)` - Reads the contents of a file into the string. Variables
in this file are _not_ interpolated. The contents of the file are
2016-02-19 16:56:55 +01:00
read as-is. The `path` is interpreted relative to the working directory.
[Path variables ](#path-variables ) can be used to reference paths relative
to other base locations. For example, when using `file()` from inside a
module, you generally want to make the path relative to the module base,
like this: `file("${path.module}/file")` .
2014-07-28 19:43:00 +02:00
2016-10-28 19:49:31 +02:00
* `floor(float)` - Returns the greatest integer value less than or equal to
2016-10-29 02:13:09 +02:00
the argument.
2016-10-28 19:49:31 +02:00
2017-06-13 21:27:45 +02:00
* `flatten(list of lists)` - Flattens lists of lists down to a flat list of
primitive values, eliminating any nested lists recursively. Examples:
* `flatten(data.github_user.user.*.gpg_keys)`
2016-08-02 15:34:29 +02:00
* `format(format, args, ...)` - Formats a string according to the given
2015-03-02 19:27:58 +01:00
format. The syntax for the format is standard `sprintf` syntax.
2016-01-14 21:55:39 +01:00
Good documentation for the syntax can be [found here ](https://golang.org/pkg/fmt/ ).
2015-03-02 19:27:58 +01:00
Example to zero-prefix a count, used commonly for naming servers:
2015-08-04 20:09:43 +02:00
`format("web-%03d", count.index + 1)` .
2015-03-02 19:27:58 +01:00
2016-08-02 15:34:29 +02:00
* `formatlist(format, args, ...)` - Formats each element of a list
2015-05-06 05:34:40 +02:00
according to the given format, similarly to `format` , and returns a list.
Non-list arguments are repeated for each list element.
For example, to convert a list of DNS addresses to a list of URLs, you might use:
`formatlist("https://%s:%s/", aws_instance.foo.*.public_dns, var.port)` .
If multiple args are lists, and they have the same number of elements, then the formatting is applied to the elements of the lists in parallel.
Example:
`formatlist("instance %v has private ip %v", aws_instance.foo.*.id, aws_instance.foo.*.private_ip)` .
Passing lists with different lengths to formatlist results in an error.
2017-06-15 22:47:54 +02:00
* `indent(numspaces, string)` - Prepends the specified number of spaces to all but the first
line of the given multi-line string. May be useful when inserting a multi-line string
into an already-indented context. The first line is not indented, to allow for the
indented string to be placed after some sort of already-indented preamble.
Example: `" \"items\": ${ indent(4, "[\n \"item1\"\n]") },"`
2016-07-27 19:47:44 +02:00
* `index(list, elem)` - Finds the index of a given element in a list.
This function only works on flat lists.
Example: `index(aws_instance.foo.*.tags.Name, "foo-test")`
2015-07-12 21:55:19 +02:00
2016-07-27 19:47:44 +02:00
* `join(delim, list)` - Joins the list with the delimiter for a resultant string.
This function works only on flat lists.
Examples:
* `join(",", aws_instance.foo.*.id)`
* `join(",", var.ami_list)`
2014-10-10 06:23:49 +02:00
2017-05-28 01:58:40 +02:00
* `jsonencode(value)` - Returns a JSON-encoded representation of the given
value, which can contain arbitrarily-nested lists and maps. Note that if
the value is a string then its value will be placed in quotes.
2016-03-29 03:02:06 +02:00
2016-07-27 19:47:44 +02:00
* `keys(map)` - Returns a lexically sorted list of the map keys.
2016-06-29 21:11:08 +02:00
2016-10-29 02:13:09 +02:00
* `length(list)` - Returns the number of members in a given list or map, or the number of characters in a given string.
2015-04-15 19:55:49 +02:00
* `${length(split(",", "a,b,c"))}` = 3
* `${length("a,b,c")}` = 5
2016-07-27 19:47:44 +02:00
* `${length(map("key", "val"))}` = 1
2015-04-15 19:55:49 +02:00
2016-08-02 15:34:29 +02:00
* `list(items, ...)` - Returns a list consisting of the arguments to the function.
2016-07-07 14:19:41 +02:00
This function provides a way of representing list literals in interpolation.
* `${list("a", "b", "c")}` returns a list of `"a", "b", "c"` .
* `${list()}` returns an empty list.
2016-07-19 19:39:40 +02:00
2017-04-25 23:41:33 +02:00
* `log(x, base)` - Returns the logarithm of `x` .
2016-12-21 15:51:54 +01:00
* `lookup(map, key, [default])` - Performs a dynamic lookup into a map
2015-02-20 19:04:53 +01:00
variable. The `map` parameter should be another variable, such
2016-05-26 02:35:09 +02:00
as `var.amis` . If `key` does not exist in `map` , the interpolation will
fail unless you specify a third argument, `default` , which should be a
2016-07-27 19:47:44 +02:00
string value to return if no `key` is found in `map` . This function
only works on flat maps and will return an error for maps that
include nested lists or maps.
2014-11-07 19:23:02 +01:00
2016-01-11 04:39:20 +01:00
* `lower(string)` - Returns a copy of the string with all Unicode letters mapped to their lower case.
2015-10-20 03:49:51 +02:00
config: Add map() interpolation function
* `map(key, value, ...)` - Returns a map consisting of the key/value pairs
specified as arguments. Every odd argument must be a string key, and every
even argument must have the same type as the other values specified.
Duplicate keys are not allowed. Examples:
* `map("hello", "world")`
* `map("us-east", list("a", "b", "c"), "us-west", list("b", "c", "d"))`
2016-07-27 19:42:46 +02:00
* `map(key, value, ...)` - Returns a map consisting of the key/value pairs
specified as arguments. Every odd argument must be a string key, and every
even argument must have the same type as the other values specified.
Duplicate keys are not allowed. Examples:
* `map("hello", "world")`
* `map("us-east", list("a", "b", "c"), "us-west", list("b", "c", "d"))`
2017-05-05 16:24:03 +02:00
* `matchkeys(values, keys, searchset)` - For two lists `values` and `keys` of
equal length, returns all elements from `values` where the corresponding
element from `keys` exists in the `searchset` list. E.g.
`matchkeys(aws_instance.example.*.id,
aws_instance.example.*.availability_zone, list("us-west-2a"))` will return a
list of the instance IDs of the `aws_instance.example` instances in
`"us-west-2a"` . No match will result in empty list. Items of `keys` are
processed sequentially, so the order of returned `values` is preserved.
2016-10-28 19:49:31 +02:00
* `max(float1, float2, ...)` - Returns the largest of the floats.
2016-08-02 15:33:08 +02:00
* `merge(map1, map2, ...)` - Returns the union of 2 or more maps. The maps
2016-08-17 23:07:52 +02:00
are consumed in the order provided, and duplicate keys overwrite previous
2016-08-02 15:33:08 +02:00
entries.
* `${merge(map("a", "b"), map("c", "d"))}` returns `{"a": "b", "c": "d"}`
2016-10-28 19:49:31 +02:00
* `min(float1, float2, ...)` - Returns the smallest of the floats.
2016-02-23 12:35:27 +01:00
* `md5(string)` - Returns a (conventional) hexadecimal representation of the
MD5 hash of the given string.
2017-01-20 15:51:25 +01:00
* `pathexpand(string)` - Returns a filepath string with `~` expanded to the home directory. Note:
2017-01-20 18:01:07 +01:00
This will create a plan diff between two different hosts, unless the filepaths are the same.
2017-03-14 00:39:05 +01:00
2017-05-19 15:01:54 +02:00
* `pow(x, y)` - Returns the base `x` of exponential `y` as a float.
2017-05-18 17:03:13 +02:00
2017-05-17 23:46:33 +02:00
Example:
* `${pow(3,2)}` = 9
* `${pow(4,0)}` = 1
2015-03-02 18:40:24 +01:00
* `replace(string, search, replace)` - Does a search and replace on the
given string. All instances of `search` are replaced with the value
of `replace` . If `search` is wrapped in forward slashes, it is treated
as a regular expression. If using a regular expression, `replace`
can reference subcaptures in the regular expression by using `$n` where
`n` is the index or name of the subcapture. If using a regular expression,
2017-04-16 02:15:14 +02:00
the syntax conforms to the [re2 regular expression syntax ](https://github.com/google/re2/wiki/Syntax ).
2015-03-02 18:40:24 +01:00
2017-12-05 20:06:32 +01:00
* `rsadecrypt(string, key)` - Decrypts `string` using RSA. The padding scheme
PKCS #1 v1.5 is used. The `string` must be base64-encoded. `key` must be an
RSA private key in PEM format. You may use `file()` to load it from a file.
2016-02-23 12:34:09 +01:00
* `sha1(string)` - Returns a (conventional) hexadecimal representation of the
SHA-1 hash of the given string.
2016-06-04 00:49:54 +02:00
Example: `"${sha1("${aws_vpc.default.tags.customer}-s3-bucket")}"`
2016-02-23 12:34:09 +01:00
* `sha256(string)` - Returns a (conventional) hexadecimal representation of the
SHA-256 hash of the given string.
2016-06-04 00:49:54 +02:00
Example: `"${sha256("${aws_vpc.default.tags.customer}-s3-bucket")}"`
2016-02-23 12:34:09 +01:00
2017-05-03 01:35:23 +02:00
* `sha512(string)` - Returns a (conventional) hexadecimal representation of the
SHA-512 hash of the given string.
Example: `"${sha512("${aws_vpc.default.tags.customer}-s3-bucket")}"`
2017-09-25 23:19:18 +02:00
* `signum(integer)` - Returns `-1` for negative numbers, `0` for `0` and `1` for positive numbers.
2016-01-27 16:36:31 +01:00
This function is useful when you need to set a value for the first resource and
a different value for the rest of the resources.
Example: `element(split(",", var.r53_failover_policy), signum(count.index))`
2016-02-07 21:28:58 +01:00
where the 0th index points to `PRIMARY` and 1st to `FAILOVER`
2016-01-27 16:36:31 +01:00
2017-02-13 22:20:02 +01:00
* `slice(list, from, to)` - Returns the portion of `list` between `from` (inclusive) and `to` (exclusive).
Example: `slice(var.list_of_strings, 0, length(var.list_of_strings) - 1)`
* `sort(list)` - Returns a lexographically sorted list of the strings contained in
2016-06-11 18:36:29 +02:00
the list passed as an argument. Sort may only be used with lists which contain only
strings.
Examples: `sort(aws_instance.foo.*.id)` , `sort(var.list_of_strings)`
2015-03-02 18:40:24 +01:00
* `split(delim, string)` - Splits the string previously created by `join`
back into a list. This is useful for pushing lists through module
2015-05-08 23:49:29 +02:00
outputs since they currently only support string values. Depending on the
2015-05-14 05:22:14 +02:00
use, the string this is being performed within may need to be wrapped
2015-05-08 23:49:29 +02:00
in brackets to indicate that the output is actually a list, e.g.
`a_resource_param = ["${split(",", var.CSV_STRING)}"]` .
2015-03-02 18:40:24 +01:00
Example: `split(",", module.amod.server_ids)`
2016-12-08 02:49:13 +01:00
2017-04-03 10:38:35 +02:00
* `substr(string, offset, length)` - Extracts a substring from the input string. A negative offset is interpreted as being equivalent to a positive offset measured backwards from the end of the string. A length of `-1` is interpreted as meaning "until the end of the string".
2017-03-22 16:30:39 +01:00
2016-12-01 20:51:01 +01:00
* `timestamp()` - Returns a UTC timestamp string in RFC 3339 format. This string will change with every
invocation of the function, so in order to prevent diffs on every plan & apply, it must be used with the
[`ignore_changes` ](/docs/configuration/resources.html#ignore-changes ) lifecycle attribute.
2015-05-04 20:41:18 +02:00
2017-12-05 19:46:12 +01:00
* `timeadd(time, duration)` - Returns a UTC timestamp string corresponding to adding a given `duration` to `time` in RFC 3339 format.
For example, `timeadd("2017-11-22T00:00:00Z", "10m")` produces a value `"2017-11-22T00:10:00Z"` .
2016-10-26 14:21:32 +02:00
* `title(string)` - Returns a copy of the string with the first characters of all the words capitalized.
2017-09-02 06:19:47 +02:00
* `transpose(map)` - Swaps the keys and list values in a map of lists of strings. For example, transpose(map("a", list("1", "2"), "b", list("2", "3")) produces a value equivalent to map("1", list("a"), "2", list("a", "b"), "3", list("b")).
2016-01-30 10:51:28 +01:00
* `trimspace(string)` - Returns a copy of the string with all leading and trailing white spaces removed.
2016-01-30 00:28:04 +01:00
2016-01-11 04:39:20 +01:00
* `upper(string)` - Returns a copy of the string with all Unicode letters mapped to their upper case.
2015-10-20 03:49:51 +02:00
2017-08-22 20:26:09 +02:00
* `urlencode(string)` - Returns an URL-safe copy of the string.
2016-03-21 21:14:30 +01:00
* `uuid()` - Returns a UUID string in RFC 4122 v4 format. This string will change with every invocation of the function, so in order to prevent diffs on every plan & apply, it must be used with the [`ignore_changes` ](/docs/configuration/resources.html#ignore-changes ) lifecycle attribute.
2016-07-27 19:47:44 +02:00
* `values(map)` - Returns a list of the map values, in the order of the keys
returned by the `keys` function. This function only works on flat maps and
will return an error for maps that include nested lists or maps.
2016-06-29 21:11:08 +02:00
2016-10-26 16:33:54 +02:00
* `zipmap(list, list)` - Creates a map from a list of keys and a list of
values. The keys must all be of type string, and the length of the lists
must be the same.
For example, to output a mapping of AWS IAM user names to the fingerprint
of the key used to encrypt their initial password, you might use:
`zipmap(aws_iam_user.users.*.name, aws_iam_user_login_profile.users.*.key_fingerprint)` .
2015-05-04 20:41:18 +02:00
## Templates
2016-10-29 02:13:09 +02:00
Long strings can be managed using templates.
[Templates ](/docs/providers/template/index.html ) are
[data-sources ](/docs/configuration/data-sources.html ) defined by a
filename and some variables to use during interpolation. They have a
computed `rendered` attribute containing the result.
2015-05-04 20:41:18 +02:00
2016-08-31 05:04:55 +02:00
A template data source looks like:
2015-05-04 20:41:18 +02:00
2017-04-05 17:29:27 +02:00
```hcl
2016-08-31 05:04:55 +02:00
data "template_file" "example" {
2016-11-07 17:42:46 +01:00
template = "$${hello} $${world}!"
2015-11-24 15:59:57 +01:00
vars {
hello = "goodnight"
world = "moon"
}
2015-05-04 20:41:18 +02:00
}
output "rendered" {
2016-08-31 05:04:55 +02:00
value = "${data.template_file.example.rendered}"
2015-05-04 20:41:18 +02:00
}
```
Then the rendered value would be `goodnight moon!` .
2016-11-07 17:42:46 +01:00
You may use any of the built-in functions in your template. For more
details on template usage, please see the
[template_file documentation ](/docs/providers/template/d/file.html ).
2015-05-29 19:19:52 +02:00
### Using Templates with Count
Here is an example that combines the capabilities of templates with the interpolation
2016-08-31 05:04:55 +02:00
from `count` to give us a parameterized template, unique to each resource instance:
2015-05-29 19:19:52 +02:00
2017-04-05 17:29:27 +02:00
```hcl
2015-05-29 19:19:52 +02:00
variable "count" {
default = 2
}
variable "hostnames" {
default = {
"0" = "example1.org"
"1" = "example2.net"
}
}
2016-08-31 05:04:55 +02:00
data "template_file" "web_init" {
Stop requiring multi-vars (splats) to be in array brackets
Prior to Terraform 0.7, lists in Terraform were just a shallow abstraction
on top of strings with a magic delimiter between items. Wrapping a single
string in brackets in the configuration was Terraform's prompt that it
needed to split the string on that delimiter during interpolation.
In 0.7, when first-class lists were added, this convention was preserved
by flattening lists-of-lists by one level when they were encountered in
configuration. However, there was an oversight in that change where it
did not correctly handle the case where the inner list was unknown.
In #14135 we removed some code that was flattening partially-unknown lists
into fully-unknown (untyped) values. This inadvertently exposed the missed
case from the previous paragraph, causing issues for list-wrapped splat
expressions with unknown members. While this worked fine for resources,
due to some fixup done inside helper/schema, this did not work for other
interpolation contexts such as module blocks.
Various attempts to fix this up and restore the flattening behavior
selectively were unsuccessful, due to a proliferation of assumptions all
over the core code that would be too risky to change just to fix this bug.
This change, then, takes the different approach of removing the
requirement that splats be presented inside list brackets. This
requirement didn't make much sense anymore anyway, since no other
list-returning expression had this constraint and so the rest of Terraform
was already successfully dealing with both cases.
This leaves us with two different scenarios:
- For resource arguments, existing normalization code in helper/schema
does its own flattening that preserves compatibility with the common
practice of using bracketed splats. This change proves this with a test
within the "test" provider that exercises the whole Terraform core and
helper/schema stack that assigns bracketed splats to list and set
attributes.
- For arguments in other blocks, such as in module callsites, the
interpolator's own flattening behavior applies to known lists,
preserving compatibility with configurations from before
partially-computed splats were possible, but those wishing to use
partially-computed splats are required to drop the surrounding brackets.
This is less concerning because this scenario was introduced only in
0.9.5, so the scope for breakage is limited to those who adopted this
new feature quickly after upgrading.
As of this commit, the recommendation is to stop using brackets around
splats but the old form continues to be supported for backward
compatibility. In a future _major_ version of Terraform we will probably
phase out this legacy form to improve consistency, but for now both
forms are acceptable at the expense of some (pre-existing) weird behavior
when _actual_ lists-of-lists are used.
This addresses #14521 by officially adopting the suggested workaround of
dropping the brackets around the splat. However, it doesn't yet allow
passing of a partially-unknown list between modules: that still violates
assumptions in Terraform's core, so for the moment partially-unknown lists
work only within a _single_ interpolation expression, and cannot be
passed around between expressions. Until more holistic work is done to
improve Terraform's type handling, passing a partially-unknown splat
through to a module will result in a fully-unknown list emerging on
the other side, just as was the case before #14135; this change just
addresses the fact that this was failing with an error in 0.9.5.
2017-05-20 02:47:52 +02:00
# Render the template once for each instance
count = "${length(var.hostnames)}"
2015-11-24 15:59:57 +01:00
template = "${file("templates/web_init.tpl")}"
2015-05-29 19:19:52 +02:00
vars {
Stop requiring multi-vars (splats) to be in array brackets
Prior to Terraform 0.7, lists in Terraform were just a shallow abstraction
on top of strings with a magic delimiter between items. Wrapping a single
string in brackets in the configuration was Terraform's prompt that it
needed to split the string on that delimiter during interpolation.
In 0.7, when first-class lists were added, this convention was preserved
by flattening lists-of-lists by one level when they were encountered in
configuration. However, there was an oversight in that change where it
did not correctly handle the case where the inner list was unknown.
In #14135 we removed some code that was flattening partially-unknown lists
into fully-unknown (untyped) values. This inadvertently exposed the missed
case from the previous paragraph, causing issues for list-wrapped splat
expressions with unknown members. While this worked fine for resources,
due to some fixup done inside helper/schema, this did not work for other
interpolation contexts such as module blocks.
Various attempts to fix this up and restore the flattening behavior
selectively were unsuccessful, due to a proliferation of assumptions all
over the core code that would be too risky to change just to fix this bug.
This change, then, takes the different approach of removing the
requirement that splats be presented inside list brackets. This
requirement didn't make much sense anymore anyway, since no other
list-returning expression had this constraint and so the rest of Terraform
was already successfully dealing with both cases.
This leaves us with two different scenarios:
- For resource arguments, existing normalization code in helper/schema
does its own flattening that preserves compatibility with the common
practice of using bracketed splats. This change proves this with a test
within the "test" provider that exercises the whole Terraform core and
helper/schema stack that assigns bracketed splats to list and set
attributes.
- For arguments in other blocks, such as in module callsites, the
interpolator's own flattening behavior applies to known lists,
preserving compatibility with configurations from before
partially-computed splats were possible, but those wishing to use
partially-computed splats are required to drop the surrounding brackets.
This is less concerning because this scenario was introduced only in
0.9.5, so the scope for breakage is limited to those who adopted this
new feature quickly after upgrading.
As of this commit, the recommendation is to stop using brackets around
splats but the old form continues to be supported for backward
compatibility. In a future _major_ version of Terraform we will probably
phase out this legacy form to improve consistency, but for now both
forms are acceptable at the expense of some (pre-existing) weird behavior
when _actual_ lists-of-lists are used.
This addresses #14521 by officially adopting the suggested workaround of
dropping the brackets around the splat. However, it doesn't yet allow
passing of a partially-unknown list between modules: that still violates
assumptions in Terraform's core, so for the moment partially-unknown lists
work only within a _single_ interpolation expression, and cannot be
passed around between expressions. Until more holistic work is done to
improve Terraform's type handling, passing a partially-unknown splat
through to a module will result in a fully-unknown list emerging on
the other side, just as was the case before #14135; this change just
addresses the fact that this was failing with an error in 0.9.5.
2017-05-20 02:47:52 +02:00
# count.index tells us the index of the instance we are rendering
hostname = "${var.hostnames[count.index]}"
2015-05-29 19:19:52 +02:00
}
}
resource "aws_instance" "web" {
Stop requiring multi-vars (splats) to be in array brackets
Prior to Terraform 0.7, lists in Terraform were just a shallow abstraction
on top of strings with a magic delimiter between items. Wrapping a single
string in brackets in the configuration was Terraform's prompt that it
needed to split the string on that delimiter during interpolation.
In 0.7, when first-class lists were added, this convention was preserved
by flattening lists-of-lists by one level when they were encountered in
configuration. However, there was an oversight in that change where it
did not correctly handle the case where the inner list was unknown.
In #14135 we removed some code that was flattening partially-unknown lists
into fully-unknown (untyped) values. This inadvertently exposed the missed
case from the previous paragraph, causing issues for list-wrapped splat
expressions with unknown members. While this worked fine for resources,
due to some fixup done inside helper/schema, this did not work for other
interpolation contexts such as module blocks.
Various attempts to fix this up and restore the flattening behavior
selectively were unsuccessful, due to a proliferation of assumptions all
over the core code that would be too risky to change just to fix this bug.
This change, then, takes the different approach of removing the
requirement that splats be presented inside list brackets. This
requirement didn't make much sense anymore anyway, since no other
list-returning expression had this constraint and so the rest of Terraform
was already successfully dealing with both cases.
This leaves us with two different scenarios:
- For resource arguments, existing normalization code in helper/schema
does its own flattening that preserves compatibility with the common
practice of using bracketed splats. This change proves this with a test
within the "test" provider that exercises the whole Terraform core and
helper/schema stack that assigns bracketed splats to list and set
attributes.
- For arguments in other blocks, such as in module callsites, the
interpolator's own flattening behavior applies to known lists,
preserving compatibility with configurations from before
partially-computed splats were possible, but those wishing to use
partially-computed splats are required to drop the surrounding brackets.
This is less concerning because this scenario was introduced only in
0.9.5, so the scope for breakage is limited to those who adopted this
new feature quickly after upgrading.
As of this commit, the recommendation is to stop using brackets around
splats but the old form continues to be supported for backward
compatibility. In a future _major_ version of Terraform we will probably
phase out this legacy form to improve consistency, but for now both
forms are acceptable at the expense of some (pre-existing) weird behavior
when _actual_ lists-of-lists are used.
This addresses #14521 by officially adopting the suggested workaround of
dropping the brackets around the splat. However, it doesn't yet allow
passing of a partially-unknown list between modules: that still violates
assumptions in Terraform's core, so for the moment partially-unknown lists
work only within a _single_ interpolation expression, and cannot be
passed around between expressions. Until more holistic work is done to
improve Terraform's type handling, passing a partially-unknown splat
through to a module will result in a fully-unknown list emerging on
the other side, just as was the case before #14135; this change just
addresses the fact that this was failing with an error in 0.9.5.
2017-05-20 02:47:52 +02:00
# Create one instance for each hostname
count = "${length(var.hostnames)}"
2017-04-05 17:29:27 +02:00
Stop requiring multi-vars (splats) to be in array brackets
Prior to Terraform 0.7, lists in Terraform were just a shallow abstraction
on top of strings with a magic delimiter between items. Wrapping a single
string in brackets in the configuration was Terraform's prompt that it
needed to split the string on that delimiter during interpolation.
In 0.7, when first-class lists were added, this convention was preserved
by flattening lists-of-lists by one level when they were encountered in
configuration. However, there was an oversight in that change where it
did not correctly handle the case where the inner list was unknown.
In #14135 we removed some code that was flattening partially-unknown lists
into fully-unknown (untyped) values. This inadvertently exposed the missed
case from the previous paragraph, causing issues for list-wrapped splat
expressions with unknown members. While this worked fine for resources,
due to some fixup done inside helper/schema, this did not work for other
interpolation contexts such as module blocks.
Various attempts to fix this up and restore the flattening behavior
selectively were unsuccessful, due to a proliferation of assumptions all
over the core code that would be too risky to change just to fix this bug.
This change, then, takes the different approach of removing the
requirement that splats be presented inside list brackets. This
requirement didn't make much sense anymore anyway, since no other
list-returning expression had this constraint and so the rest of Terraform
was already successfully dealing with both cases.
This leaves us with two different scenarios:
- For resource arguments, existing normalization code in helper/schema
does its own flattening that preserves compatibility with the common
practice of using bracketed splats. This change proves this with a test
within the "test" provider that exercises the whole Terraform core and
helper/schema stack that assigns bracketed splats to list and set
attributes.
- For arguments in other blocks, such as in module callsites, the
interpolator's own flattening behavior applies to known lists,
preserving compatibility with configurations from before
partially-computed splats were possible, but those wishing to use
partially-computed splats are required to drop the surrounding brackets.
This is less concerning because this scenario was introduced only in
0.9.5, so the scope for breakage is limited to those who adopted this
new feature quickly after upgrading.
As of this commit, the recommendation is to stop using brackets around
splats but the old form continues to be supported for backward
compatibility. In a future _major_ version of Terraform we will probably
phase out this legacy form to improve consistency, but for now both
forms are acceptable at the expense of some (pre-existing) weird behavior
when _actual_ lists-of-lists are used.
This addresses #14521 by officially adopting the suggested workaround of
dropping the brackets around the splat. However, it doesn't yet allow
passing of a partially-unknown list between modules: that still violates
assumptions in Terraform's core, so for the moment partially-unknown lists
work only within a _single_ interpolation expression, and cannot be
passed around between expressions. Until more holistic work is done to
improve Terraform's type handling, passing a partially-unknown splat
through to a module will result in a fully-unknown list emerging on
the other side, just as was the case before #14135; this change just
addresses the fact that this was failing with an error in 0.9.5.
2017-05-20 02:47:52 +02:00
# Pass each instance its corresponding template_file
user_data = "${data.template_file.web_init.*.rendered[count.index]}"
2015-05-29 19:19:52 +02:00
}
```
Stop requiring multi-vars (splats) to be in array brackets
Prior to Terraform 0.7, lists in Terraform were just a shallow abstraction
on top of strings with a magic delimiter between items. Wrapping a single
string in brackets in the configuration was Terraform's prompt that it
needed to split the string on that delimiter during interpolation.
In 0.7, when first-class lists were added, this convention was preserved
by flattening lists-of-lists by one level when they were encountered in
configuration. However, there was an oversight in that change where it
did not correctly handle the case where the inner list was unknown.
In #14135 we removed some code that was flattening partially-unknown lists
into fully-unknown (untyped) values. This inadvertently exposed the missed
case from the previous paragraph, causing issues for list-wrapped splat
expressions with unknown members. While this worked fine for resources,
due to some fixup done inside helper/schema, this did not work for other
interpolation contexts such as module blocks.
Various attempts to fix this up and restore the flattening behavior
selectively were unsuccessful, due to a proliferation of assumptions all
over the core code that would be too risky to change just to fix this bug.
This change, then, takes the different approach of removing the
requirement that splats be presented inside list brackets. This
requirement didn't make much sense anymore anyway, since no other
list-returning expression had this constraint and so the rest of Terraform
was already successfully dealing with both cases.
This leaves us with two different scenarios:
- For resource arguments, existing normalization code in helper/schema
does its own flattening that preserves compatibility with the common
practice of using bracketed splats. This change proves this with a test
within the "test" provider that exercises the whole Terraform core and
helper/schema stack that assigns bracketed splats to list and set
attributes.
- For arguments in other blocks, such as in module callsites, the
interpolator's own flattening behavior applies to known lists,
preserving compatibility with configurations from before
partially-computed splats were possible, but those wishing to use
partially-computed splats are required to drop the surrounding brackets.
This is less concerning because this scenario was introduced only in
0.9.5, so the scope for breakage is limited to those who adopted this
new feature quickly after upgrading.
As of this commit, the recommendation is to stop using brackets around
splats but the old form continues to be supported for backward
compatibility. In a future _major_ version of Terraform we will probably
phase out this legacy form to improve consistency, but for now both
forms are acceptable at the expense of some (pre-existing) weird behavior
when _actual_ lists-of-lists are used.
This addresses #14521 by officially adopting the suggested workaround of
dropping the brackets around the splat. However, it doesn't yet allow
passing of a partially-unknown list between modules: that still violates
assumptions in Terraform's core, so for the moment partially-unknown lists
work only within a _single_ interpolation expression, and cannot be
passed around between expressions. Until more holistic work is done to
improve Terraform's type handling, passing a partially-unknown splat
through to a module will result in a fully-unknown list emerging on
the other side, just as was the case before #14135; this change just
addresses the fact that this was failing with an error in 0.9.5.
2017-05-20 02:47:52 +02:00
With this, we will build a list of `template_file.web_init` data resources
which we can use in combination with our list of `aws_instance.web` resources.
2015-08-04 20:09:43 +02:00
2016-10-25 09:39:15 +02:00
## Math
2016-07-12 00:37:51 +02:00
2015-08-04 20:09:43 +02:00
Simple math can be performed in interpolations:
2017-04-05 17:29:27 +02:00
```hcl
2015-08-04 20:09:43 +02:00
variable "count" {
default = 2
}
resource "aws_instance" "web" {
2017-04-05 17:29:27 +02:00
# ...
2015-08-04 20:09:43 +02:00
count = "${var.count}"
2017-04-05 17:29:27 +02:00
# Tag the instance with a counter starting at 1, ie. web-001
2015-08-04 20:09:43 +02:00
tags {
Name = "${format("web-%03d", count.index + 1)}"
}
}
```
The supported operations are:
2016-01-20 22:28:07 +01:00
- *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), and *Divide* (`/`) for **float** types
- *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), *Divide* (`/`), and *Modulo* (`%`) for **integer** types
2015-08-04 20:09:43 +02:00
2016-11-16 00:29:38 +01:00
Operator precedences is the standard mathematical order of operations:
*Multiply* (`*`), *Divide* (`/`), and *Modulo* (`%`) have precedence over
*Add* (`+`) and *Subtract* (`-`). Parenthesis can be used to force ordering.
2017-04-05 17:29:27 +02:00
```text
2016-11-16 00:29:38 +01:00
"${2 * 4 + 3 * 3}" # computes to 17
"${3 * 3 + 2 * 4}" # computes to 17
"${2 * (4 + 3) * 3}" # computes to 42
```
You can use the [terraform console ](/docs/commands/console.html ) command to
try the math operations.
2015-08-04 20:09:43 +02:00
-> **Note:** Since Terraform allows hyphens in resource and variable names,
it's best to use spaces between math operators to prevent confusion or unexpected
behavior. For example, `${var.instance-count - 1}` will subtract **1** from the
`instance-count` variable value, while `${var.instance-count-1}` will interpolate
the `instance-count-1` variable value.