Tar
Tar

Reputation: 9015

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

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["🤫🤐")])

Upvotes: 1

Views: 318

Answers (1)

Paolo
Paolo

Reputation: 26074

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"

Upvotes: 1

Related Questions