github.com/mhlias/terraform@v0.6.12-0.20161118140322-a5d6410b912a/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 also perform [simple math](#math) in interpolations, allowing
    19  you to write expressions such as `${count.index + 1}`.
    20  
    21  You can escape interpolation with double dollar signs: `$${foo}`
    22  will be rendered as a literal `${foo}`.
    23  
    24  ## Available Variables
    25  
    26  **To reference user string variables**, use the `var.` prefix followed by the
    27  variable name. For example, `${var.foo}` will interpolate the
    28  `foo` variable value.
    29  
    30  **To reference user map variables**, the syntax is `var.MAP["KEY"]`.  For
    31  example, `${var.amis["us-east-1"]}` would get the value of the `us-east-1`
    32  key within the `amis` map variable.
    33  
    34  **To reference user list variables**, the syntax is `["${var.LIST}"]`.  For
    35  example, `["${var.subnets}"]` would get the value of the `subnets` list, as a
    36  list. You can also return list elements by index: `${var.subnets[idx]}`.
    37  
    38  **To reference attributes of your own resource**, the syntax is
    39  `self.ATTRIBUTE`. For example `${self.private_ip_address}` will
    40  interpolate that resource's private IP address. Note that this is
    41  only allowed/valid within provisioners.
    42  
    43  **To reference attributes of other resources**, the syntax is
    44  `TYPE.NAME.ATTRIBUTE`. For example, `${aws_instance.web.id}`
    45  will interpolate the ID attribute from the "aws\_instance"
    46  resource named "web". If the resource has a `count` attribute set,
    47  you can access individual attributes with a zero-based index, such
    48  as `${aws_instance.web.0.id}`. You can also use the splat syntax
    49  to get a list of all the attributes: `${aws_instance.web.*.id}`.
    50  This is documented in more detail in the
    51  [resource configuration page](/docs/configuration/resources.html).
    52  
    53  **To reference outputs from a module**, the syntax is
    54  `MODULE.NAME.OUTPUT`. For example `${module.foo.bar}` will
    55  interpolate the "bar" output from the "foo"
    56  [module](/docs/modules/index.html).
    57  
    58  **To reference count information**, the syntax is `count.FIELD`.
    59  For example, `${count.index}` will interpolate the current index
    60  in a multi-count resource. For more information on count, see the
    61  resource configuration page.
    62  
    63  <a id="path-variables"></a>
    64  
    65  **To reference path information**, the syntax is `path.TYPE`.
    66  TYPE can be `cwd`, `module`, or `root`. `cwd` will interpolate the
    67  cwd. `module` will interpolate the path to the current module. `root`
    68  will interpolate the path of the root module. In general, you probably
    69  want the `path.module` variable.
    70  
    71  <a id="functions"></a>
    72  ## Built-in Functions
    73  
    74  Terraform ships with built-in functions. Functions are called with
    75  the syntax `name(arg, arg2, ...)`. For example,
    76  to read a file: `${file("path.txt")}`. The built-in functions
    77  are documented below.
    78  
    79  The supported built-in functions are:
    80  
    81    * `base64decode(string)` - Given a base64-encoded string, decodes it and
    82      returns the original string.
    83  
    84    * `base64encode(string)` - Returns a base64-encoded representation of the
    85      given string.
    86  
    87    * `base64sha256(string)` - Returns a base64-encoded representation of raw
    88      SHA-256 sum of the given string.
    89      **This is not equivalent** of `base64encode(sha256(string))`
    90      since `sha256()` returns hexadecimal representation.
    91  
    92    * `cidrhost(iprange, hostnum)` - Takes an IP address range in CIDR notation
    93      and creates an IP address with the given host number. For example,
    94      ``cidrhost("10.0.0.0/8", 2)`` returns ``10.0.0.2``.
    95  
    96    * `cidrnetmask(iprange)` - Takes an IP address range in CIDR notation
    97      and returns the address-formatted subnet mask format that some
    98      systems expect for IPv4 interfaces. For example,
    99      ``cidrmask("10.0.0.0/8")`` returns ``255.0.0.0``. Not applicable
   100      to IPv6 networks since CIDR notation is the only valid notation for
   101      IPv4.
   102  
   103    * `cidrsubnet(iprange, newbits, netnum)` - Takes an IP address range in
   104      CIDR notation (like ``10.0.0.0/8``) and extends its prefix to include an
   105      additional subnet number. For example,
   106      ``cidrsubnet("10.0.0.0/8", 8, 2)`` returns ``10.2.0.0/16``;
   107      ``cidrsubnet("2607:f298:6051:516c::/64", 8, 2)`` returns
   108      ``2607:f298:6051:516c:200::/72``.
   109  
   110    * `coalesce(string1, string2, ...)` - Returns the first non-empty value from
   111      the given arguments. At least two arguments must be provided.
   112  
   113    * `compact(list)` - Removes empty string elements from a list. This can be
   114       useful in some cases, for example when passing joined lists as module
   115       variables or when parsing module outputs.
   116       Example: `compact(module.my_asg.load_balancer_names)`
   117  
   118    * `concat(list1, list2, ...)` - Combines two or more lists into a single list.
   119       Example: `concat(aws_instance.db.*.tags.Name, aws_instance.web.*.tags.Name)`
   120  
   121    * `distinct(list)` - Removes duplicate items from a list. Keeps the first
   122       occurrence of each element, and removes subsequent occurrences. This
   123       function is only valid for flat lists. Example: `distinct(var.usernames)`
   124  
   125    * `element(list, index)` - Returns a single element from a list
   126        at the given index. If the index is greater than the number of
   127        elements, this function will wrap using a standard mod algorithm.
   128        This function only works on flat lists. Examples:
   129        * `element(aws_subnet.foo.*.id, count.index)`
   130        * `element(var.list_of_strings, 2)`
   131  
   132    * `file(path)` - Reads the contents of a file into the string. Variables
   133        in this file are _not_ interpolated. The contents of the file are
   134        read as-is. The `path` is interpreted relative to the working directory.
   135        [Path variables](#path-variables) can be used to reference paths relative
   136        to other base locations. For example, when using `file()` from inside a
   137        module, you generally want to make the path relative to the module base,
   138        like this: `file("${path.module}/file")`.
   139  
   140    * `format(format, args, ...)` - Formats a string according to the given
   141        format. The syntax for the format is standard `sprintf` syntax.
   142        Good documentation for the syntax can be [found here](https://golang.org/pkg/fmt/).
   143        Example to zero-prefix a count, used commonly for naming servers:
   144        `format("web-%03d", count.index + 1)`.
   145  
   146    * `formatlist(format, args, ...)` - Formats each element of a list
   147        according to the given format, similarly to `format`, and returns a list.
   148        Non-list arguments are repeated for each list element.
   149        For example, to convert a list of DNS addresses to a list of URLs, you might use:
   150        `formatlist("https://%s:%s/", aws_instance.foo.*.public_dns, var.port)`.
   151        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.
   152        Example:
   153        `formatlist("instance %v has private ip %v", aws_instance.foo.*.id, aws_instance.foo.*.private_ip)`.
   154        Passing lists with different lengths to formatlist results in an error.
   155  
   156    * `index(list, elem)` - Finds the index of a given element in a list.
   157        This function only works on flat lists.
   158        Example: `index(aws_instance.foo.*.tags.Name, "foo-test")`
   159  
   160    * `join(delim, list)` - Joins the list with the delimiter for a resultant string.
   161        This function works only on flat lists.
   162        Examples:
   163        * `join(",", aws_instance.foo.*.id)`
   164        * `join(",", var.ami_list)`
   165  
   166    * `jsonencode(item)` - Returns a JSON-encoded representation of the given
   167      item, which may be a string, list of strings, or map from string to string.
   168      Note that if the item is a string, the return value includes the double
   169      quotes.
   170  
   171    * `keys(map)` - Returns a lexically sorted list of the map keys.
   172  
   173    * `length(list)` - Returns a number of members in a given list or map, or a number of characters in a given string.
   174        * `${length(split(",", "a,b,c"))}` = 3
   175        * `${length("a,b,c")}` = 5
   176        * `${length(map("key", "val"))}` = 1
   177  
   178    * `list(items, ...)` - Returns a list consisting of the arguments to the function.
   179        This function provides a way of representing list literals in interpolation.
   180        * `${list("a", "b", "c")}` returns a list of `"a", "b", "c"`.
   181        * `${list()}` returns an empty list.
   182  
   183    * `lookup(map, key [, default])` - Performs a dynamic lookup into a map
   184        variable. The `map` parameter should be another variable, such
   185        as `var.amis`. If `key` does not exist in `map`, the interpolation will
   186        fail unless you specify a third argument, `default`, which should be a
   187        string value to return if no `key` is found in `map`. This function
   188        only works on flat maps and will return an error for maps that
   189        include nested lists or maps.
   190  
   191    * `lower(string)` - Returns a copy of the string with all Unicode letters mapped to their lower case.
   192  
   193    * `map(key, value, ...)` - Returns a map consisting of the key/value pairs
   194      specified as arguments. Every odd argument must be a string key, and every
   195      even argument must have the same type as the other values specified.
   196      Duplicate keys are not allowed. Examples:
   197      * `map("hello", "world")`
   198      * `map("us-east", list("a", "b", "c"), "us-west", list("b", "c", "d"))`
   199  
   200    * `merge(map1, map2, ...)` - Returns the union of 2 or more maps. The maps
   201  	are consumed in the order provided, and duplicate keys overwrite previous
   202  	entries.
   203  	* `${merge(map("a", "b"), map("c", "d"))}` returns `{"a": "b", "c": "d"}`
   204  
   205    * `md5(string)` - Returns a (conventional) hexadecimal representation of the
   206      MD5 hash of the given string.
   207  
   208    * `replace(string, search, replace)` - Does a search and replace on the
   209        given string. All instances of `search` are replaced with the value
   210        of `replace`. If `search` is wrapped in forward slashes, it is treated
   211        as a regular expression. If using a regular expression, `replace`
   212        can reference subcaptures in the regular expression by using `$n` where
   213        `n` is the index or name of the subcapture. If using a regular expression,
   214        the syntax conforms to the [re2 regular expression syntax](https://code.google.com/p/re2/wiki/Syntax).
   215  
   216    * `sha1(string)` - Returns a (conventional) hexadecimal representation of the
   217      SHA-1 hash of the given string.
   218      Example: `"${sha1("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   219  
   220    * `sha256(string)` - Returns a (conventional) hexadecimal representation of the
   221      SHA-256 hash of the given string.
   222      Example: `"${sha256("${aws_vpc.default.tags.customer}-s3-bucket")}"`
   223  
   224    * `signum(int)` - Returns -1 for negative numbers, 0 for 0 and 1 for positive numbers.
   225        This function is useful when you need to set a value for the first resource and
   226        a different value for the rest of the resources.
   227        Example: `element(split(",", var.r53_failover_policy), signum(count.index))`
   228        where the 0th index points to `PRIMARY` and 1st to `FAILOVER`
   229  
   230    * `sort(list)` - Returns a lexographically sorted list of the strings contained in
   231        the list passed as an argument. Sort may only be used with lists which contain only
   232        strings.
   233        Examples: `sort(aws_instance.foo.*.id)`, `sort(var.list_of_strings)`
   234  
   235    * `split(delim, string)` - Splits the string previously created by `join`
   236        back into a list. This is useful for pushing lists through module
   237        outputs since they currently only support string values. Depending on the
   238        use, the string this is being performed within may need to be wrapped
   239        in brackets to indicate that the output is actually a list, e.g.
   240        `a_resource_param = ["${split(",", var.CSV_STRING)}"]`.
   241        Example: `split(",", module.amod.server_ids)`
   242  
   243    * `trimspace(string)` - Returns a copy of the string with all leading and trailing white spaces removed.
   244  
   245    * `upper(string)` - Returns a copy of the string with all Unicode letters mapped to their upper case.
   246  
   247    * `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.
   248  
   249    * `values(map)` - Returns a list of the map values, in the order of the keys
   250      returned by the `keys` function. This function only works on flat maps and
   251      will return an error for maps that include nested lists or maps.
   252  
   253  <a id="templates"></a>
   254  ## Templates
   255  
   256  Long strings can be managed using templates. [Templates](/docs/providers/template/index.html) are [data-sources](/docs/configuration/data-sources.html) defined by a filename and some variables to use during interpolation. They have a computed `rendered` attribute containing the result.
   257  
   258  A template data source looks like:
   259  
   260  ```
   261  data "template_file" "example" {
   262    template = "${hello} ${world}!"
   263    vars {
   264      hello = "goodnight"
   265      world = "moon"
   266    }
   267  }
   268  
   269  output "rendered" {
   270    value = "${data.template_file.example.rendered}"
   271  }
   272  ```
   273  
   274  Then the rendered value would be `goodnight moon!`.
   275  
   276  You may use any of the built-in functions in your template.
   277  
   278  ### Using Templates with Count
   279  
   280  Here is an example that combines the capabilities of templates with the interpolation
   281  from `count` to give us a parameterized template, unique to each resource instance:
   282  
   283  ```
   284  variable "count" {
   285    default = 2
   286  }
   287  
   288  variable "hostnames" {
   289    default = {
   290      "0" = "example1.org"
   291      "1" = "example2.net"
   292    }
   293  }
   294  
   295  data "template_file" "web_init" {
   296    // here we expand multiple template_files - the same number as we have instances
   297    count    = "${var.count}"
   298    template = "${file("templates/web_init.tpl")}"
   299    vars {
   300      // that gives us access to use count.index to do the lookup
   301      hostname = "${lookup(var.hostnames, count.index)}"
   302    }
   303  }
   304  
   305  resource "aws_instance" "web" {
   306    // ...
   307    count = "${var.count}"
   308    // here we link each web instance to the proper template_file
   309    user_data = "${element(data.template_file.web_init.*.rendered, count.index)}"
   310  }
   311  ```
   312  
   313  With this, we will build a list of `template_file.web_init` data sources which we can
   314  use in combination with our list of `aws_instance.web` resources.
   315  
   316  <a id="math"></a>
   317  ## Math
   318  
   319  Simple math can be performed in interpolations:
   320  
   321  ```
   322  variable "count" {
   323    default = 2
   324  }
   325  
   326  resource "aws_instance" "web" {
   327    // ...
   328    count = "${var.count}"
   329  
   330    // tag the instance with a counter starting at 1, ie. web-001
   331    tags {
   332      Name = "${format("web-%03d", count.index + 1)}"
   333    }
   334  }
   335  ```
   336  
   337  The supported operations are:
   338  
   339  - *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), and *Divide* (`/`) for **float** types
   340  - *Add* (`+`), *Subtract* (`-`), *Multiply* (`*`), *Divide* (`/`), and *Modulo* (`%`) for **integer** types
   341  
   342  -> **Note:** Since Terraform allows hyphens in resource and variable names,
   343  it's best to use spaces between math operators to prevent confusion or unexpected
   344  behavior. For example, `${var.instance-count - 1}` will subtract **1** from the
   345  `instance-count` variable value, while `${var.instance-count-1}` will interpolate
   346  the `instance-count-1` variable value.