I've got a variable declared in my variables.tf
like this:
variable "MyAmi" {
type = map(string)
}
but when I do:
terraform plan -var 'MyAmi=xxxx'
I get:
Error: Variables not allowed
on <value for var.MyAmi> line 1:
(source code not available)
Variables may not be used here.
Minimal code example:
test.tf
provider "aws" {
}
# S3
module "my-s3" {
source = "terraform-aws-modules/s3-bucket/aws"
bucket = "${var.MyAmi}-bucket"
}
variables.tf
variable "MyAmi" {
type = map(string)
}
terraform plan -var 'MyAmi=test'
Error: Variables not allowed
on <value for var.MyAmi> line 1:
(source code not available)
Variables may not be used here.
Any suggestions?
I see two things that could be causing the error you are seeing. Link to terraform plan
documentation.
When running terraform plan
, it will automatically load any .tfvars
files in the current directory. If your .tfvars
file is in another directory you must provide it as a -var-file
parameter. You say in your question that your variables are in a file variables.tf
which means the terraform plan
command will not automatically load that file. FIX: rename variables.tf
to variables.tfvars
When using the -var
parameter, you should ensure that what you are passing into it will be properly interpreted by HCL. If the variable you are trying to pass in is a map, then it needs to be parse-able as a map.
Instead of terraform plan -var 'MyAmi=xxxx'
I would expect something more like terraform plan -var 'MyAmi={"us-east-1":"ami-123", "us-east-2":"ami-456"}'
.
See this documentation for more on declaring variables and specifically passing them in via the command line.