I am trying to assign an output variable from a module to a local variable so that I can conveniently use a local variable. Is there another way ?
variable "vpc_id" {
default = "${module.vpc.vpc_id}"
}
Error I am getting is :
Error: Unsupported argument
on main.tf line 22, in variable "subnetid_private":
22: default = "${module.vpc.subnet_private}"
Variables may not be used here..
I spent good amount of time to google this but could not see any example. Am I missing something here. This is a pretty standard convenience feature of any language.
you can replace with locals
https://www.terraform.io/docs/configuration/locals.html
locals {
vpc_id = module.vpc.vpc_id
}
and later reference it as local.vpc_id
I had the same thought when I first started using Terraform.
The problem is naming. A Terraform variable block is more like a final or constant constructor or method parameter in other languages.
From the Local Value documentation, it says this:
A local value assigns a name to an expression, allowing it to be used multiple times within a module without repeating it.
Comparing modules to functions in a traditional programming language: if input variables are analogous to function arguments and outputs values are analogous to function return values, then local values are comparable to a function's local temporary symbols.
When you write:
variable "vpc_id" {
}
Terraform says "ah, you'd like callers of this module to be able to hand a string in called vpc_id". Definitely not what you are looking for.
For the kind of case you have, a Local Value is what Terraform provides:
locals {
vpc_id = module.vpc.vpc_id
}
In terraform 0.12, you can use variables in variables like so:
variable "var1" {
type = string
default = "this is var 1"
}
variable "var2" {
type = string
default = "$${variable.var1}"
}
output of this is:
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.