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