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