1
votes

I have created the following terraform.tfvars file:

ec2_image = "ami-00035f41c82244dab"
ec2_instance_type = "t2.micro"

And use it as follows in a main.tf file:

resource "aws_instance" "OneServer" {
    ami             =       "${var.ec2_image}"
    instance_type   =       "${var.ec2_instance_type}"
}

Then I execute the 'terraform plan' command and it complains with:

Error: resource 'aws_instance.OneServer' config: unknown variable referenced: 'ec2_image'; define it with a 'variable' block

So I changed the main.tf file as follows:

variable "ec2_image" {}
variable "ec2_instance_type" {}

resource "aws_instance" "OneServer" {
    ami             =       "${var.ec2_image}"
    instance_type   =       "${var.ec2_instance_type}"
}

Then the command 'terraform plan' works OK.

I don't understand why these variable blocks are required. What's the point for it?

1
I know that, looked through it obviously. But where is it mentioned that -when usin tfvars file- the variable block is still required in the tf file. I fully understand that the variable block is required when using tf variable file, but not when a tfvars variable file is used.wiwa1978
I'm not sure I understand your follow up question but the link @MattSchuchard posted explains it. You must define all input variables in the linked syntax (optionally including defaults and/or types) and then if you want you can override/set the values of these by using a number of options including a tfvars file or passing the var through the CLI or using TF_VAR_ environment variables.ydaetskcoR

1 Answers

0
votes

Are you actually using the -var-file command-line switch?

For example, I don't use that switch - I just define my overridable variables in a random tf file (named in my case variable.tf). If the -var-file switch is not used, that means the variable block is required to tell Terraform when a variable is being defined.