github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/website/docs/configuration/expressions.html.md (about) 1 --- 2 layout: "docs" 3 page_title: "Expressions - Configuration Language" 4 sidebar_current: "docs-config-expressions" 5 description: |- 6 The Terraform language allows the use of expressions to access data exported 7 by resources and to transform and combine that data to produce other values. 8 --- 9 10 # Expressions 11 12 -> **Note:** This page is about Terraform 0.12 and later. For Terraform 0.11 and 13 earlier, see 14 [0.11 Configuration Language: Interpolation Syntax](../configuration-0-11/interpolation.html). 15 16 _Expressions_ are used to refer to or compute values within a configuration. 17 The simplest expressions are just literal values, like `"hello"` or `5`, 18 but the Terraform language also allows more complex expressions such as 19 references to data exported by resources, arithmetic, conditional evaluation, 20 and a number of built-in functions. 21 22 Expressions can be used in a number of places in the Terraform language, 23 but some contexts limit which expression constructs are allowed, 24 such as requiring a literal value of a particular type or forbidding 25 [references to resource attributes](/docs/configuration/expressions.html#references-to-resource-attributes). 26 Each language feature's documentation describes any restrictions it places on expressions. 27 28 You can experiment with the behavior of Terraform's expressions from 29 the Terraform expression console, by running 30 [the `terraform console` command](/docs/commands/console.html). 31 32 The rest of this page describes all of the features of Terraform's 33 expression syntax. 34 35 ## Types and Values 36 37 The result of an expression is a _value_. All values have a _type_, which 38 dictates where that value can be used and what transformations can be 39 applied to it. 40 41 The Terraform language uses the following types for its values: 42 43 * `string`: a sequence of Unicode characters representing some text, like 44 `"hello"`. 45 * `number`: a numeric value. The `number` type can represent both whole 46 numbers like `15` and fractional values like `6.283185`. 47 * `bool`: either `true` or `false`. `bool` values can be used in conditional 48 logic. 49 * `list` (or `tuple`): a sequence of values, like 50 `["us-west-1a", "us-west-1c"]`. Elements in a list or tuple are identified by 51 consecutive whole numbers, starting with zero. 52 * `map` (or `object`): a group of values identified by named labels, like 53 `{name = "Mabel", age = 52}`. 54 55 Strings, numbers, and bools are sometimes called _primitive types._ Lists/tuples and maps/objects are sometimes called _complex types,_ _structural types,_ or _collection types._ 56 57 Finally, there is one special value that has _no_ type: 58 59 * `null`: a value that represents _absence_ or _omission._ If you set an 60 argument of a resource or module to `null`, Terraform behaves as though you 61 had completely omitted it — it will use the argument's default value if it has 62 one, or raise an error if the argument is mandatory. `null` is most useful in 63 conditional expressions, so you can dynamically omit an argument if a 64 condition isn't met. 65 66 ### Advanced Type Details 67 68 In most situations, lists and tuples behave identically, as do maps and objects. 69 Whenever the distinction isn't relevant, the Terraform documentation uses each 70 pair of terms interchangeably (with a historical preference for "list" and 71 "map"). 72 73 However, module authors and provider developers should understand the 74 differences between these similar types (and the related `set` type), since they 75 offer different ways to restrict the allowed values for input variables and 76 resource arguments. 77 78 For complete details about these types (and an explanation of why the difference 79 usually doesn't matter), see [Type Constraints](./types.html). 80 81 ### Type Conversion 82 83 Expressions are most often used to set values for the arguments of resources and 84 child modules. In these cases, the argument has an expected type and the given 85 expression must produce a value of that type. 86 87 Where possible, Terraform automatically converts values from one type to 88 another in order to produce the expected type. If this isn't possible, Terraform 89 will produce a type mismatch error and you must update the configuration with a 90 more suitable expression. 91 92 Terraform automatically converts number and bool values to strings when needed. 93 It also converts strings to numbers or bools, as long as the string contains a 94 valid representation of a number or bool value. 95 96 * `true` converts to `"true"`, and vice-versa 97 * `false` converts to `"false"`, and vice-versa 98 * `15` converts to `"15"`, and vice-versa 99 100 ## Literal Expressions 101 102 A _literal expression_ is an expression that directly represents a particular 103 constant value. Terraform has a literal expression syntax for each of the value 104 types described above: 105 106 * Strings are usually represented by a double-quoted sequence of Unicode 107 characters, `"like this"`. There is also a "heredoc" syntax for more complex 108 strings. String literals are the most complex kind of literal expression in 109 Terraform, and have additional documentation on this page: 110 * See [String Literals](#string-literals) below for information about escape 111 sequences and the heredoc syntax. 112 * See [String Templates](#string-templates) below for information about 113 interpolation and template directives. 114 * Numbers are represented by unquoted sequences of digits with or without a 115 decimal point, like `15` or `6.283185`. 116 * Bools are represented by the unquoted symbols `true` and `false`. 117 * The null value is represented by the unquoted symbol `null`. 118 * Lists/tuples are represented by a pair of square brackets containing a 119 comma-separated sequence of values, like `["a", 15, true]`. 120 121 List literals can be split into multiple lines for readability, but always 122 require a comma between values. A comma after the final value is allowed, 123 but not required. Values in a list can be arbitrary expressions. 124 * Maps/objects are represented by a pair of curly braces containing a series of 125 `<KEY> = <VALUE>` pairs: 126 127 ```hcl 128 { 129 name = "John" 130 age = 52 131 } 132 ``` 133 134 Key/value pairs can be separated by either a comma or a line break. Values 135 can be arbitrary expressions. Keys are strings; they can be left unquoted if 136 they are a valid [identifier](./syntax.html#identifiers), but must be quoted 137 otherwise. You can use a non-literal expression as a key by wrapping it in 138 parentheses, like `(var.business_unit_tag_name) = "SRE"`. 139 140 ## Indices and Attributes 141 142 [inpage-index]: #indices-and-attributes 143 144 Elements of list/tuple and map/object values can be accessed using 145 the square-bracket index notation, like `local.list[3]`. The expression within 146 the brackets must be a whole number for list and tuple values or a string 147 for map and object values. 148 149 Map/object attributes with names that are valid identifiers can also be accessed 150 using the dot-separated attribute notation, like `local.object.attrname`. 151 In cases where a map might contain arbitrary user-specified keys, we recommend 152 using only the square-bracket index notation (`local.map["keyname"]`). 153 154 ## References to Named Values 155 156 Terraform makes several kinds of named values available. Each of these names is 157 an expression that references the associated value; you can use them as 158 standalone expressions, or combine them with other expressions to compute new 159 values. 160 161 The following named values are available: 162 163 * `<RESOURCE TYPE>.<NAME>` is an object representing a 164 [managed resource](./resources.html) of the given type 165 and name. The attributes of the resource can be accessed using 166 [dot or square bracket notation][inpage-index]. 167 168 Any named value that does not match another pattern listed below 169 will be interpreted by Terraform as a reference to a managed resource. 170 171 If the resource has the `count` argument set, the value of this expression 172 is a _list_ of objects representing its instances. 173 174 If the resource has the `for_each` argument set, the value of this expression 175 is a _map_ of objects representing its instances. 176 177 For more information, see 178 [references to resource attributes](#references-to-resource-attributes) below. 179 * `var.<NAME>` is the value of the 180 [input variable](./variables.html) of the given name. 181 * `local.<NAME>` is the value of the 182 [local value](./locals.html) of the given name. 183 * `module.<MODULE NAME>.<OUTPUT NAME>` is the value of the specified 184 [output value](./outputs.html) from a 185 [child module](./modules.html) called by the current module. 186 * `data.<DATA TYPE>.<NAME>` is an object representing a 187 [data resource](./data-sources.html) of the given data 188 source type and name. If the resource has the `count` argument set, the value 189 is a list of objects representing its instances. If the resource has the `for_each` 190 argument set, the value is a map of objects representing its instances. 191 * `path.module` is the filesystem path of the module where the expression 192 is placed. 193 * `path.root` is the filesystem path of the root module of the configuration. 194 * `path.cwd` is the filesystem path of the current working directory. In 195 normal use of Terraform this is the same as `path.root`, but some advanced 196 uses of Terraform run it from a directory other than the root module 197 directory, causing these paths to be different. 198 * `terraform.workspace` is the name of the currently selected 199 [workspace](/docs/state/workspaces.html). 200 201 Although many of these names use dot-separated paths that resemble 202 [attribute notation][inpage-index] for elements of object values, they are not 203 implemented as real objects. This means you must use them exactly as written: 204 you cannot use square-bracket notation to replace the dot-separated paths, and 205 you cannot iterate over the "parent object" of a named entity (for example, you 206 cannot use `aws_instance` in a `for` expression). 207 208 ### Local Named Values 209 210 Within the bodies of certain expressions, or in some other specific contexts, 211 there are other named values available beyond the global values listed above. 212 These local names are described in the documentation for the specific contexts 213 where they appear. Some of most common local names are: 214 215 - `count.index`, in resources that use 216 [the `count` meta-argument](./resources.html#count-multiple-resource-instances-by-count). 217 - `each.key` / `each.value`, in resources that use 218 [the `for_each` meta-argument](./resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings). 219 - `self`, in [provisioner](../provisioners/index.html) and 220 [connection](../provisioners/connection.html) blocks. 221 222 -> **Note:** Local names are often referred to as _variables_ or 223 _temporary variables_ in their documentation. These are not [input 224 variables](./variables.html); they are just arbitrary names 225 that temporarily represent a value. 226 227 ### Named Values and Dependencies 228 229 Constructs like resources and module calls often use references to named values 230 in their block bodies, and Terraform analyzes these expressions to automatically 231 infer dependencies between objects. For example, an expression in a resource 232 argument that refers to another managed resource creates an implicit dependency 233 between the two resources. 234 235 ### References to Resource Attributes 236 237 The most common reference type is a reference to an attribute of a resource 238 which has been declared either with a `resource` or `data` block. Because 239 the contents of such blocks can be quite complicated themselves, expressions 240 referring to these contents can also be complicated. 241 242 Consider the following example resource block: 243 244 ```hcl 245 resource "aws_instance" "example" { 246 ami = "ami-abc123" 247 instance_type = "t2.micro" 248 249 ebs_block_device { 250 device_name = "sda2" 251 volume_size = 16 252 } 253 ebs_block_device { 254 device_name = "sda3" 255 volume_size = 20 256 } 257 } 258 ``` 259 260 The documentation for [`aws_instance`](/docs/providers/aws/r/instance.html) 261 lists all of the arguments and nested blocks supported for this resource type, 262 and also lists a number of attributes that are _exported_ by this resource 263 type. All of these different resource type schema constructs are available 264 for use in references, as follows: 265 266 * The `ami` argument set in the configuration can be used elsewhere with 267 the reference expression `aws_instance.example.ami`. 268 * The `id` attribute exported by this resource type can be read using the 269 same syntax, giving `aws_instance.example.id`. 270 * The arguments of the `ebs_block_device` nested blocks can be accessed using 271 a [splat expression](#splat-expressions). For example, to obtain a list of 272 all of the `device_name` values, use 273 `aws_instance.example.ebs_block_device[*].device_name`. 274 * The nested blocks in this particular resource type do not have any exported 275 attributes, but if `ebs_block_device` were to have a documented `id` 276 attribute then a list of them could be accessed similarly as 277 `aws_instance.example.ebs_block_device[*].id`. 278 * Sometimes nested blocks are defined as taking a logical key to identify each 279 block, which serves a similar purpose as the resource's own name by providing 280 a convenient way to refer to that single block in expressions. If `aws_instance` 281 had a hypothetical nested block type `device` that accepted such a key, it 282 would look like this in configuration: 283 284 ```hcl 285 device "foo" { 286 size = 2 287 } 288 device "bar" { 289 size = 4 290 } 291 ``` 292 293 Arguments inside blocks with _keys_ can be accessed using index syntax, such 294 as `aws_instance.example.device["foo"].size`. 295 296 To obtain a map of values of a particular argument for _labelled_ nested 297 block types, use a [`for` expression](#for-expressions): 298 `{for k, device in aws_instance.example.device : k => device.size}`. 299 300 When a resource has the 301 [`count`](https://www.terraform.io/docs/configuration/resources.html#count-multiple-resource-instances-by-count) 302 argument set, the resource itself becomes a _list_ of instance objects rather than 303 a single object. In that case, access the attributes of the instances using 304 either [splat expressions](#splat-expressions) or index syntax: 305 306 * `aws_instance.example[*].id` returns a list of all of the ids of each of the 307 instances. 308 * `aws_instance.example[0].id` returns just the id of the first instance. 309 310 When a resource has the 311 [`for_each`](/docs/configuration/resources.html#for_each-multiple-resource-instances-defined-by-a-map-or-set-of-strings) 312 argument set, the resource itself becomes a _map_ of instance objects rather than 313 a single object, and attributes of instances must be specified by key, or can 314 be accessed using a [`for` expression](#for-expressions). 315 316 * `aws_instance.example["a"].id` returns the id of the "a"-keyed resource. 317 * `[for value in aws_instance.example: value.id]` returns a list of all of the ids 318 of each of the instances. 319 320 Note that unlike `count`, splat expressions are _not_ directly applicable to resources managed with `for_each`, as splat expressions are for lists only. You may apply a splat expression to values in a map like so: 321 322 * `values(aws_instance.example)[*].id` 323 324 ### Local Named Values 325 326 Within the bodies of certain expressions, or in some other specific contexts, 327 there are other named values available beyond the global values listed above. 328 (For example, the body of a resource block where `count` is set can use a 329 special `count.index` value.) These local names are described in the 330 documentation for the specific contexts where they appear. 331 332 -> **Note:** Local named values are often referred to as _variables_ or 333 _temporary variables_ in their documentation. These are not [input 334 variables](./variables.html); they are just arbitrary names 335 that temporarily represent a value. 336 337 ### Values Not Yet Known 338 339 When Terraform is planning a set of changes that will apply your configuration, 340 some resource attribute values cannot be populated immediately because their 341 values are decided dynamically by the remote system. For example, if a 342 particular remote object type is assigned a generated unique id on creation, 343 Terraform cannot predict the value of this id until the object has been created. 344 345 To allow expressions to still be evaluated during the plan phase, Terraform 346 uses special "unknown value" placeholders for these results. In most cases you 347 don't need to do anything special to deal with these, since the Terraform 348 language automatically handles unknown values during expressions, so that 349 for example adding a known value to an unknown value automatically produces 350 an unknown value as the result. 351 352 However, there are some situations where unknown values _do_ have a significant 353 effect: 354 355 * The `count` meta-argument for resources cannot be unknown, since it must 356 be evaluated during the plan phase to determine how many instances are to 357 be created. 358 359 * If unknown values are used in the configuration of a data resource, that 360 data resource cannot be read during the plan phase and so it will be deferred 361 until the apply phase. In this case, the results of the data resource will 362 _also_ be unknown values. 363 364 * If an unknown value is assigned to an argument inside a `module` block, 365 any references to the corresponding input variable within the child module 366 will use that unknown value. 367 368 * If an unknown value is used in the `value` argument of an output value, 369 any references to that output value in the parent module will use that 370 unknown value. 371 372 * Terraform will attempt to validate that unknown values are of suitable 373 types where possible, but incorrect use of such values may not be detected 374 until the apply phase, causing the apply to fail. 375 376 Unknown values appear in the `terraform plan` output as `(not yet known)`. 377 378 ## Arithmetic and Logical Operators 379 380 An _operator_ is a type of expression that transforms or combines one or more 381 other expressions. Operators either combine two values in some way to 382 produce a third result value, or transform a single given value to 383 produce a single result. 384 385 Operators that work on two values place an operator symbol between the two 386 values, similar to mathematical notation: `1 + 2`. Operators that work on 387 only one value place an operator symbol before that value, like 388 `!true`. 389 390 The Terraform language has a set of operators for both arithmetic and logic, 391 which are similar to operators in programming languages such as JavaScript 392 or Ruby. 393 394 When multiple operators are used together in an expression, they are evaluated 395 in the following order of operations: 396 397 1. `!`, `-` (multiplication by `-1`) 398 1. `*`, `/`, `%` 399 1. `+`, `-` (subtraction) 400 1. `>`, `>=`, `<`, `<=` 401 1. `==`, `!=` 402 1. `&&` 403 1. `||` 404 405 Parentheses can be used to override the default order of operations. Without 406 parentheses, higher levels are evaluated first, so `1 + 2 * 3` is interpreted 407 as `1 + (2 * 3)` and _not_ as `(1 + 2) * 3`. 408 409 The different operators can be gathered into a few different groups with 410 similar behavior, as described below. Each group of operators expects its 411 given values to be of a particular type. Terraform will attempt to convert 412 values to the required type automatically, or will produce an error message 413 if this automatic conversion is not possible. 414 415 ### Arithmetic Operators 416 417 The arithmetic operators all expect number values and produce number values 418 as results: 419 420 * `a + b` returns the result of adding `a` and `b` together. 421 * `a - b` returns the result of subtracting `b` from `a`. 422 * `a * b` returns the result of multiplying `a` and `b`. 423 * `a / b` returns the result of dividing `a` by `b`. 424 * `a % b` returns the remainder of dividing `a` by `b`. This operator is 425 generally useful only when used with whole numbers. 426 * `-a` returns the result of multiplying `a` by `-1`. 427 428 ### Equality Operators 429 430 The equality operators both take two values of any type and produce boolean 431 values as results. 432 433 * `a == b` returns `true` if `a` and `b` both have the same type and the same 434 value, or `false` otherwise. 435 * `a != b` is the opposite of `a == b`. 436 437 ### Comparison Operators 438 439 The comparison operators all expect number values and produce boolean values 440 as results. 441 442 * `a < b` returns `true` if `a` is less than `b`, or `false` otherwise. 443 * `a <= b` returns `true` if `a` is less than or equal to `b`, or `false` 444 otherwise. 445 * `a > b` returns `true` if `a` is greater than `b`, or `false` otherwise. 446 * `a >= b` returns `true` if `a` is greater than or equal to `b`, or `false otherwise. 447 448 ### Logical Operators 449 450 The logical operators all expect bool values and produce bool values as results. 451 452 * `a || b` returns `true` if either `a` or `b` is `true`, or `false` if both are `false`. 453 * `a && b` returns `true` if both `a` and `b` are `true`, or `false` if either one is `false`. 454 * `!a` returns `true` if `a` is `false`, and `false` if `a` is `true`. 455 456 ## Conditional Expressions 457 458 A _conditional expression_ uses the value of a bool expression to select one of 459 two values. 460 461 The syntax of a conditional expression is as follows: 462 463 ```hcl 464 condition ? true_val : false_val 465 ``` 466 467 If `condition` is `true` then the result is `true_val`. If `condition` is 468 `false` then the result is `false_val`. 469 470 A common use of conditional expressions is to define defaults to replace 471 invalid values: 472 473 ``` 474 var.a != "" ? var.a : "default-a" 475 ``` 476 477 If `var.a` is an empty string then the result is `"default-a"`, but otherwise 478 it is the actual value of `var.a`. 479 480 Any of the equality, comparison, and logical operators can be used to define 481 the condition. The two result values may be of any type, but they must both 482 be of the _same_ type so that Terraform can determine what type the whole 483 conditional expression will return without knowing the condition value. 484 485 ## Function Calls 486 487 The Terraform language has a number of 488 [built-in functions](./functions.html) that can be used 489 within expressions as another way to transform and combine values. These 490 are similar to the operators but all follow a common syntax: 491 492 ```hcl 493 <FUNCTION NAME>(<ARGUMENT 1>, <ARGUMENT 2>) 494 ``` 495 496 The function name specifies which function to call. Each defined function 497 expects a specific number of arguments with specific value types, and returns a 498 specific value type as a result. 499 500 Some functions take an arbitrary number of arguments. For example, the `min` 501 function takes any amount of number arguments and returns the one that is 502 numerically smallest: 503 504 ```hcl 505 min(55, 3453, 2) 506 ``` 507 508 ### Expanding Function Arguments 509 510 If the arguments to pass to a function are available in a list or tuple value, 511 that value can be _expanded_ into separate arguments. Provide the list value as 512 an argument and follow it with the `...` symbol: 513 514 ```hcl 515 min([55, 2453, 2]...) 516 ``` 517 518 The expansion symbol is three periods (`...`), not a Unicode ellipsis character 519 (`…`). Expansion is a special syntax that is only available in function calls. 520 521 ### Available Functions 522 523 For a full list of available functions, see 524 [the function reference](./functions.html). 525 526 ## `for` Expressions 527 528 A _`for` expression_ creates a complex type value by transforming 529 another complex type value. Each element in the input value 530 can correspond to either one or zero values in the result, and an arbitrary 531 expression can be used to transform each input element into an output element. 532 533 For example, if `var.list` is a list of strings, then the following expression 534 produces a list of strings with all-uppercase letters: 535 536 ```hcl 537 [for s in var.list : upper(s)] 538 ``` 539 540 This `for` expression iterates over each element of `var.list`, and then 541 evaluates the expression `upper(s)` with `s` set to each respective element. 542 It then builds a new tuple value with all of the results of executing that 543 expression in the same order. 544 545 The type of brackets around the `for` expression decide what type of result 546 it produces. The above example uses `[` and `]`, which produces a tuple. If 547 `{` and `}` are used instead, the result is an object, and two result 548 expressions must be provided separated by the `=>` symbol: 549 550 ```hcl 551 {for s in var.list : s => upper(s)} 552 ``` 553 554 This expression produces an object whose attributes are the original elements 555 from `var.list` and their corresponding values are the uppercase versions. 556 557 A `for` expression can also include an optional `if` clause to filter elements 558 from the source collection, which can produce a value with fewer elements than 559 the source: 560 561 ``` 562 [for s in var.list : upper(s) if s != ""] 563 ``` 564 565 The source value can also be an object or map value, in which case two 566 temporary variable names can be provided to access the keys and values 567 respectively: 568 569 ``` 570 [for k, v in var.map : length(k) + length(v)] 571 ``` 572 573 Finally, if the result type is an object (using `{` and `}` delimiters) then 574 the value result expression can be followed by the `...` symbol to group 575 together results that have a common key: 576 577 ``` 578 {for s in var.list : substr(s, 0, 1) => s... if s != ""} 579 ``` 580 581 ## Splat Expressions 582 583 A _splat expression_ provides a more concise way to express a common 584 operation that could otherwise be performed with a `for` expression. 585 586 If `var.list` is a list of objects that all have an attribute `id`, then 587 a list of the ids could be produced with the following `for` expression: 588 589 ```hcl 590 [for o in var.list : o.id] 591 ``` 592 593 This is equivalent to the following _splat expression:_ 594 595 ```hcl 596 var.list[*].id 597 ``` 598 599 The special `[*]` symbol iterates over all of the elements of the list given 600 to its left and accesses from each one the attribute name given on its 601 right. A splat expression can also be used to access attributes and indexes 602 from lists of complex types by extending the sequence of operations to the 603 right of the symbol: 604 605 ```hcl 606 var.list[*].interfaces[0].name 607 ``` 608 609 The above expression is equivalent to the following `for` expression: 610 611 ```hcl 612 [for o in var.list : o.interfaces[0].name] 613 ``` 614 615 Splat expressions are for lists only (and thus cannot be used [to reference resources 616 created with `for_each`](/docs/configuration/resources.html#referring-to-instances-1), 617 which are represented as maps in Terraform). However, if a splat expression is applied 618 to a value that is _not_ a list or tuple then the value is automatically wrapped in 619 a single-element list before processing. 620 621 For example, `var.single_object[*].id` is equivalent to `[var.single_object][*].id`, 622 or effectively `[var.single_object.id]`. This behavior is not interesting in most cases, 623 but it is particularly useful when referring to resources that may or may 624 not have `count` set, and thus may or may not produce a tuple value: 625 626 ```hcl 627 aws_instance.example[*].id 628 ``` 629 630 The above will produce a list of ids whether `aws_instance.example` has 631 `count` set or not, avoiding the need to revise various other expressions 632 in the configuration when a particular resource switches to and from 633 having `count` set. 634 635 ### Legacy (Attribute-only) Splat Expressions 636 637 An older variant of the splat expression is available for compatibility with 638 code written in older versions of the Terraform language. This is a less useful 639 version of the splat expression, and should be avoided in new configurations. 640 641 An "attribute-only" splat expression is indicated by the sequence `.*` (instead 642 of `[*]`): 643 644 ``` 645 var.list.*.interfaces[0].name 646 ``` 647 648 This form has a subtly different behavior, equivalent to the following 649 `for` expression: 650 651 ``` 652 [for o in var.list : o.interfaces][0].name 653 ``` 654 655 Notice that with the attribute-only splat expression the index operation 656 `[0]` is applied to the result of the iteration, rather than as part of 657 the iteration itself. 658 659 ## `dynamic` blocks 660 661 Within top-level block constructs like resources, expressions can usually be 662 used only when assigning a value to an argument using the `name = expression` 663 form. This covers many uses, but some resource types include repeatable _nested 664 blocks_ in their arguments, which do not accept expressions: 665 666 ```hcl 667 resource "aws_elastic_beanstalk_environment" "tfenvtest" { 668 name = "tf-test-name" # can use expressions here 669 670 setting { 671 # but the "setting" block is always a literal block 672 } 673 } 674 ``` 675 676 You can dynamically construct repeatable nested blocks like `setting` using a 677 special `dynamic` block type, which is supported inside `resource`, `data`, 678 `provider`, and `provisioner` blocks: 679 680 ```hcl 681 resource "aws_elastic_beanstalk_environment" "tfenvtest" { 682 name = "tf-test-name" 683 application = "${aws_elastic_beanstalk_application.tftest.name}" 684 solution_stack_name = "64bit Amazon Linux 2018.03 v2.11.4 running Go 1.12.6" 685 686 dynamic "setting" { 687 for_each = var.settings 688 content { 689 namespace = setting.value["namespace"] 690 name = setting.value["name"] 691 value = setting.value["value"] 692 } 693 } 694 } 695 ``` 696 697 A `dynamic` block acts much like a `for` expression, but produces nested blocks 698 instead of a complex typed value. It iterates over a given complex value, and 699 generates a nested block for each element of that complex value. 700 701 - The label of the dynamic block (`"setting"` in the example above) specifies 702 what kind of nested block to generate. 703 - The `for_each` argument provides the complex value to iterate over. 704 - The `iterator` argument (optional) sets the name of a temporary variable 705 that represents the current element of the complex value. If omitted, the name 706 of the variable defaults to the label of the `dynamic` block (`"setting"` in 707 the example above). 708 - The `labels` argument (optional) is a list of strings that specifies the block 709 labels, in order, to use for each generated block. You can use the temporary 710 iterator variable in this value. 711 - The nested `content` block defines the body of each generated block. You can 712 use the temporary iterator variable inside this block. 713 714 Since the `for_each` argument accepts any collection or structural value, 715 you can use a `for` expression or splat expression to transform an existing 716 collection. 717 718 The iterator object (`setting` in the example above) has two attributes: 719 720 * `key` is the map key or list element index for the current element. If the 721 `for_each` expression produces a _set_ value then `key` is identical to 722 `value` and should not be used. 723 * `value` is the value of the current element. 724 725 A `dynamic` block can only generate arguments that belong to the resource type, 726 data source, provider or provisioner being configured. It is _not_ possible 727 to generate meta-argument blocks such as `lifecycle` and `provisioner` 728 blocks, since Terraform must process these before it is safe to evaluate 729 expressions. 730 731 The `for_each` value must be a map or set with one element per desired 732 nested block. If you need to declare resource instances based on a nested 733 data structure or combinations of elements from multiple data structures you 734 can use Terraform expressions and functions to derive a suitable value. 735 For some common examples of such situations, see the 736 [`flatten`](/docs/configuration/functions/flatten.html) 737 and 738 [`setproduct`](/docs/configuration/functions/setproduct.html) 739 functions. 740 741 ### Best Practices for `dynamic` Blocks 742 743 Overuse of `dynamic` blocks can make configuration hard to read and maintain, so 744 we recommend using them only when you need to hide details in order to build a 745 clean user interface for a re-usable module. Always write nested blocks out 746 literally where possible. 747 748 ## String Literals 749 750 The Terraform language has two different syntaxes for string literals. The 751 most common is to delimit the string with quote characters (`"`), like 752 `"hello"`. In quoted strings, the backslash character serves as an escape 753 sequence, with the following characters selecting the escape behavior: 754 755 | Sequence | Replacement | 756 | ------------ | ----------------------------------------------------------------------------- | 757 | `\n` | Newline | 758 | `\r` | Carriage Return | 759 | `\t` | Tab | 760 | `\"` | Literal quote (without terminating the string) | 761 | `\\` | Literal backslash | 762 | `\uNNNN` | Unicode character from the basic multilingual plane (NNNN is four hex digits) | 763 | `\UNNNNNNNN` | Unicode character from supplementary planes (NNNNNNNN is eight hex digits) | 764 765 The alternative syntax for string literals is the so-called "heredoc" style, 766 inspired by Unix shell languages. This style allows multi-line strings to 767 be expressed more clearly by using a custom delimiter word on a line of its 768 own to close the string: 769 770 ```hcl 771 <<EOT 772 hello 773 world 774 EOT 775 ``` 776 777 The `<<` marker followed by any identifier at the end of a line introduces the 778 sequence. Terraform then processes the following lines until it finds one that 779 consists entirely of the identifier given in the introducer. In the above 780 example, `EOT` is the identifier selected. Any identifier is allowed, but 781 conventionally this identifier is in all-uppercase and begins with `EO`, meaning 782 "end of". `EOT` in this case stands for "end of text". 783 784 The "heredoc" form shown above requires that the lines following be flush with 785 the left margin, which can be awkward when an expression is inside an indented 786 block: 787 788 ```hcl 789 block { 790 value = <<EOT 791 hello 792 world 793 EOT 794 } 795 ``` 796 797 To improve on this, Terraform also accepts an _indented_ heredoc string variant 798 that is introduced by the `<<-` sequence: 799 800 ```hcl 801 block { 802 value = <<-EOT 803 hello 804 world 805 EOT 806 } 807 ``` 808 809 In this case, Terraform analyses the lines in the sequence to find the one 810 with the smallest number of leading spaces, and then trims that many spaces 811 from the beginning of all of the lines, leading to the following result: 812 813 ``` 814 hello 815 world 816 ``` 817 818 Backslash sequences are not interpreted in a heredoc string expression. 819 Instead, the backslash character is interpreted literally. 820 821 In both quoted and heredoc string expressions, Terraform supports template 822 sequences that begin with `${` and `%{`. These are described in more detail 823 in the following section. To include these sequences _literally_ without 824 beginning a template sequence, double the leading character: `$${` or `%%{`. 825 826 ## String Templates 827 828 Within quoted and heredoc string expressions, the sequences `${` and `%{` begin 829 _template sequences_. Templates let you directly embed expressions into a string 830 literal, to dynamically construct strings from other values. 831 832 ### Interpolation 833 834 A `${ ... }` sequence is an _interpolation,_ which evaluates the expression 835 given between the markers, converts the result to a string if necessary, and 836 then inserts it into the final string: 837 838 ```hcl 839 "Hello, ${var.name}!" 840 ``` 841 842 In the above example, the named object `var.name` is accessed and its value 843 inserted into the string, producing a result like "Hello, Juan!". 844 845 ### Directives 846 847 A `%{ ... }` sequence is a _directive_, which allows for conditional 848 results and iteration over collections, similar to conditional 849 and `for` expressions. 850 851 The following directives are supported: 852 853 * The `if <BOOL>`/`else`/`endif` directive chooses between two templates based 854 on the value of a bool expression: 855 856 ```hcl 857 "Hello, %{ if var.name != "" }${var.name}%{ else }unnamed%{ endif }!" 858 ``` 859 860 The `else` portion may be omitted, in which case the result is an empty 861 string if the condition expression returns `false`. 862 863 * The `for <NAME> in <COLLECTION>` / `endfor` directive iterates over the 864 elements of a given collection or structural value and evaluates a given 865 template once for each element, concatenating the results together: 866 867 ```hcl 868 <<EOT 869 %{ for ip in aws_instance.example.*.private_ip } 870 server ${ip} 871 %{ endfor } 872 EOT 873 ``` 874 875 The name given immediately after the `for` keyword is used as a temporary 876 variable name which can then be referenced from the nested template. 877 878 To allow template directives to be formatted for readability without adding 879 unwanted spaces and newlines to the result, all template sequences can include 880 optional _strip markers_ (`~`), immediately after the opening characters or 881 immediately before the end. When a strip marker is present, the template 882 sequence consumes all of the literal whitespace (spaces and newlines) either 883 before the sequence (if the marker appears at the beginning) or after (if the 884 marker appears at the end): 885 886 ```hcl 887 <<EOT 888 %{ for ip in aws_instance.example.*.private_ip ~} 889 server ${ip} 890 %{ endfor ~} 891 EOT 892 ``` 893 894 In the above example, the newline after each of the directives is not included 895 in the output, but the newline after the `server ${ip}` sequence is retained, 896 causing only one line to be generated for each element: 897 898 ``` 899 server 10.1.16.154 900 server 10.1.16.1 901 server 10.1.16.34 902 ``` 903 904 When using template directives, we recommend always using the "heredoc" string 905 literal form and then formatting the template over multiple lines for 906 readability. Quoted string literals should usually include only interpolation 907 sequences.