
Variables can be defined in a variable block. Let's say you have the following files on your Terraform server.
├── locals.tf
├── modules.tf
├── outputs.tf
├── provider.tf
├── terraform.tfstate
├── variables.tf
├── child (directory, child module)
│ ├── data.tf
│ ├── outputs.tf
│ ├── resources.tf
And let's say variables.tf in the same directory as your main root module (main.tf) has the following.
variable "foo" {
type = string
sensitive = false
}
variable "my-string" {
type = string
sensitive = false
default = "Hello"
}
variable "my-integer" {
type = number
sensitive = false
default = 1
}
variable "my-boolean" {
type = bool
sensitive = false
default = true
}
And let's say outputs.tf in the same directory as your main root module (main.tf) has the following. In this example, output blocks are used to output the value of each variable.
output "my-text" {
value = "World"
}
output "my-foo" {
value = var.foo
}
output "string-out" {
value = var.my-string
}
output "integer-out" {
value = var.my-integer
}
output "boolean-out" {
value = var.my-boolean
}
Or, like this.
output "my-foo" {
value = ${var.foo}
}
The terraform refresh, terraform output, terrafrom plan, and terraform apply commands should now all show the output.
terraform refresh
Since the "foo" variable does not have a default value and no value was set, there will be a prompt like this.
var.foo
Enter a value:
Which should return something like this.
string-out = "Hello"
my-foo = "My Value"
my-string = "World"
my-integer = 1
boolean-out = true
Let's say variables.tf in the same directory as your main root module (main.tf) has the following.
variable "username" {
description = "prompt username"
type = string
sensitive = true
}
variable "password" {
description = "prompt password"
type = string
sensitive = true
}
Here is an example of how you could use the username and password variables in a different .tf file as long as the .tf files are in the same directory.
terraform {
required_providers {
rabbitmq = {
source = "cyrilgdn/rabbitmq"
}
}
}
provider "rabbitmq" {
endpoint = "http://rabbit.example.com:15672"
username = var.username
password = var.password
}
You will be prompted for the username and password.
var.username
prompt username
Enter a value:
var.password
prompt password
Enter a value:
The default key can be used if you do not want to be prompted.
variable "username" {
description = "RabbitMQ username"
type = string
sensitive = true
default = "john.doe"
}
variable "password" {
description = "RabbitMQ password"
type = string
sensitive = true
default = "itsasecret"
}
Or the -var command line option can be used.
terraform init -var="profile=my-profile" -var="region=us-east-1"
Did you find this article helpful?
If so, consider buying me a coffee over at