github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/website/docs/configuration-0-11/interpolation.html.md (about)

     1  ---
     2  layout: "docs"
     3  page_title: "Interpolation Syntax - 0.11 Configuration Language"
     4  sidebar_current: "docs-conf-old-interpolation"
     5  description: |-
     6    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}`.
     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](../configuration/expressions.html) and
    14  [Configuration Language: Functions](../configuration/functions.html).
    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](./data-sources.html) 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](/docs/modules/index.html).
    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](./resources.html).
    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 [state environment](/docs/state/environments.html).
   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      * `${pow(3,2)}` = 9
   360      * `${pow(4,0)}` = 1
   361  
   362    * `replace(string, search, replace)` - Does a search and replace on the
   363        given string. All instances of `search` are replaced with the value
   364        of `replace`. If `search` is wrapped in forward slashes, it is treated
   365        as a regular expression. If using a regular expression, `replace`
   366        can reference subcaptures in the regular expression by using `$n` where
   367        `n` is the index or name of the subcapture. If using a regular expression,
   368        the syntax conforms to the [re2 regular expression syntax](https://github.com/google/re2/wiki/Syntax).
   369  
   370    * `rsadecrypt(string, key)` - Decrypts `string` using RSA. The padding scheme
   371      PKCS #1 v1.5 is used. The `string` must be base64-encoded. `key` must be an
   372      RSA private key in PEM format. You may use `file()` to load it from a file.
   373  
   374    * `sha1(string)` - Returns a (conventional) hexadecimal representation of the
   375      SHA-1 hash of the given string.
   376      Example: `"${sha1("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   377  
   378    * `sha256(string)` - Returns a (conventional) hexadecimal representation of the
   379      SHA-256 hash of the given string.
   380      Example: `"${sha256("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   381  
   382    * `sha512(string)` - Returns a (conventional) hexadecimal representation of the
   383      SHA-512 hash of the given string.
   384      Example: `"${sha512("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   385  
   386    * `signum(integer)` - Returns `-1` for negative numbers, `0` for `0` and `1` for positive numbers.
   387        This function is useful when you need to set a value for the first resource and
   388        a different value for the rest of the resources.
   389        Example: `element(split(",", var.r53_failover_policy), signum(count.index))`
   390        where the 0th index points to `PRIMARY` and 1st to `FAILOVER`
   391  
   392    * `slice(list, from, to)` - Returns the portion of `list` between `from` (inclusive) and `to` (exclusive).
   393        Example: `slice(var.list_of_strings, 0, length(var.list_of_strings) - 1)`
   394  
   395    * `sort(list)` - Returns a lexicographically sorted list of the strings contained in
   396        the list passed as an argument. Sort may only be used with lists which contain only
   397        strings.
   398        Examples: `sort(aws_instance.foo.*.id)`, `sort(var.list_of_strings)`
   399  
   400    * `split(delim, string)` - Returns a list by splitting the string based on
   401        the delimiter. This is useful for pushing lists through module
   402        outputs since they currently only support string values. Depending on the
   403        use, the string this is being performed within may need to be wrapped
   404        in brackets to indicate that the output is actually a list, e.g.
   405        `a_resource_param = ["${split(",", var.CSV_STRING)}"]`.
   406        Example: `split(",", module.amod.server_ids)`
   407  
   408    * `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".
   409  
   410    * `timestamp()` - Returns a UTC timestamp string in RFC 3339 format. This string will change with every
   411     invocation of the function, so in order to prevent diffs on every plan & apply, it must be used with the
   412     [`ignore_changes`](./resources.html#ignore-changes) lifecycle attribute.
   413  
   414    * `timeadd(time, duration)` - Returns a UTC timestamp string corresponding to adding a given `duration` to `time` in RFC 3339 format.
   415      For example, `timeadd("2017-11-22T00:00:00Z", "10m")` produces a value `"2017-11-22T00:10:00Z"`.
   416  
   417    * `title(string)` - Returns a copy of the string with the first characters of all the words capitalized.
   418  
   419    * `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")).
   420  
   421    * `trimspace(string)` - Returns a copy of the string with all leading and trailing white spaces removed.
   422  
   423    * `upper(string)` - Returns a copy of the string with all Unicode letters mapped to their upper case.
   424  
   425    * `urlencode(string)` - Returns an URL-safe copy of the string.
   426  
   427    * `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`](./resources.html#ignore-changes) lifecycle attribute.
   428  
   429    * `values(map)` - Returns a list of the map values, in the order of the keys
   430      returned by the `keys` function. This function only works on flat maps and
   431      will return an error for maps that include nested lists or maps.
   432  
   433    * `zipmap(list, list)` - Creates a map from a list of keys and a list of
   434        values. The keys must all be of type string, and the length of the lists
   435        must be the same.
   436        For example, to output a mapping of AWS IAM user names to the fingerprint
   437        of the key used to encrypt their initial password, you might use:
   438        `zipmap(aws_iam_user.users.*.name, aws_iam_user_login_profile.users.*.key_fingerprint)`.
   439  
   440  The hashing functions `base64sha256`, `base64sha512`, `md5`, `sha1`, `sha256`,
   441  and `sha512` all have variants with a `file` prefix, like `filesha1`, which
   442  interpret their first argument as a path to a file on disk rather than as a
   443  literal string. This allows safely creating hashes of binary files that might
   444  otherwise be corrupted in memory if loaded into Terraform strings (which are
   445  assumed to be UTF-8). `filesha1(filename)` is equivalent to `sha1(file(filename))`
   446  in Terraform 0.11 and earlier, but the latter will fail for binary files in
   447  Terraform 0.12 and later.
   448  
   449  ## Templates
   450  
   451  Long strings can be managed using templates.
   452  [Templates](/docs/providers/template/index.html) are
   453  [data-sources](./data-sources.html) defined by a
   454  string with interpolation tokens (usually loaded from a file) and some variables
   455  to use during interpolation. They have a computed `rendered` attribute
   456  containing the result.
   457  
   458  A template data source looks like:
   459  
   460  ```hcl
   461  # templates/greeting.tpl
   462  ${hello} ${world}!
   463  ```
   464  
   465  ```hcl
   466  data "template_file" "example" {
   467    template = "${file("templates/greeting.tpl")}"
   468    vars {
   469      hello = "goodnight"
   470      world = "moon"
   471    }
   472  }
   473  
   474  output "rendered" {
   475    value = "${data.template_file.example.rendered}"
   476  }
   477  ```
   478  
   479  Then the rendered value would be `goodnight moon!`.
   480  
   481  -> **Note:** If you specify the template as a literal string instead of loading
   482  a file, the inline template must use double dollar signs (like `$${hello}`) to
   483  prevent Terraform from interpolating values from the configuration into the
   484  string. This is because `template_file` creates its own instance of the
   485  interpolation system, with values provided by its nested `vars` block instead of
   486  by the surrounding scope of the configuration.
   487  
   488  You may use any of the built-in functions in your template. For more
   489  details on template usage, please see the
   490  [template_file documentation](/docs/providers/template/d/file.html).
   491  
   492  ### Using Templates with Count
   493  
   494  Here is an example that combines the capabilities of templates with the interpolation
   495  from `count` to give us a parameterized template, unique to each resource instance:
   496  
   497  ```hcl
   498  variable "hostnames" {
   499    default = {
   500      "0" = "example1.org"
   501      "1" = "example2.net"
   502    }
   503  }
   504  
   505  data "template_file" "web_init" {
   506    # Render the template once for each instance
   507    count    = "${length(var.hostnames)}"
   508    template = "${file("templates/web_init.tpl")}"
   509    vars {
   510      # count.index tells us the index of the instance we are rendering
   511      hostname = "${var.hostnames[count.index]}"
   512    }
   513  }
   514  
   515  resource "aws_instance" "web" {
   516    # Create one instance for each hostname
   517    count     = "${length(var.hostnames)}"
   518  
   519    # Pass each instance its corresponding template_file
   520    user_data = "${data.template_file.web_init.*.rendered[count.index]}"
   521  }
   522  ```
   523  
   524  With this, we will build a list of `template_file.web_init` data resources
   525  which we can use in combination with our list of `aws_instance.web` resources.
   526  
   527  ## Math
   528  
   529  Simple math can be performed in interpolations:
   530  
   531  ```hcl
   532  variable "count" {
   533    default = 2
   534  }
   535  
   536  resource "aws_instance" "web" {
   537    # ...
   538  
   539    count = "${var.count}"
   540  
   541    # Tag the instance with a counter starting at 1, ie. web-001
   542    tags {
   543      Name = "${format("web-%03d", count.index + 1)}"
   544    }
   545  }
   546  ```
   547  
   548  The supported operations are:
   549  
   550  - *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), and *Divide* (`/`) for **float** types
   551  - *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), *Divide* (`/`), and *Modulo* (`%`) for **integer** types
   552  
   553  Operator precedences is the standard mathematical order of operations:
   554  *Multiply* (`*`), *Divide* (`/`), and *Modulo* (`%`) have precedence over
   555  *Add* (`+`) and *Subtract* (`-`). Parenthesis can be used to force ordering.
   556  
   557  ```text
   558  "${2 * 4 + 3 * 3}" # computes to 17
   559  "${3 * 3 + 2 * 4}" # computes to 17
   560  "${2 * (4 + 3) * 3}" # computes to 42
   561  ```
   562  
   563  You can use the [terraform console](/docs/commands/console.html) command to
   564  try the math operations.
   565  
   566  -> **Note:** Since Terraform allows hyphens in resource and variable names,
   567  it's best to use spaces between math operators to prevent confusion or unexpected
   568  behavior. For example, `${var.instance-count - 1}` will subtract **1** from the
   569  `instance-count` variable value, while `${var.instance-count-1}` will interpolate
   570  the `instance-count-1` variable value.