Seun
Seun

Reputation: 83

In Terraform, can i have variables in Data Sources?

i will like to know if I can use variables while calling Data sources in terraform:

Instead of having:

data.terraform_remote_state.dev_vpc

I want to have a variable call dev like:

data.terraform_remote_state.${var.stage}_vpc

I tried to use the variable as it is above but got the error:

Error: Invalid attribute name

on locals.tf line 21, in locals:

21: for n in data.terraform_remote_state.${var.stage}_vpc :

An attribute name is required after a dot.

Any help will be appreciated.

Thanks in advance.

Upvotes: 3

Views: 5217

Answers (2)

Sallyerik
Sallyerik

Reputation: 519

You can do something like this:

locals {
    stage_map = {
        ¨variable1 name¨ = data.terraform_remote_state.variable1_value
        ¨variable2 name¨ = data.terraform_remote_state.variable2_value
    }
}

resource "xxxx" "this" {
    name = var.scp_name
    content = local.stage_map[var.stage]
}

Upvotes: 2

Dan Monego
Dan Monego

Reputation: 10087

You can't template an identifier like that, but there are a few other ways you could do it.

Use a variable in the remote state definition:

data "terraform_remote_state" "rs" {
  backend = "local"
  config = {
    path = local.remote_path
  }
}

This is a little simpler, and lets you template in your remote config using config files, locals, or variables as you want.

Define multiple remote states, and index:

locals {
  remote_paths = { dev = "./dev/terraform.tfstate", prod = "./prod/terraform.tfstate" }
}

data "terraform_remote_state" "rs" {
  for_each = local.remote_paths
  backend = "local"
  config = {
    path = each.value
  }
}

You can now reference dev and prod at data.terraform_remote_state.rs["dev"] or data.terraform_remote_state.rs["prod"]

Upvotes: 2

Related Questions