NickH
NickH

Reputation: 41

Terraform: Undefined remote state handling

I have a remote state attribute called subnets which is stored in: data.terraform_remote_state.alb.subnets

Depending on what I'm deploying, this attribute either exists or doesn't exist.

When I try to create an ECS cluster, it requires an input of the subnet groups in which I would like to either use:

data.terraform_remote_state.alb.subnets or var.vpc_subnets (the subnets of the VPC)

Unfortunately, because of the way the interpolation works, it needed to be hacked together:

"${split(",", length(var.vpc_subnets) == 0 ? join(",",data.terraform_remote_state.alb.subnets) : join(",",var.vpc_subnets))}"

(Refering to: https://github.com/hashicorp/terraform/issues/12453)

However, because Terraform does not seem to 'lazily' evaluate ternary operators, it throws me the following error even if var.vpc_subnets is NOT zero:

Resource 'data.terraform_remote_state.alb' does not have attribute 'subnets' for variable 'data.terraform_remote_state.alb.subnets'

How can I properly handle remote state resources that could be undefined?

EDIT: Typo: Subnet->Subnets

Upvotes: 2

Views: 1949

Answers (2)

NickH
NickH

Reputation: 41

Managed to figure it out. When using Terraform Remote State, you have the ability to set a default: https://www.terraform.io/docs/providers/terraform/d/remote_state.html

This works in my situation when my data "terraform_remote_state.alb.subnets does not return a value. I can preset the variable to be "" and use locals to do a check for this variable.

Upvotes: 2

BMW
BMW

Reputation: 45223

Will it be subnet or subnets?

Suppose you have below data source:

data "terraform_remote_state" "alb" {
  backend = "s3"
  config {
    name = "alb"
  }
}

You need check the remote state attribute have any outputs with name subnet or not. Or the key name is subnets, you need confirm by yourself.

Upvotes: 0

Related Questions