github.com/eliastor/durgaform@v0.0.0-20220816172711-d0ab2d17673e/website/docs/language/values/variables.mdx (about)

     1  ---
     2  page_title: Input Variables - Configuration Language
     3  description: >-
     4    Input variables allow you to customize modules without altering their source
     5    code. Learn how to declare, define, and reference variables in configurations.
     6  ---
     7  
     8  # Input Variables
     9  
    10  > **Hands-on:** Try the [Customize Terraform Configuration with Variables](https://learn.hashicorp.com/tutorials/terraform/variables?in=terraform/configuration-language&utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS) tutorial on HashiCorp Learn.
    11  
    12  Input variables let you customize aspects of Terraform modules without altering
    13  the module's own source code. This allows you to share modules across different
    14  Terraform configurations, making your module composable and reusable.
    15  
    16  When you declare variables in the root module of your configuration, you can
    17  set their values using CLI options and environment variables.
    18  When you declare them in [child modules](/language/modules),
    19  the calling module should pass values in the `module` block.
    20  
    21  If you're familiar with traditional programming languages, it can be useful to
    22  compare Terraform modules to function definitions:
    23  
    24  * Input variables are like function arguments.
    25  * [Output values](/language/values/outputs) are like function return values.
    26  * [Local values](/language/values/locals) are like a function's temporary local 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](/language/expressions)).
    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](/language/syntax/configuration#identifiers)
    72  _except_ the following: `source`, `version`, `providers`, `count`, `for_each`, `lifecycle`, `depends_on`, `locals`.
    73  
    74  These names are reserved for meta-arguments in
    75  [module configuration blocks](/language/modules/syntax), and cannot be
    76  declared as variable names.
    77  
    78  ## Arguments
    79  
    80  Terraform CLI defines the following optional arguments for variable declarations:
    81  
    82  * [`default`][inpage-default] - A default value which then makes the variable optional.
    83  * [`type`][inpage-type] - This argument specifies what value types are accepted for the variable.
    84  * [`description`][inpage-description] - This specifies the input variable's documentation.
    85  * [`validation`][inpage-validation] - A block to define validation rules, usually in addition to type constraints.
    86  * [`sensitive`][inpage-sensitive] - Limits Terraform UI output when the variable is used in configuration.
    87  * [`nullable`][inpage-nullable] - Specify if the variable can be `null` within the module.
    88  
    89  ### Default values
    90  
    91  [inpage-default]: #default-values
    92  
    93  The variable declaration can also include a `default` argument. If present,
    94  the variable is considered to be _optional_ and the default value will be used
    95  if no value is set when calling the module or running Terraform. The `default`
    96  argument requires a literal value and cannot reference other objects in the
    97  configuration.
    98  
    99  ### Type Constraints
   100  
   101  [inpage-type]: #type-constraints
   102  
   103  The `type` argument in a `variable` block allows you to restrict the
   104  [type of value](/language/expressions/types) that will be accepted as
   105  the value for a variable. If no type constraint is set then a value of any type
   106  is accepted.
   107  
   108  While type constraints are optional, we recommend specifying them; they
   109  can serve as helpful reminders for users of the module, and they
   110  allow Terraform to return a helpful error message if the wrong type is used.
   111  
   112  Type constraints are created from a mixture of type keywords and type
   113  constructors. The supported type keywords are:
   114  
   115  * `string`
   116  * `number`
   117  * `bool`
   118  
   119  The type constructors allow you to specify complex types such as
   120  collections:
   121  
   122  * `list(<TYPE>)`
   123  * `set(<TYPE>)`
   124  * `map(<TYPE>)`
   125  * `object({<ATTR NAME> = <TYPE>, ... })`
   126  * `tuple([<TYPE>, ...])`
   127  
   128  The keyword `any` may be used to indicate that any type is acceptable. For
   129  more information on the meaning and behavior of these different types, as well
   130  as detailed information about automatic conversion of complex types, see
   131  [Type Constraints](/language/expressions/types).
   132  
   133  If both the `type` and `default` arguments are specified, the given default
   134  value must be convertible to the specified type.
   135  
   136  ### Input Variable Documentation
   137  
   138  [inpage-description]: #input-variable-documentation
   139  
   140  Because the input variables of a module are part of its user interface, you can
   141  briefly describe the purpose of each variable using the optional
   142  `description` argument:
   143  
   144  ```hcl
   145  variable "image_id" {
   146    type        = string
   147    description = "The id of the machine image (AMI) to use for the server."
   148  }
   149  ```
   150  
   151  The description should concisely explain the purpose
   152  of the variable and what kind of value is expected. This description string
   153  might be included in documentation about the module, and so it should be written
   154  from the perspective of the user of the module rather than its maintainer. For
   155  commentary for module maintainers, use comments.
   156  
   157  ### Custom Validation Rules
   158  
   159  [inpage-validation]: #custom-validation-rules
   160  
   161  -> This feature was introduced in Terraform CLI v0.13.0.
   162  
   163  You can specify custom validation rules for a particular variable by adding a `validation` block within the corresponding `variable` block. The example below checks whether the AMI ID has the correct syntax.
   164  
   165  ```hcl
   166  variable "image_id" {
   167    type        = string
   168    description = "The id of the machine image (AMI) to use for the server."
   169  
   170    validation {
   171      condition     = length(var.image_id) > 4 && substr(var.image_id, 0, 4) == "ami-"
   172      error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
   173    }
   174  }
   175  ```
   176  Refer to [Custom Condition Checks](/language/expressions/custom-conditions#input-variable-validation) for more details.
   177  
   178  ### Suppressing Values in CLI Output
   179  
   180  [inpage-sensitive]: #suppressing-values-in-cli-output
   181  
   182  -> This feature was introduced in Terraform v0.14.0.
   183  
   184  > **Hands-on:** Try the [Protect Sensitive Input Variables](https://learn.hashicorp.com/tutorials/terraform/sensitive-variables?in=terraform/configuration-language&utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS) tutorial on HashiCorp Learn.
   185  
   186  Setting a variable as `sensitive` prevents Terraform from showing its value in
   187  the `plan` or `apply` output, when you use that variable elsewhere in your
   188  configuration.
   189  
   190  Terraform will still record sensitive values in the [state](/language/state),
   191  and so anyone who can access the state data will have access to the sensitive
   192  values in cleartext. For more information, see
   193  [_Sensitive Data in State_](/language/state/sensitive-data).
   194  
   195  Declare a variable as sensitive by setting the `sensitive` argument to `true`:
   196  
   197  ```hcl
   198  variable "user_information" {
   199    type = object({
   200      name    = string
   201      address = string
   202    })
   203    sensitive = true
   204  }
   205  
   206  resource "some_resource" "a" {
   207    name    = var.user_information.name
   208    address = var.user_information.address
   209  }
   210  ```
   211  
   212  Any expressions whose result depends on the sensitive variable will be treated
   213  as sensitive themselves, and so in the above example the two arguments of
   214  `resource "some_resource" "a"` will also be hidden in the plan output:
   215  
   216  ```
   217  Terraform will perform the following actions:
   218  
   219    # some_resource.a will be created
   220    + resource "some_resource" "a" {
   221        + name    = (sensitive)
   222        + address = (sensitive)
   223      }
   224  
   225  Plan: 1 to add, 0 to change, 0 to destroy.
   226  ```
   227  
   228  In some cases where you use a sensitive variable inside a nested block, Terraform
   229  may treat the entire block as redacted. This happens for resource types where
   230  all of the blocks of a particular type are required to be unique, and so
   231  disclosing the content of one block might imply the content of a sibling block.
   232  
   233  ```
   234    # some_resource.a will be updated in-place
   235    ~ resource "some_resource" "a" {
   236        ~ nested_block {
   237            # At least one attribute in this block is (or was) sensitive,
   238            # so its contents will not be displayed.
   239          }
   240      }
   241  ```
   242  
   243  A provider can also
   244  [declare an attribute as sensitive](/plugin/sdkv2/best-practices/sensitive-state#using-the-sensitive-flag),
   245  which will cause Terraform to hide it from regular output regardless of how
   246  you assign it a value. For more information, see
   247  [Sensitive Resource Attributes](/language/expressions/references#sensitive-resource-attributes).
   248  
   249  If you use a sensitive value as part of an
   250  [output value](/language/values/outputs) then Terraform will require
   251  you to also mark the output value itself as sensitive, to confirm that you
   252  intended to export it.
   253  
   254  #### Cases where Terraform may disclose a sensitive variable
   255  
   256  A `sensitive` variable is a configuration-centered concept, and values are sent to providers without any obfuscation. A provider error could disclose a value if that value is included in the error message. For example, a provider might return the following error even if "foo" is a sensitive value: `"Invalid value 'foo' for field"`
   257  
   258  If a resource attribute is used as, or part of, the provider-defined resource id, an `apply` will disclose the value. In the example below, the `prefix` attribute has been set to a sensitive variable, but then that value ("jae") is later disclosed as part of the resource id:
   259  
   260  ```
   261    # random_pet.animal will be created
   262    + resource "random_pet" "animal" {
   263        + id        = (known after apply)
   264        + length    = 2
   265        + prefix    = (sensitive)
   266        + separator = "-"
   267      }
   268  
   269  Plan: 1 to add, 0 to change, 0 to destroy.
   270  
   271  ...
   272  
   273  random_pet.animal: Creating...
   274  random_pet.animal: Creation complete after 0s [id=jae-known-mongoose]
   275  ```
   276  
   277  ### Disallowing Null Input Values
   278  
   279  [inpage-nullable]: #disallowing-null-input-values
   280  
   281  -> This feature is available in Terraform v1.1.0 and later.
   282  
   283  The `nullable` argument in a variable block controls whether the module caller
   284  may assign the value `null` to the variable.
   285  
   286  ```hcl
   287  variable "example" {
   288    type     = string
   289    nullable = false
   290  }
   291  ```
   292  
   293  The default value for `nullable` is `true`. When `nullable` is `true`, `null`
   294  is a valid value for the variable, and the module configuration must always
   295  account for the possibility of the variable value being `null`. Passing a
   296  `null` value as a module input argument will override any `default` value.
   297  
   298  Setting `nullable` to `false` ensures that the variable value will never be
   299  `null` within the module. If `nullable` is `false` and the variable has a
   300  `default` value, then Terraform uses the default when a module input argument is `null`.
   301  
   302  The `nullable` argument only controls where the direct value of the variable may be `null`.
   303  For variables of collection or structural types, such as lists or objects,
   304  the caller may still use `null` in nested elements or attributes, as long as
   305  the collection or structure itself is not null.
   306  
   307  ## Using Input Variable Values
   308  
   309  Within the module that declared a variable, its value can be accessed from
   310  within [expressions](/language/expressions) as `var.<NAME>`,
   311  where `<NAME>` matches the label given in the declaration block:
   312  
   313  -> **Note:** Input variables are _created_ by a `variable` block, but you
   314  _reference_ them as attributes on an object named `var`.
   315  
   316  ```hcl
   317  resource "aws_instance" "example" {
   318    instance_type = "t2.micro"
   319    ami           = var.image_id
   320  }
   321  ```
   322  
   323  The value assigned to a variable can only be accessed in expressions within
   324  the module where it was declared.
   325  
   326  ## Assigning Values to Root Module Variables
   327  
   328  When variables are declared in the root module of your configuration, they
   329  can be set in a number of ways:
   330  
   331  * [In a Terraform Cloud workspace](/cloud-docs/workspaces/variables).
   332  * Individually, with the `-var` command line option.
   333  * In variable definitions (`.tfvars`) files, either specified on the command line
   334    or automatically loaded.
   335  * As environment variables.
   336  
   337  The following sections describe these options in more detail. This section does
   338  not apply to _child_ modules, where values for input variables are instead
   339  assigned in the configuration of their parent module, as described in
   340  [_Modules_](/language/modules).
   341  
   342  ### Variables on the Command Line
   343  
   344  To specify individual variables on the command line, use the `-var` option
   345  when running the `terraform plan` and `terraform apply` commands:
   346  
   347  ```
   348  terraform apply -var="image_id=ami-abc123"
   349  terraform apply -var='image_id_list=["ami-abc123","ami-def456"]' -var="instance_type=t2.micro"
   350  terraform apply -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def456"}'
   351  ```
   352  
   353  The above examples show appropriate syntax for Unix-style shells, such as on
   354  Linux or macOS. For more information on shell quoting, including additional
   355  examples for Windows Command Prompt, see
   356  [Input Variables on the Command Line](/cli/commands/plan#input-variables-on-the-command-line).
   357  
   358  You can use the `-var` option multiple times in a single command to set several
   359  different variables.
   360  
   361  <a id="variable-files"></a>
   362  
   363  ### Variable Definitions (`.tfvars`) Files
   364  
   365  To set lots of variables, it is more convenient to specify their values in
   366  a _variable definitions file_ (with a filename ending in either `.tfvars`
   367  or `.tfvars.json`) and then specify that file on the command line with
   368  `-var-file`:
   369  
   370  ```
   371  terraform apply -var-file="testing.tfvars"
   372  ```
   373  
   374  -> **Note:** This is how Terraform Cloud passes
   375  [workspace variables](/cloud-docs/workspaces/variables) to Terraform.
   376  
   377  A variable definitions file uses the same basic syntax as Terraform language
   378  files, but consists only of variable name assignments:
   379  
   380  ```hcl
   381  image_id = "ami-abc123"
   382  availability_zone_names = [
   383    "us-east-1a",
   384    "us-west-1c",
   385  ]
   386  ```
   387  
   388  Terraform also automatically loads a number of variable definitions files
   389  if they are present:
   390  
   391  * Files named exactly `terraform.tfvars` or `terraform.tfvars.json`.
   392  * Any files with names ending in `.auto.tfvars` or `.auto.tfvars.json`.
   393  
   394  Files whose names end with `.json` are parsed instead as JSON objects, with
   395  the root object properties corresponding to variable names:
   396  
   397  ```json
   398  {
   399    "image_id": "ami-abc123",
   400    "availability_zone_names": ["us-west-1a", "us-west-1c"]
   401  }
   402  ```
   403  
   404  ### Environment Variables
   405  
   406  As a fallback for the other ways of defining variables, Terraform searches
   407  the environment of its own process for environment variables named `TF_VAR_`
   408  followed by the name of a declared variable.
   409  
   410  This can be useful when running Terraform in automation, or when running a
   411  sequence of Terraform commands in succession with the same variables.
   412  For example, at a `bash` prompt on a Unix system:
   413  
   414  ```
   415  $ export TF_VAR_image_id=ami-abc123
   416  $ terraform plan
   417  ...
   418  ```
   419  
   420  On operating systems where environment variable names are case-sensitive,
   421  Terraform matches the variable name exactly as given in configuration, and
   422  so the required environment variable name will usually have a mix of upper
   423  and lower case letters as in the above example.
   424  
   425  ### Complex-typed Values
   426  
   427  When variable values are provided in a variable definitions file, you can use
   428  Terraform's usual syntax for
   429  [literal expressions](/language/expressions/types#literal-expressions)
   430  to assign complex-typed values, like lists and maps.
   431  
   432  Some special rules apply to the `-var` command line option and to environment
   433  variables. For convenience, Terraform defaults to interpreting `-var` and
   434  environment variable values as literal strings, which need only shell quoting,
   435  and no special quoting for Terraform. For example, in a Unix-style shell:
   436  
   437  ```
   438  $ export TF_VAR_image_id='ami-abc123'
   439  ```
   440  
   441  However, if a root module variable uses a [type constraint](#type-constraints)
   442  to require a complex value (list, set, map, object, or tuple), Terraform will
   443  instead attempt to parse its value using the same syntax used within variable
   444  definitions files, which requires careful attention to the string escaping rules
   445  in your shell:
   446  
   447  ```
   448  $ export TF_VAR_availability_zone_names='["us-west-1b","us-west-1d"]'
   449  ```
   450  
   451  For readability, and to avoid the need to worry about shell escaping, we
   452  recommend always setting complex variable values via variable definitions files.
   453  For more information on quoting and escaping for `-var` arguments,
   454  see
   455  [Input Variables on the Command Line](/cli/commands/plan#input-variables-on-the-command-line).
   456  
   457  ### Values for Undeclared Variables
   458  
   459  If you have defined a variable value, but not its corresponding `variable {}`
   460  definition, you may get an error or warning depending on how you have provided
   461  that value.
   462  
   463  If you provide values for undeclared variables defined as [environment variables](#environment-variables)
   464  you will not get an error or warning. This is because environment variables may
   465  be declared but not used in all configurations that might be run.
   466  
   467  If you provide values for undeclared variables defined [in a file](#variable-definitions-tfvars-files)
   468  you will get a warning. This is to help in cases where you have provided a variable
   469  value _meant_ for a variable declaration, but perhaps there is a mistake in the
   470  value definition. For example, the following configuration:
   471  
   472  ```terraform
   473  variable "moose" {
   474    type = string
   475  }
   476  ```
   477  
   478  And the following `.tfvars` file:
   479  
   480  ```hcl
   481  mosse = "Moose"
   482  ```
   483  
   484  Will cause Terraform to warn you that there is no variable declared `"mosse"`, which can help
   485  you spot this mistake.
   486  
   487  If you use `.tfvars` files across multiple configurations and expect to continue to see this warning,
   488  you can use the [`-compact-warnings`](/cli/commands/plan#compact-warnings)
   489  option to simplify your output.
   490  
   491  If you provide values for undeclared variables on the [command line](#variables-on-the-command-line),
   492  Terraform will error. To avoid this error, either declare a variable block for the value, or remove
   493  the variable value from your Terraform call.
   494  
   495  ### Variable Definition Precedence
   496  
   497  The above mechanisms for setting variables can be used together in any
   498  combination. If the same variable is assigned multiple values, Terraform uses
   499  the _last_ value it finds, overriding any previous values. Note that the same
   500  variable cannot be assigned multiple values within a single source.
   501  
   502  Terraform loads variables in the following order, with later sources taking
   503  precedence over earlier ones:
   504  
   505  * Environment variables
   506  * The `terraform.tfvars` file, if present.
   507  * The `terraform.tfvars.json` file, if present.
   508  * Any `*.auto.tfvars` or `*.auto.tfvars.json` files, processed in lexical order
   509    of their filenames.
   510  * Any `-var` and `-var-file` options on the command line, in the order they
   511    are provided. (This includes variables set by a Terraform Cloud
   512    workspace.)
   513  
   514  ~> **Important:** In Terraform 0.12 and later, variables with map and object
   515  values behave the same way as other variables: the last value found overrides
   516  the previous values. This is a change from previous versions of Terraform, which
   517  would _merge_ map values instead of overriding them.