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