skip to Main Content

New to terraform, and have been building out the infrastructure recently.
I am trying to pull secrets from azure key vault and assign the keys to the variables.tf file depending on the environment(dev.tfvars, test.tfvars, etc). However when I execute the plan with the tfvar file as the parameter, I get an error with the following message:

Error: Variables not allowed

Here are the files and the relevant contents of it.

variables.tf:

variable "user_name" {
  type      = string
  sensitive = true
}

data.tf (referencing the azure key vault):

 data "azurerm_key_vault" "test" {
  name                = var.key_vault_name
  resource_group_name = var.resource_group
}

data "azurerm_key_vault_secret" "test" {
  name         = "my-key-vault-key-name"
  key_vault_id = data.azurerm_key_vault.test.id
}

test.tfvars:

user_name = "${data.azurerm_key_vault_secret.test.value}" # Where the error occurrs

Can anyone point out what I’m doing wrong here? And if so is there another way to achieve such a thing?

2

Answers


  1. You can’t create dynamic variables. All variables must have known values before execution of your code. The only thing you could do is to use local, instead of variabile:

    locals {
      user_name = data.azurerm_key_vault_secret.test.value
    }
    

    and then refer to it as local.user_name.

    Login or Signup to reply.
  2. In Terraform a variable can be used for user input only. You can not assign to them anything dynamically computed from your code. They are like read-only arguments, for more info see Input Variables from the doc.

    If you want to assign a value to something for later use, you must use locals. For example:

    locals {
      user_name = data.azurerm_key_vault_secret.test.value
    }
    

    Local values can be changed dynamically during execution. For more info, see Local Values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search