Skip to content

Variables

Variables should be defined in vars.tf.

hcl
variable "myvar" {
    type = "string"
    default ="hello terraform"
}

variable "mymap" {
    type = map(string)
    default = {
        mykey = "myvalue"
        mykey2 = "myvalue2"
    }
}

variable "mylist" {
    type = list
    default = [1,2,3]
}
shell
$ var.myvar
hello terraform
$ ${var.myvar}
hello terraform
$ var.mymap["mykey"]
myvalue
$ var.mylist[0]
1
$ slice(var.mylist, 0, 2)
[
    1,
    2
]

You can also define variables in terraform.tfvars files. Generally you do not want to check this in to version control.

hcl
# In template.tfvars
AWS_REGION="us-central-1"

# In vars.tf
variable "AWS_REGION" {
    type = "string"
}

Outputs

hcl
resource "aws_instance" "example" {
    ami = lookup(var.AMIS, var.AWS_REGION)
    instance_type = "t2.micro"

    # can also be used in scripts
    provisioner "local-exec" {
        command = "echo ${aws_instance.example.private_ip} >> private_ips.txt"
    }
}

output "ip" {
    value = aws_instance.example.public_ip
}