How can i replace the value of a variable dynamically in terraform based on a condition

Viewed 2570

i have two modules:

module "vpc" {
..
..
}

module "subnet" {
 vpc = "${module.vpc.id}"
}

And the appropriate variables and output file.

Based on a condition, i would like to change the value of vpc in module subnet dynamically. i.e value of vpc can be either "${module.vpc.id}" or "${var.vpcid}". When i do this, i can create a new vpc and subnet ,when the value of vpc is set to - "${module.vpc.id}" applying all the terrform modules, and also make use of an existing vpc when the value of vpc is "${var.vpcid}"( here terraform apply with not include the vpc module)

I've tried to use expressions, used a local block with a condition outside of these two modules, but it ends up creating a new vpc.

locals {
vpctake = "${var.vpcch ? element(module.vpc.id, 0) : var.vpcid}"
}

where vpcch can be either true or false and in the subnet module:

vpc = "${local.vpctake}"

Is there any way to implement this.

1 Answers

There are mistakes in your code:

  • vpcch should be vpcid
  • missing condition in your local block

Below is an example of how I would do it:

# vpcid with default value of empty string
variable "vpcid" {
  default = ""
}

# correctly defined local variable vpctake
locals {
  vpctake = "${var.vpcid == "" ? element(module.vpc.id, 0) : var.vpcid}"
}

module "subnet" {
 vpc = "${local.vpctake}"
}

With this, if vpcid is provided from command line:

terraform apply -var="vpcid=some-id"

local.vpctake will be some-id. Otherwise value from element(module.vpc.id, 0) will be used.

Related