Trouble setting terraform variable from CLI

545 views Asked by At

My terraform project layout looks something like:

[project root dir]
main.tf
  - my_module [directory]:
      variables.tf
      my_instance.tf

In variables.tf I have something like this:

variable "foo-ami" {
  default = "ami-12345"
  description = "Super awesome AMI"
}

In my_instance.tf I reference it like so:

resource "aws_instance" "my_instance" {
  ami = "${var.foo-ami}"
  ...
}

If I want to override this variable from the command line, the docs here seem to suggest I should be able to run the following command from the top level (main.tf) location:

terraform plan -var 'foo-ami=ami-987654'

However, the variable switch doesn't seem to be getting picked up. The old value remains set. Further more if I remove the default setting I get an error from terraform saying it's not set, so clearly the -var switch isn't being picked up.

Thoughts?

TIA

1

There are 1 answers

0
minamijoyo On

The variables of root and my_module are different. If you want to pass a variable to my_module, you need to specify it.

In the main.tf, you should set the variable as follows:

variable "foo-ami" {}

module "my_module" {
  source = "./my_module"
  foo-ami = "${var.foo-ami}"
  ...
}

For details of the module feature refer to the following documents: https://www.terraform.io/docs/modules/usage.html