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