Kit Sunde
Kit Sunde

Reputation: 37065

Is it possible to alias variables with terraform?

To get the current AWS id I do:

data "aws_caller_identity" "current" { }

Which makes it available in data.aws_caller_identity.current.account_id. Is there some way to make it available as just account_id? I tried:

variable "account_id" {
  default = "${data.aws_caller_identity.current.account_id}"
}

but it says I can't do string interpolation in variables.

Upvotes: 3

Views: 3680

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56849

Since 0.10.3, you can use locals to get around the lack of variable interpolation.

This allows you to define a "friendly" name for all sorts of things that might require interpolation.

In your case you would simply use:

locals {
  account_id = "${data.aws_caller_identity.current.account_id}"
}

But you can combine any amount of interpolations and functions:

variable "foo" {}
variable "bar" {}

locals {
  account_id = "${data.aws_caller_identity.current.account_id}"
  foo_BAR    = "${var.foo}_${upper(var.bar)}"
}

Old answer

As Terraform points out in your error, you can't do variable interpolation directly although there are known hacky workarounds for when you need some form of variable interpolation.

Unfortunately all of these involve slightly convoluted uses of modules, templates or the null_resource or null_data_source which would then still leave you accessing the variable in an awkward way.

One option that might be more palatable for you is to wrap a bunch of data sources into a module like this:

data "aws_caller_identity" "current" {}
output "account_id" { value = "data.aws_caller_identity.current.account_id" }

data "aws_availability_zones" "zones" {}
output "zones" { value = "data.aws_availability_zones.zones.names }

And then access these like so:

module "data_sources" {
    source = "path/to/data-sources-module.tf"
}

...
    account_id = "${module.data_sources.account_id}"
...
    availability_zone = "${module.data_sources.zones[0]}"

But that doesn't really make these values as easily exposed as intermediate variables unfortunately.

Upvotes: 7

Related Questions