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