ha9u63a7
ha9u63a7

Reputation: 6824

Terraform - Variable defined in "*.auto.tfvars" file, but still cannot be discovered

I have the following directory Structure:

.
├── ./first_terraform.tf
├── ./modules
│   └── ./modules/ssh_keys
│       ├── ./modules/ssh_keys/main.tf
│       ├── ./modules/ssh_keys/outputs.tf
│       └── ./modules/ssh_keys/variables.tf
├── ./terraform.auto.tfvars
├── ./variables.tf

I am trying to pass a variable ssh_key to my child module defined as main.tf inside ./modules/ssh_keys/main.tf

resource "aws_key_pair" "id_rsa_ec2" {
  key_name   = "id_rsa_ec2"
  public_key = file(var.ssh_key)
}

I also have this variable defined both at root and child level variables.tf file. For the value, I have set it in terraform.auto.tfvars as below

# SSH Key
ssh_key = "~/.ssh/haha_key.pub"

I also have a variable defined in root level and child level variables.tf file:

variable "ssh_key" {
  type        = string
  description = "ssh key for EC2 login and checks"
}

My root terraform configuration has this module declared as:

module "ssh_keys" {
  source = "./modules/ssh_keys"
}

I first did a terraform init -upgrade on my root level. Then ran terraform refresh and got hit by the following error.

Error: Missing required argument

  on first_terraform.tf line 69, in module "ssh_keys":
  69: module "ssh_keys" {

The argument "ssh_key" is required, but no definition was found.

Just for reference, line 69 in my root level configuration is where the module declaration has been made. I don't know what I have done wrong here. It seems I have all the variables declared, so am I missing some relationship between root/child module variable passing etc.?

Any help is appreciated! Thanks

Upvotes: 1

Views: 5174

Answers (1)

ha9u63a7
ha9u63a7

Reputation: 6824

I Think I know what I did wrong.

Terraform Modules - as per the documentation requires parents to pass on variables as part of invocation. For example:

module "foo" { source = "./modules/foo" var1 = value var2 = value

}

The above var1, var2 can come from either auto.tfvars file, environment variables (recommended) or even command line -var-file calls. In fact, this is what Terraform calls "Calling a Child Module" here

Once I did that, everything worked like a charm! I hope I did find the correct way of doing things.

Upvotes: 1

Related Questions