# 9. Terraform Variables

### Input Variables

We can define input variables in the config file as follows

```hcl
variable "subnet_prefix" {
  description = "cidr block for the subnet"
  default = "10.0.2.0/24"
  type = string
}
```

* Accessed as `var.<name>`
* `default` value like name suggests is the default value when we don't assign any value to it
* `type = any` means any data type is accepted
  * We can also use lists type or list of objects

#### Usage

Order of precedence // lowest -> highest

1. If we dont specify any value, it will ask us for input while running `terraform apply`.
2. Second is the default value in declaration block
3. `TF_VAR_<name>` environment variable
4. Best way is to use a seperate file for variables with name `terraform.tfvars`
   * We can assign values in that file like
   * ```hcl
     subnet_prefix = "10.0.1.0/24"
     avail_zone = "eu-west-1"
     ```
   * If you want to use other file like `example.tfvars`, you have to specify it while applying config like `terraform apply -var-file example.tfvars`
5. `*.auto.tfvars` file
6. Command line arguments to enter the value of the variables like `terraform apply -var "subnet_prefix=10.0.1.0/24"` or `-var-file`

***

### Local Variables

We can define local variables in the config file as follows

```hcl
locals {
  service_name = "My Service"
  owner = "NomanAziz"
}
```

* Can be accessed as `local.<name>`
* Temporary variables within the scope of the function

***

### [Output Variables](https://notes.nomanaziz.me/devops/infrastructure-as-a-code-iac/terraform/7.-terraform-output)

***

### Types

#### Primitive Types

1. string
2. number
3. bool

#### Complex Types

1. `list(<TYPE>)`
2. `set(<TYPE>)`
3. `map(<TYPE>)`
4. `object({ <ATTR NAME> = <TYPE>, ... })`
5. `tuple([<TYPE>, ...])`

***

### Sensitive Data

#### Mark variables as sensitive

```tf
sensitive=true
```

#### Pass to terraform apply with

* `TV_VAR_variable`
* `-var` (retrieved from secret manager at runtime)

#### Can also use external secret store

* AWS Secrets manager

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.nomanaziz.me/devops/infrastructure-as-a-code-iac/terraform/9.-terraform-variables.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
