github.com/hugorut/terraform@v1.1.3/website/docs/language/configuration-0-11/interpolation.mdx (about)

     1  ---
     2  page_title: Interpolation Syntax - 0.11 Configuration Language
     3  description: >-
     4    Embedded within strings in Terraform, whether you're using the Terraform
     5    syntax or JSON syntax, you can interpolate other values into strings. These
     6    interpolations are wrapped in `${}`, such as `${var.foo}`.
     7  ---
     8  
     9  # Interpolation Syntax
    10  
    11  -> **Note:** This page is about Terraform 0.11 and earlier. For Terraform 0.12
    12  and later, see
    13  [Configuration Language: Expressions](/language/expressions) and
    14  [Configuration Language: Functions](/language/functions).
    15  
    16  Embedded within strings in Terraform, whether you're using the
    17  Terraform syntax or JSON syntax, you can interpolate other values. These
    18  interpolations are wrapped in `${}`, such as `${var.foo}`.
    19  
    20  The interpolation syntax is powerful and allows you to reference
    21  variables, attributes of resources, call functions, etc.
    22  
    23  You can perform [simple math](#math) in interpolations, allowing
    24  you to write expressions such as `${count.index + 1}`. And you can
    25  also use [conditionals](#conditionals) to determine a value based
    26  on some logic.
    27  
    28  You can escape interpolation with double dollar signs: `$${foo}`
    29  will be rendered as a literal `${foo}`.
    30  
    31  ## Available Variables
    32  
    33  There are a variety of available variable references you can use.
    34  
    35  #### User string variables
    36  
    37  Use the `var.` prefix followed by the variable name. For example,
    38  `${var.foo}` will interpolate the `foo` variable value.
    39  
    40  #### User map variables
    41  
    42  The syntax is `var.<MAP>["<KEY>"]`. For example, `${var.amis["us-east-1"]}`
    43  would get the value of the `us-east-1` key within the `amis` map
    44  variable.
    45  
    46  #### User list variables
    47  
    48  The syntax is `"${var.<LIST>}"`. For example, `"${var.subnets}"`
    49  would get the value of the `subnets` list, as a list. You can also
    50  return list elements by index: `${var.subnets[idx]}`.
    51  
    52  #### Attributes of your own resource
    53  
    54  The syntax is `self.<ATTRIBUTE>`. For example `${self.private_ip}`
    55  will interpolate that resource's private IP address.
    56  
    57  -> **Note**: The `self.<ATTRIBUTE>` syntax is only allowed and valid within
    58  provisioners.
    59  
    60  #### Attributes of other resources
    61  
    62  The syntax is `<TYPE>.<NAME>.<ATTRIBUTE>`. For example,
    63  `${aws_instance.web.id}` will interpolate the ID attribute from the
    64  `aws_instance` resource named `web`. If the resource has a `count`
    65  attribute set, you can access individual attributes with a zero-based
    66  index, such as `${aws_instance.web.0.id}`. You can also use the splat
    67  syntax to get a list of all the attributes: `${aws_instance.web.*.id}`.
    68  
    69  #### Attributes of a data source
    70  
    71  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](/language/configuration-0-11/data-sources) named `ubuntu`. If the data source has a `count`
    72  attribute set, you can access individual attributes with a zero-based
    73  index, such as `${data.aws_subnet.example.0.cidr_block}`. You can also use the splat
    74  syntax to get a list of all the attributes: `${data.aws_subnet.example.*.cidr_block}`.
    75  
    76  #### Outputs from a module
    77  
    78  The syntax is `module.<NAME>.<OUTPUT>`. For example `${module.foo.bar}` will
    79  interpolate the `bar` output from the `foo`
    80  [module](/language/modules/develop).
    81  
    82  #### Count information
    83  
    84  The syntax is `count.index`. For example, `${count.index}` will
    85  interpolate the current index in a multi-count resource. For more
    86  information on `count`, see the [resource configuration
    87  page](/language/configuration-0-11/resources).
    88  
    89  #### Path information
    90  
    91  The syntax is `path.<TYPE>`. TYPE can be `cwd`, `module`, or `root`.
    92  `cwd` will interpolate the current working directory. `module` will
    93  interpolate the path to the current module. `root` will interpolate the
    94  path of the root module.  In general, you probably want the
    95  `path.module` variable.
    96  
    97  #### Terraform meta information
    98  
    99  The syntax is `terraform.<FIELD>`. This variable type contains metadata about
   100  the currently executing Terraform run. FIELD can currently only be `env` to
   101  reference the currently active workspace.
   102  
   103  ## Conditionals
   104  
   105  Interpolations may contain conditionals to branch on the final value.
   106  
   107  ```hcl
   108  resource "aws_instance" "web" {
   109    subnet = "${var.env == "production" ? var.prod_subnet : var.dev_subnet}"
   110  }
   111  ```
   112  
   113  The conditional syntax is the well-known ternary operation:
   114  
   115  ```text
   116  CONDITION ? TRUEVAL : FALSEVAL
   117  ```
   118  
   119  The condition can be any valid interpolation syntax, such as variable
   120  access, a function call, or even another conditional. The true and false
   121  value can also be any valid interpolation syntax. The returned types by
   122  the true and false side must be the same.
   123  
   124  The supported operators are:
   125  
   126  - Equality: `==` and `!=`
   127  - Numerical comparison: `>`, `<`, `>=`, `<=`
   128  - Boolean logic: `&&`, `||`, unary `!`
   129  
   130  A common use case for conditionals is to enable/disable a resource by
   131  conditionally setting the count:
   132  
   133  ```hcl
   134  resource "aws_instance" "vpn" {
   135    count = "${var.something ? 1 : 0}"
   136  }
   137  ```
   138  
   139  In the example above, the "vpn" resource will only be included if
   140  "var.something" evaluates to true. Otherwise, the VPN resource will
   141  not be created at all.
   142  
   143  ## Built-in Functions
   144  
   145  Terraform ships with built-in functions. Functions are called with the
   146  syntax `name(arg, arg2, ...)`. For example, to read a file:
   147  `${file("path.txt")}`.
   148  
   149  ~> **Note**: Proper escaping is required for JSON field values containing quotes
   150  (`"`) such as `environment` values. If directly setting the JSON, they should be
   151  escaped as `\"` in the JSON,  e.g. `"value": "I \"love\" escaped quotes"`. If
   152  using a Terraform variable value, they should be escaped as `\\\"` in the
   153  variable, e.g. `value = "I \\\"love\\\" escaped quotes"` in the variable and
   154  `"value": "${var.myvariable}"` in the JSON.
   155  
   156  ### Supported built-in functions
   157  
   158  The supported built-in functions are:
   159  
   160  - `abs(float)` - Returns the absolute value of a given float.
   161    Example: `abs(1)` returns `1`, and `abs(-1)` would also return `1`,
   162    whereas `abs(-3.14)` would return `3.14`. See also the `signum` function.
   163  
   164  - `basename(path)` - Returns the last element of a path.
   165  
   166  - `base64decode(string)` - Given a base64-encoded string, decodes it and
   167    returns the original string.
   168  
   169  - `base64encode(string)` - Returns a base64-encoded representation of the
   170    given string.
   171  
   172  - `base64gzip(string)` - Compresses the given string with gzip and then
   173    encodes the result to base64. This can be used with certain resource
   174    arguments that allow binary data to be passed with base64 encoding, since
   175    Terraform strings are required to be valid UTF-8.
   176  
   177  - `base64sha256(string)` - Returns a base64-encoded representation of raw
   178    SHA-256 sum of the given string.
   179    **This is not equivalent** of `base64encode(sha256(string))`
   180    since `sha256()` returns hexadecimal representation.
   181  
   182  - `base64sha512(string)` - Returns a base64-encoded representation of raw
   183    SHA-512 sum of the given string.
   184    **This is not equivalent** of `base64encode(sha512(string))`
   185    since `sha512()` returns hexadecimal representation.
   186  
   187  - `bcrypt(password, cost)` - Returns the Blowfish encrypted hash of the string
   188    at the given cost. A default `cost` of 10 will be used if not provided.
   189  
   190  - `ceil(float)` - Returns the least integer value greater than or equal
   191    to the argument.
   192  
   193  - `chomp(string)` - Removes trailing newlines from the given string.
   194  
   195  - `chunklist(list, size)` - Returns the `list` items chunked by `size`.
   196    Examples:
   197    - `chunklist(aws_subnet.foo.*.id, 1)`: will outputs `[["id1"], ["id2"], ["id3"]]`
   198    - `chunklist(var.list_of_strings, 2)`: will outputs `[["id1", "id2"], ["id3", "id4"], ["id5"]]`
   199  
   200  - `cidrhost(iprange, hostnum)` - Takes an IP address range in CIDR notation
   201    and creates an IP address with the given host number. If given host
   202    number is negative, the count starts from the end of the range.
   203    For example, `cidrhost("10.0.0.0/8", 2)` returns `10.0.0.2` and
   204    `cidrhost("10.0.0.0/8", -2)` returns `10.255.255.254`.
   205  
   206  - `cidrnetmask(iprange)` - Takes an IP address range in CIDR notation
   207    and returns the address-formatted subnet mask format that some
   208    systems expect for IPv4 interfaces. For example,
   209    `cidrnetmask("10.0.0.0/8")` returns `255.0.0.0`. Not applicable
   210    to IPv6 networks since CIDR notation is the only valid notation for
   211    IPv6.
   212  
   213  - `cidrsubnet(iprange, newbits, netnum)` - Takes an IP address range in
   214    CIDR notation (like `10.0.0.0/8`) and extends its prefix to include an
   215    additional subnet number. For example,
   216    `cidrsubnet("10.0.0.0/8", 8, 2)` returns `10.2.0.0/16`;
   217    `cidrsubnet("2607:f298:6051:516c::/64", 8, 2)` returns
   218    `2607:f298:6051:516c:200::/72`.
   219  
   220  - `coalesce(string1, string2, ...)` - Returns the first non-empty value from
   221    the given arguments. At least two arguments must be provided.
   222  
   223  - `coalescelist(list1, list2, ...)` - Returns the first non-empty list from
   224    the given arguments. At least two arguments must be provided.
   225  
   226  - `compact(list)` - Removes empty string elements from a list. This can be
   227    useful in some cases, for example when passing joined lists as module
   228    variables or when parsing module outputs.
   229    Example: `compact(module.my_asg.load_balancer_names)`
   230  
   231  - `concat(list1, list2, ...)` - Combines two or more lists into a single list.
   232    Example: `concat(aws_instance.db.*.tags.Name, aws_instance.web.*.tags.Name)`
   233  
   234  - `contains(list, element)` - Returns _true_ if a list contains the given element
   235    and returns _false_ otherwise. Examples: `contains(var.list_of_strings, "an_element")`
   236  
   237  - `dirname(path)` - Returns all but the last element of path, typically the path's directory.
   238  
   239  - `distinct(list)` - Removes duplicate items from a list. Keeps the first
   240    occurrence of each element, and removes subsequent occurrences. This
   241    function is only valid for flat lists. Example: `distinct(var.usernames)`
   242  
   243  - `element(list, index)` - Returns a single element from a list
   244    at the given index. If the index is greater than the number of
   245    elements, this function will wrap using a standard mod algorithm.
   246    This function only works on flat lists. Examples:
   247    - `element(aws_subnet.foo.*.id, count.index)`
   248    - `element(var.list_of_strings, 2)`
   249  
   250  - `file(path)` - Reads the contents of a file into the string. Variables
   251    in this file are _not_ interpolated. The contents of the file are
   252    read as-is. The `path` is interpreted relative to the working directory.
   253    [Path variables](#path-information) can be used to reference paths relative
   254    to other base locations. For example, when using `file()` from inside a
   255    module, you generally want to make the path relative to the module base,
   256    like this: `file("${path.module}/file")`.
   257  
   258  - `floor(float)` - Returns the greatest integer value less than or equal to
   259    the argument.
   260  
   261  - `flatten(list of lists)` - Flattens lists of lists down to a flat list of
   262    primitive values, eliminating any nested lists recursively. Examples:
   263    - `flatten(data.github_user.user.*.gpg_keys)`
   264  
   265  - `format(format, args, ...)` - Formats a string according to the given
   266    format. The syntax for the format is standard `sprintf` syntax.
   267    Good documentation for the syntax can be [found here](https://golang.org/pkg/fmt/).
   268    Example to zero-prefix a count, used commonly for naming servers:
   269    `format("web-%03d", count.index + 1)`.
   270  
   271  - `formatlist(format, args, ...)` - Formats each element of a list
   272    according to the given format, similarly to `format`, and returns a list.
   273    Non-list arguments are repeated for each list element.
   274    For example, to convert a list of DNS addresses to a list of URLs, you might use:
   275    `formatlist("https://%s:%s/", aws_instance.foo.*.public_dns, var.port)`.
   276    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.
   277    Example:
   278    `formatlist("instance %v has private ip %v", aws_instance.foo.*.id, aws_instance.foo.*.private_ip)`.
   279    Passing lists with different lengths to formatlist results in an error.
   280  
   281  - `indent(numspaces, string)` - Prepends the specified number of spaces to all but the first
   282    line of the given multi-line string. May be useful when inserting a multi-line string
   283    into an already-indented context. The first line is not indented, to allow for the
   284    indented string to be placed after some sort of already-indented preamble.
   285    Example: `"    \"items\": ${ indent(4, "[\n    \"item1\"\n]") },"`
   286  
   287  - `index(list, elem)` - Finds the index of a given element in a list.
   288    This function only works on flat lists.
   289    Example: `index(aws_instance.foo.*.tags.Name, "foo-test")`
   290  
   291  - `join(delim, list)` - Joins the list with the delimiter for a resultant string.
   292    This function works only on flat lists.
   293    Examples:
   294    - `join(",", aws_instance.foo.*.id)`
   295    - `join(",", var.ami_list)`
   296  
   297  - `jsonencode(value)` - Returns a JSON-encoded representation of the given
   298    value, which can contain arbitrarily-nested lists and maps. Note that if
   299    the value is a string then its value will be placed in quotes.
   300  
   301  - `keys(map)` - Returns a lexically sorted list of the map keys.
   302  
   303  - `length(list)` - Returns the number of members in a given list or map, or the number of characters in a given string.
   304    - `${length(split(",", "a,b,c"))}` = 3
   305    - `${length("a,b,c")}` = 5
   306    - `${length(map("key", "val"))}` = 1
   307  
   308  - `list(items, ...)` - Returns a list consisting of the arguments to the function.
   309    This function provides a way of representing list literals in interpolation.
   310    - `${list("a", "b", "c")}` returns a list of `"a", "b", "c"`.
   311    - `${list()}` returns an empty list.
   312  
   313  - `log(x, base)` - Returns the logarithm of `x`.
   314  
   315  - `lookup(map, key, [default])` - Performs a dynamic lookup into a map
   316    variable. The `map` parameter should be another variable, such
   317    as `var.amis`. If `key` does not exist in `map`, the interpolation will
   318    fail unless you specify a third argument, `default`, which should be a
   319    string value to return if no `key` is found in `map`. This function
   320    only works on flat maps and will return an error for maps that
   321    include nested lists or maps.
   322  
   323  - `lower(string)` - Returns a copy of the string with all Unicode letters mapped to their lower case.
   324  
   325  - `map(key, value, ...)` - Returns a map consisting of the key/value pairs
   326    specified as arguments. Every odd argument must be a string key, and every
   327    even argument must have the same type as the other values specified.
   328    Duplicate keys are not allowed. Examples:
   329    - `map("hello", "world")`
   330    - `map("us-east", list("a", "b", "c"), "us-west", list("b", "c", "d"))`
   331  
   332  - `matchkeys(values, keys, searchset)` - For two lists `values` and `keys` of
   333    equal length, returns all elements from `values` where the corresponding
   334    element from `keys` exists in the `searchset` list.  E.g.
   335    `matchkeys(aws_instance.example.*.id,
   336      aws_instance.example.*.availability_zone, list("us-west-2a"))` will return a
   337    list of the instance IDs of the `aws_instance.example` instances in
   338    `"us-west-2a"`. No match will result in empty list. Items of `keys` are
   339    processed sequentially, so the order of returned `values` is preserved.
   340  
   341  - `max(float1, float2, ...)` - Returns the largest of the floats.
   342  
   343  - `merge(map1, map2, ...)` - Returns the union of 2 or more maps. The maps
   344    are consumed in the order provided, and duplicate keys overwrite previous
   345    entries.
   346    - `${merge(map("a", "b"), map("c", "d"))}` returns `{"a": "b", "c": "d"}`
   347  
   348  - `min(float1, float2, ...)` - Returns the smallest of the floats.
   349  
   350  - `md5(string)` - Returns a (conventional) hexadecimal representation of the
   351    MD5 hash of the given string.
   352  
   353  - `pathexpand(string)` - Returns a filepath string with `~` expanded to the home directory. Note:
   354    This will create a plan diff between two different hosts, unless the filepaths are the same.
   355  
   356  - `pow(x, y)` - Returns the base `x` of exponential `y` as a float.
   357  
   358    Example:
   359  
   360    - `${pow(3,2)}` = 9
   361    - `${pow(4,0)}` = 1
   362  
   363  - `replace(string, search, replace)` - Does a search and replace on the
   364    given string. All instances of `search` are replaced with the value
   365    of `replace`. If `search` is wrapped in forward slashes, it is treated
   366    as a regular expression. If using a regular expression, `replace`
   367    can reference subcaptures in the regular expression by using `$n` where
   368    `n` is the index or name of the subcapture. If using a regular expression,
   369    the syntax conforms to the [re2 regular expression syntax](https://github.com/google/re2/wiki/Syntax).
   370  
   371  - `rsadecrypt(string, key)` - Decrypts `string` using RSA. The padding scheme
   372    PKCS #1 v1.5 is used. The `string` must be base64-encoded. `key` must be an
   373    RSA private key in PEM format. You may use `file()` to load it from a file.
   374  
   375  - `sha1(string)` - Returns a (conventional) hexadecimal representation of the
   376    SHA-1 hash of the given string.
   377    Example: `"${sha1("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   378  
   379  - `sha256(string)` - Returns a (conventional) hexadecimal representation of the
   380    SHA-256 hash of the given string.
   381    Example: `"${sha256("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   382  
   383  - `sha512(string)` - Returns a (conventional) hexadecimal representation of the
   384    SHA-512 hash of the given string.
   385    Example: `"${sha512("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   386  
   387  - `signum(integer)` - Returns `-1` for negative numbers, `0` for `0` and `1` for positive numbers.
   388    This function is useful when you need to set a value for the first resource and
   389    a different value for the rest of the resources.
   390    Example: `element(split(",", var.r53_failover_policy), signum(count.index))`
   391    where the 0th index points to `PRIMARY` and 1st to `FAILOVER`
   392  
   393  - `slice(list, from, to)` - Returns the portion of `list` between `from` (inclusive) and `to` (exclusive).
   394    Example: `slice(var.list_of_strings, 0, length(var.list_of_strings) - 1)`
   395  
   396  - `sort(list)` - Returns a lexicographically sorted list of the strings contained in
   397    the list passed as an argument. Sort may only be used with lists which contain only
   398    strings.
   399    Examples: `sort(aws_instance.foo.*.id)`, `sort(var.list_of_strings)`
   400  
   401  - `split(delim, string)` - Returns a list by splitting the string based on
   402    the delimiter. This is useful for pushing lists through module
   403    outputs since they currently only support string values. Depending on the
   404    use, the string this is being performed within may need to be wrapped
   405    in brackets to indicate that the output is actually a list, e.g.
   406    `a_resource_param = ["${split(",", var.CSV_STRING)}"]`.
   407    Example: `split(",", module.amod.server_ids)`
   408  
   409  - `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".
   410  
   411  - `timestamp()` - Returns a UTC timestamp string in RFC 3339 format. This string will change with every
   412    invocation of the function, so in order to prevent diffs on every plan & apply, it must be used with the
   413    [`ignore_changes`](/language/configuration-0-11/resources#ignore_changes) lifecycle attribute.
   414  
   415  - `timeadd(time, duration)` - Returns a UTC timestamp string corresponding to adding a given `duration` to `time` in RFC 3339 format.
   416    For example, `timeadd("2017-11-22T00:00:00Z", "10m")` produces a value `"2017-11-22T00:10:00Z"`.
   417  
   418  - `title(string)` - Returns a copy of the string with the first characters of all the words capitalized.
   419  
   420  - `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")).
   421  
   422  - `trimspace(string)` - Returns a copy of the string with all leading and trailing white spaces removed.
   423  
   424  - `upper(string)` - Returns a copy of the string with all Unicode letters mapped to their upper case.
   425  
   426  - `urlencode(string)` - Returns an URL-safe copy of the string.
   427  
   428  - `uuid()` - Returns a random UUID string. 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`](/language/configuration-0-11/resources#ignore_changes) lifecycle attribute.
   429  
   430  - `values(map)` - Returns a list of the map values, in the order of the keys
   431    returned by the `keys` function. This function only works on flat maps and
   432    will return an error for maps that include nested lists or maps.
   433  
   434  - `zipmap(list, list)` - Creates a map from a list of keys and a list of
   435    values. The keys must all be of type string, and the length of the lists
   436    must be the same.
   437    For example, to output a mapping of AWS IAM user names to the fingerprint
   438    of the key used to encrypt their initial password, you might use:
   439    `zipmap(aws_iam_user.users.*.name, aws_iam_user_login_profile.users.*.key_fingerprint)`.
   440  
   441  The hashing functions `base64sha256`, `base64sha512`, `md5`, `sha1`, `sha256`,
   442  and `sha512` all have variants with a `file` prefix, like `filesha1`, which
   443  interpret their first argument as a path to a file on disk rather than as a
   444  literal string. This allows safely creating hashes of binary files that might
   445  otherwise be corrupted in memory if loaded into Terraform strings (which are
   446  assumed to be UTF-8). `filesha1(filename)` is equivalent to `sha1(file(filename))`
   447  in Terraform 0.11 and earlier, but the latter will fail for binary files in
   448  Terraform 0.12 and later.
   449  
   450  ## Templates
   451  
   452  Long strings can be managed using templates.
   453  [Templates](https://registry.terraform.io/providers/hashicorp/template/latest/docs) are
   454  [data-sources](/language/configuration-0-11/data-sources) defined by a
   455  string with interpolation tokens (usually loaded from a file) and some variables
   456  to use during interpolation. They have a computed `rendered` attribute
   457  containing the result.
   458  
   459  A template data source looks like:
   460  
   461  ```hcl
   462  # templates/greeting.tpl
   463  ${hello} ${world}!
   464  ```
   465  
   466  ```hcl
   467  data "template_file" "example" {
   468    template = "${file("templates/greeting.tpl")}"
   469    vars {
   470      hello = "goodnight"
   471      world = "moon"
   472    }
   473  }
   474  
   475  output "rendered" {
   476    value = "${data.template_file.example.rendered}"
   477  }
   478  ```
   479  
   480  Then the rendered value would be `goodnight moon!`.
   481  
   482  -> **Note:** If you specify the template as a literal string instead of loading
   483  a file, the inline template must use double dollar signs (like `$${hello}`) to
   484  prevent Terraform from interpolating values from the configuration into the
   485  string. This is because `template_file` creates its own instance of the
   486  interpolation system, with values provided by its nested `vars` block instead of
   487  by the surrounding scope of the configuration.
   488  
   489  You may use any of the built-in functions in your template. For more
   490  details on template usage, please see the
   491  [template_file documentation](https://registry.terraform.io/providers/hashicorp/template/latest/docs/data-sources/file).
   492  
   493  ### Using Templates with Count
   494  
   495  Here is an example that combines the capabilities of templates with the interpolation
   496  from `count` to give us a parameterized template, unique to each resource instance:
   497  
   498  ```hcl
   499  variable "hostnames" {
   500    default = {
   501      "0" = "example1.org"
   502      "1" = "example2.net"
   503    }
   504  }
   505  
   506  data "template_file" "web_init" {
   507    # Render the template once for each instance
   508    count    = "${length(var.hostnames)}"
   509    template = "${file("templates/web_init.tpl")}"
   510    vars {
   511      # count.index tells us the index of the instance we are rendering
   512      hostname = "${var.hostnames[count.index]}"
   513    }
   514  }
   515  
   516  resource "aws_instance" "web" {
   517    # Create one instance for each hostname
   518    count     = "${length(var.hostnames)}"
   519  
   520    # Pass each instance its corresponding template_file
   521    user_data = "${data.template_file.web_init.*.rendered[count.index]}"
   522  }
   523  ```
   524  
   525  With this, we will build a list of `template_file.web_init` data resources
   526  which we can use in combination with our list of `aws_instance.web` resources.
   527  
   528  ## Math
   529  
   530  Simple math can be performed in interpolations:
   531  
   532  ```hcl
   533  variable "count" {
   534    default = 2
   535  }
   536  
   537  resource "aws_instance" "web" {
   538    # ...
   539  
   540    count = "${var.count}"
   541  
   542    # Tag the instance with a counter starting at 1, ie. web-001
   543    tags {
   544      Name = "${format("web-%03d", count.index + 1)}"
   545    }
   546  }
   547  ```
   548  
   549  The supported operations are:
   550  
   551  - _Add_ (`+`), _Subtract_ (`-`), _Multiply_ (`*`), and _Divide_ (`/`) for **float** types
   552  - _Add_ (`+`), _Subtract_ (`-`), _Multiply_ (`*`), _Divide_ (`/`), and _Modulo_ (`%`) for **integer** types
   553  
   554  Operator precedences is the standard mathematical order of operations:
   555  _Multiply_ (`*`), _Divide_ (`/`), and _Modulo_ (`%`) have precedence over
   556  _Add_ (`+`) and _Subtract_ (`-`). Parenthesis can be used to force ordering.
   557  
   558  ```text
   559  "${2 * 4 + 3 * 3}" # computes to 17
   560  "${3 * 3 + 2 * 4}" # computes to 17
   561  "${2 * (4 + 3) * 3}" # computes to 42
   562  ```
   563  
   564  You can use the [terraform console](/cli/commands/console) command to
   565  try the math operations.
   566  
   567  -> **Note:** Since Terraform allows hyphens in resource and variable names,
   568  it's best to use spaces between math operators to prevent confusion or unexpected
   569  behavior. For example, `${var.instance-count - 1}` will subtract **1** from the
   570  `instance-count` variable value, while `${var.instance-count-1}` will interpolate
   571  the `instance-count-1` variable value.