Search code examples
variablesterraformdatasourcehashicorp-vault

using value of variable and string to fetch from terraform data source


I am trying to fetch some certficates from hashicorp vault using tf data source

This is how cert path looks like in vault

serverA:
  dev-cert: <base64 encoded cert>
  qa-cert: <base64 encoded cert>
  test-cert: <base64 encoded cert>

This cert is used in other resource block which works fine as shown below

resource <somegcpresource> <xyz>
{
   certificate = base64decode(data.vault_generic_secret.server_cryptoobjects.data["dev-cert"])
}
  1. Can I use a custom env variable to fetch value of certificate like;

    certificate = base64decode(data.vault_generic_secret.server_cryptoobjects.data["var.env-cert"])

  2. or a local var to reference the key name from vault datasource like;

    certificate = base64decode(data.vault_generic_secret.server_cryptoobjects.data[local.certname])


Solution

  • Yes, the data.vault_generic_secret.server_cryptoobjects.data is an object so you can access its values with their corresponding keys. If you declare a variable env-cert:

    variable "env-cert" {
      type    = string
      default = "dev-cert"
    }
    

    then you can use it as the key:

    certificate = base64decode(data.vault_generic_secret.server_cryptoobjects.data["var.env-cert"])
    

    Yes you can also use a local as the key:

    locals {
      certname = "dev-cert"
    }
    
    certificate = base64decode(data.vault_generic_secret.server_cryptoobjects.data[local.certname])
    

    I would also suggest looking at the Vault PKI secrets engine for your overall use case if you have not already, since this example in the question is using the KV2 secrets engine.