Get local variable in terraform console

Viewed 27016

Is there any way to get local variables within Terraform console?

> local.name
unknown values referenced, can't compute value

Seems like Terraform console allows only to check input variables and module output variables.

> var.in
2

> module.abc.out
3

Configuration file examples:

# main.tf

locals {
  name = 1
}

variable "in" {
  value = 2
}

module "abc" {
  source "path/to/module"
}

# path/to/module/main.tf

output "out" {
  value = 3
}
3 Answers

This should work in recent Terraform releases.

$ terraform version
Terraform v1.0.5

$ terraform console
> local.name
1
> var.in
2

The tested 'main.tf'

locals {
  name = 1
}

variable in {
  default = 2
}

There is no REPL on terraform console still as on today(December 2021)

But there is a strongly upvoted request for that, see here on github. If you feel appropriate, you may also go there and upvote.

For me I just wanted to get some items from a list.

For the first item, I could use the element function and do this.

element(["apple", "banana", "pine apple", "grape", "strawberry"], 0)

I get back "apple".

And if want the last item, I have to do the following, using length function

element(["apple", "banana", "pine apple", "grape", "strawberry"], 
length(["apple", "banana", "pine apple", "grape", "strawberry"])-1)

I get back "strawberry".

Since there is code repetition here, I was look for something like this, to define a variable and use it.

var fruits = ["apple", "banana", "pine apple", "grape", "strawberry"]
element(fruits, length(fruits)-1)

This is just not working.

So I ended up defining a variable in a file called main.tf as follows.

variable fruits {
  default = ["apple", "banana", "pine apple", "grape", "strawberry"]
}

Launched terraform console.

Now I can use it as follows.

element(var.fruits, length(var.fruits)-1)

Some of the relevant examples you may want to look at from my Repo

Related