# Variables

## Variable types

* string
* number
* bool (true/false)
* list(datatype)
* map(datatype)
* set(datatype)

## Input Variables

* Terraform variables allow you to write configuration that is flexible and easier to re-use.
*   Example to declare a variable in variables file say `variables.tf`:

    ```
    variable "instance_name" {
    description = "Value of the Name tag for the EC2 instance"
    type        = string
    default     = "ExampleAppServerInstance"
    }

    # In .tf configuration file where u need to use the variable make changes using `var.variable_name`

    resource "aws_instance" "app_server" {
        ami = "ami-08d70e59c07c61a3a"
        instance_type = "t2.micro"
        tags = {
            Name = var.instance_name
        }
    }
    ```

> Note: Terraform loads all files in the current directory ending in .tf, so you can name your configuration files however you choose.

* To override the default value of a variable use `-var` flag.

```shell
$ terraform apply -var "instance_name=anotherName"
```

* Setting variables via the command-line will not save their values. Terraform supports many ways to use and set variables so you can avoid having to enter them repeatedly as you execute commands.
* If you do not set a default value for a variable, you must assign a value before Terraform can apply the configuration. **Terraform does not support unassigned variables**.
* You can also store variable values in a file `terraform.tfvars` which is the default file that terrafom looks for when applying configuration, or explicit file location can also be passed using `-var-file file_name.tfvars`.
* To learn more, follow [here](https://learn.hashicorp.com/tutorials/terraform/variables?in=terraform/configuration-language).

## Output Variables

* Create a file called `outputs.tf` in your terraform directory _(i.e in the directory in which your terraform file resides)_.

```
    output "instance_id" {
        description = "ID of the EC2 instance"
        value = aws_instance.app_server.id
    }

    output "instance_public_ip" {
        description = "Public IP address of the EC2 instance"
        value = aws_instance.app_server.public_ip
    }
```

* Refer the command [list](02_terraform_commands) for how to query the output variable.
* To learn more about output variables visit [here](https://learn.hashicorp.com/tutorials/terraform/outputs?in=terraform/configuration-language).
