Joey Yi Zhao
Joey Yi Zhao

Reputation: 42518

How can I reference a variable in `main.tf`?

I have two terraform files main.tf and var.tfvars:

main.tf:

provider "google" {
  project = var.project_id
  region  = var.gcp_region
}

provider "aws" {
  region = var.aws_region
    alias = "aws"
}

vars.tfvars:

variable "gcp_region" {
    type = string
    default = "asia-southeast1"
}

variable "aws_region" {
    type = string
    default = "ap-southeast-2"
}

variable "project_id" {
    type = string
    default = "test-oidc-arosha"
}

when I run terraform apply, I got below error:

Error: Reference to undeclared input variable
│
│   on local.tf line 6, in locals:
│    6:     state_backet = "${local.component_name}-${local.part_name}-deployment-${var.aws_region}-${data.aws_caller_identity.current.account_id}"
│
│ An input variable with the name "aws_region" has not been declared. This variable can be declared
│ with a variable "aws_region" {} block.
╵
╷
│ Error: Reference to undeclared input variable
│
│   on main.tf line 2, in provider "google":
│    2:   project = var.project_id
│
│ An input variable with the name "project_id" has not been declared. This variable can be declared
│ with a variable "project_id" {} block.
╵
╷
│ Error: Reference to undeclared input variable
│
│   on main.tf line 3, in provider "google":
│    3:   region  = var.gcp_region
│
│ An input variable with the name "gcp_region" has not been declared. This variable can be declared
│ with a variable "gcp_region" {} block.

I don't understand why I got this error even I already specified the default values for each variable.

My terraform version is:

$ terraform --version
Terraform v1.0.0
on darwin_amd64
+ provider registry.terraform.io/hashicorp/aws v3.45.0
+ provider registry.terraform.io/hashicorp/google v3.72.0

Upvotes: 1

Views: 6832

Answers (2)

LazyEval
LazyEval

Reputation: 859

Change the name of you vars.tfvars file to variables.tf and it should pick up the default value. .tfvars files are for inputs to variables which are in turn defined in the variables.tf file (or any .tf file actually, doesn't matter what you call it.)

Upvotes: 3

Jatin Mehrotra
Jatin Mehrotra

Reputation: 11548

you need to add variable definition to your main.tf and then use your variable in var.tf approapriately

example

 variable "aws_region" {
    type = string
    default = "ap-southeast-2"
}

var.tfvars

example

aws_region = {
    Name = "created by jatin/terraform",
    instance_type="t2.micro"
}

Upvotes: 1

Related Questions