How to get a Terraform element's name (e.g. name of a local or a variable)?

Viewed 62

I have this Terraform code:

locals {
    environment_variables = {
        db_connection_string = ""
    }
}

And I am generating the following code (code's language irrelevant):

resource local_file configuration_strings {
    content = <<EOT

    public class Config {
        /* ... stuff ... */
        public string ConnectionString => configProvider["db_connection_string"];
        /* ... things
    }

EOT
}

Is there a way to let Terraform provide the name of the field ("db_connection_string"), rather than its value (""), in case e.g. I ever rename it and forget to update? for instance something like:

public string ConnectionString =>
    configProvider[get_name_of(local.environment_variables.db_connection_string)];

which should emit e.g.:

public string ConnectionString =>
    configProvider["db_connection_string")];

(again: emit configProvider["db_connection_string")], not configProvider["")])

1 Answers

You can use matchkeys to look up the key based on the value:

matchkeys(keys(local.environment_variables),values(local.environment_variables),[""])[0]
"db_connection_string"
Related