github.com/rstandt/terraform@v0.12.32-0.20230710220336-b1063613405c/website/docs/configuration/variables.html.md (about) 1 --- 2 layout: "docs" 3 page_title: "Input Variables - Configuration Language" 4 sidebar_current: "docs-config-variables" 5 description: |- 6 Input variables are parameters for Terraform modules. 7 This page covers configuration syntax for variables. 8 --- 9 10 # Input Variables 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: Input Variables](../configuration-0-11/variables.html). 15 16 Input variables serve as parameters for a Terraform module, allowing aspects 17 of the module to be customized without altering the module's own source code, 18 and allowing modules to be shared between different configurations. 19 20 When you declare variables in the root module of your configuration, you can 21 set their values using CLI options and environment variables. 22 When you declare them in [child modules](./modules.html), 23 the calling module should pass values in the `module` block. 24 25 Input variable usage is introduced in the Getting Started guide section 26 [_Input Variables_](https://learn.hashicorp.com/terraform/getting-started/variables). 27 28 -> **Note:** For brevity, input variables are often referred to as just 29 "variables" or "Terraform variables" when it is clear from context what sort of 30 variable is being discussed. Other kinds of variables in Terraform include 31 _environment variables_ (set by the shell where Terraform runs) and _expression 32 variables_ (used to indirectly represent a value in an 33 [expression](./expressions.html)). 34 35 ## Declaring an Input Variable 36 37 Each input variable accepted by a module must be declared using a `variable` 38 block: 39 40 ```hcl 41 variable "image_id" { 42 type = string 43 } 44 45 variable "availability_zone_names" { 46 type = list(string) 47 default = ["us-west-1a"] 48 } 49 50 variable "docker_ports" { 51 type = list(object({ 52 internal = number 53 external = number 54 protocol = string 55 })) 56 default = [ 57 { 58 internal = 8300 59 external = 8300 60 protocol = "tcp" 61 } 62 ] 63 } 64 ``` 65 66 The label after the `variable` keyword is a name for the variable, which must 67 be unique among all variables in the same module. This name is used to 68 assign a value to the variable from outside and to reference the variable's 69 value from within the module. 70 71 The name of a variable can be any valid [identifier](./syntax.html#identifiers) 72 _except_ the following: 73 74 - `source` 75 - `version` 76 - `providers` 77 - `count` 78 - `for_each` 79 - `lifecycle` 80 - `depends_on` 81 - `locals` 82 83 These names are reserved for meta-arguments in 84 [module configuration blocks](./modules.html), and cannot be 85 declared as variable names. 86 87 The variable declaration can optionally include a `type` argument to 88 specify what value types are accepted for the variable, as described 89 in the following section. 90 91 The variable declaration can also include a `default` argument. If present, 92 the variable is considered to be _optional_ and the default value will be used 93 if no value is set when calling the module or running Terraform. The `default` 94 argument requires a literal value and cannot reference other objects in the 95 configuration. 96 97 ## Using Input Variable Values 98 99 Within the module that declared a variable, its value can be accessed from 100 within [expressions](./expressions.html) as `var.<NAME>`, 101 where `<NAME>` matches the label given in the declaration block: 102 103 ```hcl 104 resource "aws_instance" "example" { 105 instance_type = "t2.micro" 106 ami = var.image_id 107 } 108 ``` 109 110 The value assigned to a variable can be accessed only from expressions within 111 the module where it was declared. 112 113 ## Type Constraints 114 115 The `type` argument in a `variable` block allows you to restrict the 116 [type of value](./expressions.html#types-and-values) that will be accepted as 117 the value for a variable. If no type constraint is set then a value of any type 118 is accepted. 119 120 While type constraints are optional, we recommend specifying them; they 121 serve as easy reminders for users of the module, and 122 allow Terraform to return a helpful error message if the wrong type is used. 123 124 Type constraints are created from a mixture of type keywords and type 125 constructors. The supported type keywords are: 126 127 * `string` 128 * `number` 129 * `bool` 130 131 The type constructors allow you to specify complex types such as 132 collections: 133 134 * `list(<TYPE>)` 135 * `set(<TYPE>)` 136 * `map(<TYPE>)` 137 * `object({<ATTR NAME> = <TYPE>, ... })` 138 * `tuple([<TYPE>, ...])` 139 140 The keyword `any` may be used to indicate that any type is acceptable. For 141 more information on the meaning and behavior of these different types, as well 142 as detailed information about automatic conversion of complex types, see 143 [Type Constraints](./types.html). 144 145 If both the `type` and `default` arguments are specified, the given default 146 value must be convertible to the specified type. 147 148 ## Input Variable Documentation 149 150 Because the input variables of a module are part of its user interface, you can 151 briefly describe the purpose of each variable using the optional 152 `description` argument: 153 154 ```hcl 155 variable "image_id" { 156 type = string 157 description = "The id of the machine image (AMI) to use for the server." 158 } 159 ``` 160 161 The description should concisely explain the purpose 162 of the variable and what kind of value is expected. This description string 163 might be included in documentation about the module, and so it should be written 164 from the perspective of the user of the module rather than its maintainer. For 165 commentary for module maintainers, use comments. 166 167 ## Custom Validation Rules 168 169 ~> *Warning:* This feature is currently experimental and is subject to breaking 170 changes even in minor releases. We welcome your feedback, but cannot 171 recommend using this feature in production modules yet. 172 173 In addition to Type Constraints as described above, a module author can specify 174 arbitrary custom validation rules for a particular variable using a `validation` 175 block nested within the corresponding `variable` block: 176 177 ```hcl 178 variable "image_id" { 179 type = string 180 description = "The id of the machine image (AMI) to use for the server." 181 182 validation { 183 condition = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-" 184 error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"." 185 } 186 } 187 ``` 188 189 The `condition` argument is an expression that must use the value of the 190 variable to return `true` if the value is valid, or `false` if it is invalid. 191 The expression can refer only to the variable that the condition applies to, 192 and _must not_ produce errors. 193 194 If the failure of an expression is the basis of the validation decision, use 195 [the `can` function](./functions/can.html) to detect such errors. For example: 196 197 ```hcl 198 variable "image_id" { 199 type = string 200 description = "The id of the machine image (AMI) to use for the server." 201 202 validation { 203 # regex(...) fails if it cannot find a match 204 condition = can(regex("^ami-", var.image_id)) 205 error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"." 206 } 207 } 208 ``` 209 210 If `condition` evaluates to `false`, Terraform will produce an error message 211 that includes the sentences given in `error_message`. The error message string 212 should be at least one full sentence explaining the constraint that failed, 213 using a sentence structure similar to the above examples. 214 215 This is [an experimental language feature](./terraform.html#experimental-language-features) 216 that currently requires an explicit opt-in using the experiment keyword 217 `variable_validation`: 218 219 ```hcl 220 terraform { 221 experiments = [variable_validation] 222 } 223 ``` 224 225 ## Assigning Values to Root Module Variables 226 227 When variables are declared in the root module of your configuration, they 228 can be set in a number of ways: 229 230 * [In a Terraform Cloud workspace](/docs/cloud/workspaces/variables.html). 231 * Individually, with the `-var` command line option. 232 * In variable definitions (`.tfvars`) files, either specified on the command line 233 or automatically loaded. 234 * As environment variables. 235 236 The following sections describe these options in more detail. This section does 237 not apply to _child_ modules, where values for input variables are instead 238 assigned in the configuration of their parent module, as described in 239 [_Modules_](./modules.html). 240 241 ### Variables on the Command Line 242 243 To specify individual variables on the command line, use the `-var` option 244 when running the `terraform plan` and `terraform apply` commands: 245 246 ``` 247 terraform apply -var="image_id=ami-abc123" 248 terraform apply -var='image_id_list=["ami-abc123","ami-def456"]' 249 terraform apply -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def456"}' 250 ``` 251 252 The `-var` option can be used any number of times in a single command. 253 254 ### Variable Definitions (`.tfvars`) Files 255 256 To set lots of variables, it is more convenient to specify their values in 257 a _variable definitions file_ (with a filename ending in either `.tfvars` 258 or `.tfvars.json`) and then specify that file on the command line with 259 `-var-file`: 260 261 ``` 262 terraform apply -var-file="testing.tfvars" 263 ``` 264 265 -> **Note:** This is how Terraform Cloud passes 266 [workspace variables](/docs/cloud/workspaces/variables.html) to Terraform. 267 268 A variable definitions file uses the same basic syntax as Terraform language 269 files, but consists only of variable name assignments: 270 271 ```hcl 272 image_id = "ami-abc123" 273 availability_zone_names = [ 274 "us-east-1a", 275 "us-west-1c", 276 ] 277 ``` 278 279 Terraform also automatically loads a number of variable definitions files 280 if they are present: 281 282 * Files named exactly `terraform.tfvars` or `terraform.tfvars.json`. 283 * Any files with names ending in `.auto.tfvars` or `.auto.tfvars.json`. 284 285 Files whose names end with `.json` are parsed instead as JSON objects, with 286 the root object properties corresponding to variable names: 287 288 ```json 289 { 290 "image_id": "ami-abc123", 291 "availability_zone_names": ["us-west-1a", "us-west-1c"] 292 } 293 ``` 294 295 ### Environment Variables 296 297 As a fallback for the other ways of defining variables, Terraform searches 298 the environment of its own process for environment variables named `TF_VAR_` 299 followed by the name of a declared variable. 300 301 This can be useful when running Terraform in automation, or when running a 302 sequence of Terraform commands in succession with the same variables. 303 For example, at a `bash` prompt on a Unix system: 304 305 ``` 306 $ export TF_VAR_image_id=ami-abc123 307 $ terraform plan 308 ... 309 ``` 310 311 On operating systems where environment variable names are case-sensitive, 312 Terraform matches the variable name exactly as given in configuration, and 313 so the required environment variable name will usually have a mix of upper 314 and lower case letters as in the above example. 315 316 ### Complex-typed Values 317 318 When variable values are provided in a variable definitions file, Terraform's 319 [usual syntax](./expressions.html#structural-types) can be used to assign 320 complex-typed values, like lists and maps. 321 322 Some special rules apply to the `-var` command line option and to environment 323 variables. For convenience, Terraform defaults to interpreting `-var` and 324 environment variable values as literal strings, which do not need to be quoted: 325 326 ``` 327 $ export TF_VAR_image_id=ami-abc123 328 ``` 329 330 However, if a root module variable uses a [type constraint](#type-constraints) 331 to require a complex value (list, set, map, object, or tuple), Terraform will 332 instead attempt to parse its value using the same syntax used within variable 333 definitions files, which requires careful attention to the string escaping rules 334 in your shell: 335 336 ``` 337 $ export TF_VAR_availability_zone_names='["us-west-1b","us-west-1d"]' 338 ``` 339 340 For readability, and to avoid the need to worry about shell escaping, we 341 recommend always setting complex variable values via variable definitions files. 342 343 ### Variable Definition Precedence 344 345 The above mechanisms for setting variables can be used together in any 346 combination. If the same variable is assigned multiple values, Terraform uses 347 the _last_ value it finds, overriding any previous values. Note that the same 348 variable cannot be assigned multiple values within a single source. 349 350 Terraform loads variables in the following order, with later sources taking 351 precedence over earlier ones: 352 353 * Environment variables 354 * The `terraform.tfvars` file, if present. 355 * The `terraform.tfvars.json` file, if present. 356 * Any `*.auto.tfvars` or `*.auto.tfvars.json` files, processed in lexical order 357 of their filenames. 358 * Any `-var` and `-var-file` options on the command line, in the order they 359 are provided. (This includes variables set by a Terraform Cloud 360 workspace.) 361 362 ~> **Important:** In Terraform 0.12 and later, variables with map and object 363 values behave the same way as other variables: the last value found overrides 364 the previous values. This is a change from previous versions of Terraform, which 365 would _merge_ map values instead of overriding them.