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