0

I have a map of values (populated from Consul), which I use to configure my resources, however if values for optional variables are missing, I would like Terraform to act as it the parameter was not provided. For example:

resource "aws_db_instance" "db" {
  engine = "${lookup(config_map, "db_engine", "postgres")}"
  port   = "${lookup(config_map, "db_port", "<pick default for the engine>")}"
}

If port is not given, Terraform picks a default value depending on the engine. Can I trigger this behavior explicitly?

1 Answer 1

1

The following should do what you expect (syntax is validated, however apply has not been tested : I'll update the answer if it works, or delete it otherwise).

First, you should have somewhere a mapping between engines and default ports (here, this is a variable, but it could be stored in Consul like your config_map) :

variable "default_ports_by_engine" {
  type = "map"

  # key = engine, value = port
  default = {
    "postgres" = "3333"
    "mysql"    = "3334"
    # other engines/ports...
  }
}

Then, you can use this variable in a nested lookup :

resource "aws_db_instance" "db" {
  engine = "${lookup(config_map, "db_engine", "postgres")}"
  port   = "${
    lookup(
      var.default_ports_by_engine,
      "${lookup(config_map, "db_engine", "postgres")}"
    )
  }"
}

Notice that not passing a third argument to lookup function will make Terraform fail if db_engine is not found in default_ports_by_engine.

Sign up to request clarification or add additional context in comments.

3 Comments

I suppose this will work, but I had hoped to reuse the logic performed by Terraform, rather than replicate it.
What do you mean by "replicate the logic"?
In this example, I need to check the default ports used by Terraform for all the engines I want to use and hard-code them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.