github.com/vtorhonen/terraform@v0.9.0-beta2.0.20170307220345-5d894e4ffda7/website/source/docs/configuration/interpolation.html.md (about)

     1  ---
     2  layout: "docs"
     3  page_title: "Interpolation Syntax"
     4  sidebar_current: "docs-config-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  Embedded within strings in Terraform, whether you're using the
    12  Terraform syntax or JSON syntax, you can interpolate other values. These
    13  interpolations are wrapped in `${}`, such as `${var.foo}`.
    14  
    15  The interpolation syntax is powerful and allows you to reference
    16  variables, attributes of resources, call functions, etc.
    17  
    18  You can perform [simple math](#math) in interpolations, allowing
    19  you to write expressions such as `${count.index + 1}`. And you can
    20  also use [conditionals](#conditionals) to determine a value based
    21  on some logic.
    22  
    23  You can escape interpolation with double dollar signs: `$${foo}`
    24  will be rendered as a literal `${foo}`.
    25  
    26  ## Available Variables
    27  
    28  There are a variety of available variable references you can use.
    29  
    30  #### User string variables
    31  
    32  Use the `var.` prefix followed by the variable name. For example,
    33  `${var.foo}` will interpolate the `foo` variable value.
    34  
    35  #### User map variables
    36  
    37  The syntax is `var.MAP["KEY"]`. For example, `${var.amis["us-east-1"]}`
    38  would get the value of the `us-east-1` key within the `amis` map
    39  variable.
    40  
    41  #### User list variables
    42  
    43  The syntax is `["${var.LIST}"]`. For example, `["${var.subnets}"]`
    44  would get the value of the `subnets` list, as a list. You can also
    45  return list elements by index: `${var.subnets[idx]}`.
    46  
    47  #### Attributes of your own resource
    48  
    49  The syntax is `self.ATTRIBUTE`. For example `${self.private_ip_address}`
    50  will interpolate that resource's private IP address.
    51  
    52  -> **Note**: The `self.ATTRIBUTE` syntax is only allowed and valid within
    53  provisioners.
    54  
    55  #### Attributes of other resources
    56  
    57  The syntax is `TYPE.NAME.ATTRIBUTE`. For example,
    58  `${aws_instance.web.id}` will interpolate the ID attribute from the
    59  `aws_instance` resource named `web`. If the resource has a `count`
    60  attribute set, you can access individual attributes with a zero-based
    61  index, such as `${aws_instance.web.0.id}`. You can also use the splat
    62  syntax to get a list of all the attributes: `${aws_instance.web.*.id}`.
    63  
    64  #### Outputs from a module
    65  
    66  The syntax is `MODULE.NAME.OUTPUT`. For example `${module.foo.bar}` will
    67  interpolate the `bar` output from the `foo`
    68  [module](/docs/modules/index.html).
    69  
    70  #### Count information
    71  
    72  The syntax is `count.FIELD`. For example, `${count.index}` will
    73  interpolate the current index in a multi-count resource. For more
    74  information on `count`, see the [resource configuration
    75  page](/docs/configuration/resources.html).
    76  
    77  <a id="path-variables"></a>
    78  
    79  #### Path information
    80  
    81  The syntax is `path.TYPE`. TYPE can be `cwd`, `module`, or `root`.
    82  `cwd` will interpolate the current working directory. `module` will
    83  interpolate the path to the current module. `root` will interpolate the
    84  path of the root module.  In general, you probably want the
    85  `path.module` variable.
    86  
    87  <a id="conditionals"></a>
    88  ## Conditionals
    89  
    90  Interpolations may contain conditionals to branch on the final value.
    91  
    92  ```
    93  resource "aws_instance" "web" {
    94    subnet = "${var.env == "production" ? var.prod_subnet : var.dev_subnet}"
    95  }
    96  ```
    97  
    98  The conditional syntax is the well-known ternary operation:
    99  
   100      CONDITION ? TRUEVAL : FALSEVAL
   101  
   102  The condition can be any valid interpolation syntax, such as variable
   103  access, a function call, or even another conditional. The true and false
   104  value can also be any valid interpolation syntax. The returned types by
   105  the true and false side must be the same.
   106  
   107  The support operators are:
   108  
   109    * Equality: `==` and `!=`
   110    * Numerical comparison: `>`, `<`, `>=`, `<=`
   111    * Boolean logic: `&&`, `||`, unary `!`
   112  
   113  A common use case for conditionals is to enable/disable a resource by
   114  conditionally setting the count:
   115  
   116  ```
   117  resource "aws_instance" "vpn" {
   118    count = "${var.something ? 1 : 0}"
   119  }
   120  ```
   121  
   122  In the example above, the "vpn" resource will only be included if
   123  "var.something" evaluates to true. Otherwise, the VPN resource will
   124  not be created at all.
   125  
   126  <a id="functions"></a>
   127  ## Built-in Functions
   128  
   129  Terraform ships with built-in functions. Functions are called with the
   130  syntax `name(arg, arg2, ...)`. For example, to read a file:
   131  `${file("path.txt")}`.
   132  
   133  ### Supported built-in functions
   134  
   135  The supported built-in functions are:
   136  
   137    * `base64decode(string)` - Given a base64-encoded string, decodes it and
   138      returns the original string.
   139  
   140    * `base64encode(string)` - Returns a base64-encoded representation of the
   141      given string.
   142  
   143    * `base64sha256(string)` - Returns a base64-encoded representation of raw
   144      SHA-256 sum of the given string.
   145      **This is not equivalent** of `base64encode(sha256(string))`
   146      since `sha256()` returns hexadecimal representation.
   147  
   148    * `ceil(float)` - Returns the least integer value greater than or equal
   149        to the argument.
   150  
   151    * `cidrhost(iprange, hostnum)` - Takes an IP address range in CIDR notation
   152      and creates an IP address with the given host number. For example,
   153      `cidrhost("10.0.0.0/8", 2)` returns `10.0.0.2`.
   154  
   155    * `cidrnetmask(iprange)` - Takes an IP address range in CIDR notation
   156      and returns the address-formatted subnet mask format that some
   157      systems expect for IPv4 interfaces. For example,
   158      `cidrnetmask("10.0.0.0/8")` returns `255.0.0.0`. Not applicable
   159      to IPv6 networks since CIDR notation is the only valid notation for
   160      IPv6.
   161  
   162    * `cidrsubnet(iprange, newbits, netnum)` - Takes an IP address range in
   163      CIDR notation (like `10.0.0.0/8`) and extends its prefix to include an
   164      additional subnet number. For example,
   165      `cidrsubnet("10.0.0.0/8", 8, 2)` returns `10.2.0.0/16`;
   166      `cidrsubnet("2607:f298:6051:516c::/64", 8, 2)` returns
   167      `2607:f298:6051:516c:200::/72`.
   168  
   169    * `coalesce(string1, string2, ...)` - Returns the first non-empty value from
   170      the given arguments. At least two arguments must be provided.
   171  
   172    * `compact(list)` - Removes empty string elements from a list. This can be
   173       useful in some cases, for example when passing joined lists as module
   174       variables or when parsing module outputs.
   175       Example: `compact(module.my_asg.load_balancer_names)`
   176  
   177    * `concat(list1, list2, ...)` - Combines two or more lists into a single list.
   178       Example: `concat(aws_instance.db.*.tags.Name, aws_instance.web.*.tags.Name)`
   179  
   180    * `distinct(list)` - Removes duplicate items from a list. Keeps the first
   181       occurrence of each element, and removes subsequent occurrences. This
   182       function is only valid for flat lists. Example: `distinct(var.usernames)`
   183  
   184    * `element(list, index)` - Returns a single element from a list
   185        at the given index. If the index is greater than the number of
   186        elements, this function will wrap using a standard mod algorithm.
   187        This function only works on flat lists. Examples:
   188        * `element(aws_subnet.foo.*.id, count.index)`
   189        * `element(var.list_of_strings, 2)`
   190  
   191    * `file(path)` - Reads the contents of a file into the string. Variables
   192        in this file are _not_ interpolated. The contents of the file are
   193        read as-is. The `path` is interpreted relative to the working directory.
   194        [Path variables](#path-variables) can be used to reference paths relative
   195        to other base locations. For example, when using `file()` from inside a
   196        module, you generally want to make the path relative to the module base,
   197        like this: `file("${path.module}/file")`.
   198  
   199    * `floor(float)` - Returns the greatest integer value less than or equal to
   200        the argument.
   201  
   202    * `format(format, args, ...)` - Formats a string according to the given
   203        format. The syntax for the format is standard `sprintf` syntax.
   204        Good documentation for the syntax can be [found here](https://golang.org/pkg/fmt/).
   205        Example to zero-prefix a count, used commonly for naming servers:
   206        `format("web-%03d", count.index + 1)`.
   207  
   208    * `formatlist(format, args, ...)` - Formats each element of a list
   209        according to the given format, similarly to `format`, and returns a list.
   210        Non-list arguments are repeated for each list element.
   211        For example, to convert a list of DNS addresses to a list of URLs, you might use:
   212        `formatlist("https://%s:%s/", aws_instance.foo.*.public_dns, var.port)`.
   213        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.
   214        Example:
   215        `formatlist("instance %v has private ip %v", aws_instance.foo.*.id, aws_instance.foo.*.private_ip)`.
   216        Passing lists with different lengths to formatlist results in an error.
   217  
   218    * `index(list, elem)` - Finds the index of a given element in a list.
   219        This function only works on flat lists.
   220        Example: `index(aws_instance.foo.*.tags.Name, "foo-test")`
   221  
   222    * `join(delim, list)` - Joins the list with the delimiter for a resultant string.
   223        This function works only on flat lists.
   224        Examples:
   225        * `join(",", aws_instance.foo.*.id)`
   226        * `join(",", var.ami_list)`
   227  
   228    * `jsonencode(item)` - Returns a JSON-encoded representation of the given
   229      item, which may be a string, list of strings, or map from string to string.
   230      Note that if the item is a string, the return value includes the double
   231      quotes.
   232  
   233    * `keys(map)` - Returns a lexically sorted list of the map keys.
   234  
   235    * `length(list)` - Returns the number of members in a given list or map, or the number of characters in a given string.
   236        * `${length(split(",", "a,b,c"))}` = 3
   237        * `${length("a,b,c")}` = 5
   238        * `${length(map("key", "val"))}` = 1
   239  
   240    * `list(items, ...)` - Returns a list consisting of the arguments to the function.
   241        This function provides a way of representing list literals in interpolation.
   242        * `${list("a", "b", "c")}` returns a list of `"a", "b", "c"`.
   243        * `${list()}` returns an empty list.
   244  
   245    * `lookup(map, key, [default])` - Performs a dynamic lookup into a map
   246        variable. The `map` parameter should be another variable, such
   247        as `var.amis`. If `key` does not exist in `map`, the interpolation will
   248        fail unless you specify a third argument, `default`, which should be a
   249        string value to return if no `key` is found in `map`. This function
   250        only works on flat maps and will return an error for maps that
   251        include nested lists or maps.
   252  
   253    * `lower(string)` - Returns a copy of the string with all Unicode letters mapped to their lower case.
   254  
   255    * `map(key, value, ...)` - Returns a map consisting of the key/value pairs
   256      specified as arguments. Every odd argument must be a string key, and every
   257      even argument must have the same type as the other values specified.
   258      Duplicate keys are not allowed. Examples:
   259      * `map("hello", "world")`
   260      * `map("us-east", list("a", "b", "c"), "us-west", list("b", "c", "d"))`
   261  
   262    * `max(float1, float2, ...)` - Returns the largest of the floats.
   263  
   264    * `merge(map1, map2, ...)` - Returns the union of 2 or more maps. The maps
   265  	are consumed in the order provided, and duplicate keys overwrite previous
   266  	entries.
   267  	* `${merge(map("a", "b"), map("c", "d"))}` returns `{"a": "b", "c": "d"}`
   268  
   269    * `min(float1, float2, ...)` - Returns the smallest of the floats.
   270  
   271    * `md5(string)` - Returns a (conventional) hexadecimal representation of the
   272      MD5 hash of the given string.
   273  
   274    * `pathexpand(string)` - Returns a filepath string with `~` expanded to the home directory. Note:
   275      This will create a plan diff between two different hosts, unless the filepaths are the same.
   276    
   277    * `replace(string, search, replace)` - Does a search and replace on the
   278        given string. All instances of `search` are replaced with the value
   279        of `replace`. If `search` is wrapped in forward slashes, it is treated
   280        as a regular expression. If using a regular expression, `replace`
   281        can reference subcaptures in the regular expression by using `$n` where
   282        `n` is the index or name of the subcapture. If using a regular expression,
   283        the syntax conforms to the [re2 regular expression syntax](https://code.google.com/p/re2/wiki/Syntax).
   284  
   285    * `sha1(string)` - Returns a (conventional) hexadecimal representation of the
   286      SHA-1 hash of the given string.
   287      Example: `"${sha1("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   288  
   289    * `sha256(string)` - Returns a (conventional) hexadecimal representation of the
   290      SHA-256 hash of the given string.
   291      Example: `"${sha256("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   292  
   293    * `signum(int)` - Returns `-1` for negative numbers, `0` for `0` and `1` for positive numbers.
   294        This function is useful when you need to set a value for the first resource and
   295        a different value for the rest of the resources.
   296        Example: `element(split(",", var.r53_failover_policy), signum(count.index))`
   297        where the 0th index points to `PRIMARY` and 1st to `FAILOVER`
   298  
   299    * `slice(list, from, to)` - Returns the portion of `list` between `from` (inclusive) and `to` (exclusive).
   300        Example: `slice(var.list_of_strings, 0, length(var.list_of_strings) - 1)`
   301  
   302    * `sort(list)` - Returns a lexographically sorted list of the strings contained in
   303        the list passed as an argument. Sort may only be used with lists which contain only
   304        strings.
   305        Examples: `sort(aws_instance.foo.*.id)`, `sort(var.list_of_strings)`
   306  
   307    * `split(delim, string)` - Splits the string previously created by `join`
   308        back into a list. This is useful for pushing lists through module
   309        outputs since they currently only support string values. Depending on the
   310        use, the string this is being performed within may need to be wrapped
   311        in brackets to indicate that the output is actually a list, e.g.
   312        `a_resource_param = ["${split(",", var.CSV_STRING)}"]`.
   313        Example: `split(",", module.amod.server_ids)`
   314  
   315    * `timestamp()` - Returns a UTC timestamp string in RFC 3339 format. This string will change with every
   316     invocation of the function, so in order to prevent diffs on every plan & apply, it must be used with the
   317     [`ignore_changes`](/docs/configuration/resources.html#ignore-changes) lifecycle attribute.
   318  
   319    * `title(string)` - Returns a copy of the string with the first characters of all the words capitalized.
   320  
   321    * `trimspace(string)` - Returns a copy of the string with all leading and trailing white spaces removed.
   322  
   323    * `upper(string)` - Returns a copy of the string with all Unicode letters mapped to their upper case.
   324  
   325    * `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.
   326  
   327    * `values(map)` - Returns a list of the map values, in the order of the keys
   328      returned by the `keys` function. This function only works on flat maps and
   329      will return an error for maps that include nested lists or maps.
   330  
   331    * `zipmap(list, list)` - Creates a map from a list of keys and a list of
   332        values. The keys must all be of type string, and the length of the lists
   333        must be the same.
   334        For example, to output a mapping of AWS IAM user names to the fingerprint
   335        of the key used to encrypt their initial password, you might use:
   336        `zipmap(aws_iam_user.users.*.name, aws_iam_user_login_profile.users.*.key_fingerprint)`.
   337  
   338  <a id="templates"></a>
   339  ## Templates
   340  
   341  Long strings can be managed using templates.
   342  [Templates](/docs/providers/template/index.html) are
   343  [data-sources](/docs/configuration/data-sources.html) defined by a
   344  filename and some variables to use during interpolation. They have a
   345  computed `rendered` attribute containing the result.
   346  
   347  A template data source looks like:
   348  
   349  ```
   350  data "template_file" "example" {
   351    template = "$${hello} $${world}!"
   352    vars {
   353      hello = "goodnight"
   354      world = "moon"
   355    }
   356  }
   357  
   358  output "rendered" {
   359    value = "${data.template_file.example.rendered}"
   360  }
   361  ```
   362  
   363  Then the rendered value would be `goodnight moon!`.
   364  
   365  You may use any of the built-in functions in your template. For more
   366  details on template usage, please see the
   367  [template_file documentation](/docs/providers/template/d/file.html).
   368  
   369  ### Using Templates with Count
   370  
   371  Here is an example that combines the capabilities of templates with the interpolation
   372  from `count` to give us a parameterized template, unique to each resource instance:
   373  
   374  ```
   375  variable "count" {
   376    default = 2
   377  }
   378  
   379  variable "hostnames" {
   380    default = {
   381      "0" = "example1.org"
   382      "1" = "example2.net"
   383    }
   384  }
   385  
   386  data "template_file" "web_init" {
   387    // here we expand multiple template_files - the same number as we have instances
   388    count    = "${var.count}"
   389    template = "${file("templates/web_init.tpl")}"
   390    vars {
   391      // that gives us access to use count.index to do the lookup
   392      hostname = "${lookup(var.hostnames, count.index)}"
   393    }
   394  }
   395  
   396  resource "aws_instance" "web" {
   397    // ...
   398    count = "${var.count}"
   399    // here we link each web instance to the proper template_file
   400    user_data = "${element(data.template_file.web_init.*.rendered, count.index)}"
   401  }
   402  ```
   403  
   404  With this, we will build a list of `template_file.web_init` data sources which we can
   405  use in combination with our list of `aws_instance.web` resources.
   406  
   407  <a id="math"></a>
   408  ## Math
   409  
   410  Simple math can be performed in interpolations:
   411  
   412  ```
   413  variable "count" {
   414    default = 2
   415  }
   416  
   417  resource "aws_instance" "web" {
   418    // ...
   419    count = "${var.count}"
   420  
   421    // tag the instance with a counter starting at 1, ie. web-001
   422    tags {
   423      Name = "${format("web-%03d", count.index + 1)}"
   424    }
   425  }
   426  ```
   427  
   428  The supported operations are:
   429  
   430  - *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), and *Divide* (`/`) for **float** types
   431  - *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), *Divide* (`/`), and *Modulo* (`%`) for **integer** types
   432  
   433  Operator precedences is the standard mathematical order of operations:
   434  *Multiply* (`*`), *Divide* (`/`), and *Modulo* (`%`) have precedence over
   435  *Add* (`+`) and *Subtract* (`-`). Parenthesis can be used to force ordering.
   436  
   437  ```
   438  "${2 * 4 + 3 * 3}" # computes to 17
   439  "${3 * 3 + 2 * 4}" # computes to 17
   440  "${2 * (4 + 3) * 3}" # computes to 42
   441  ```
   442  
   443  You can use the [terraform console](/docs/commands/console.html) command to
   444  try the math operations.
   445  
   446  -> **Note:** Since Terraform allows hyphens in resource and variable names,
   447  it's best to use spaces between math operators to prevent confusion or unexpected
   448  behavior. For example, `${var.instance-count - 1}` will subtract **1** from the
   449  `instance-count` variable value, while `${var.instance-count-1}` will interpolate
   450  the `instance-count-1` variable value.