skip to Main Content

In the belo code, I trying to fetch azure secret ( if exists) from keyvault and render it to generate template.

...
< Keyvault definition >

data "azurerm_key_vault_secret" "win_admin_pass" {
count = ${var.cnt} # either 0 and 1
name         = "vm-winpw"
key_vault_id = data.azurerm_key_vault.keyvault.id
}

data "template_files" "wininv"{
count = ${var.cnt} # either 0 and 1
template = file(ansible/inventory.tpl)
var = {
winpw = data.azurerm_key_vault.keyvault.id[count.index]
}
}

resource "local_file" "wininv" {
count = ${var.cnt} 
content = data.template_files.wininv[count.index]
filename = "ansible/inventory.cfg"

}

Here, I want fetch azure secret, if available on keyvault and generate template.

Without "count" code, its working well, but when secret is not available on azure that time getting error in Terraform. That stuff i have to control.

But with this code, getting below error:

Error: incorrect attributes value type
On test.tf in data template_files" "wininv":

66    var ={ 

inappropriate value for attribute string required vars: elements example : String required

Can you please suggest possible Syntex or any alternative solution for same.

Thanks

2

Answers


  1. template_file requires string only attributes. It should be:

    winpw = data.azurerm_key_vault.keyvault[count.index].id
    

    Also these days its recommended to use templatefile over template_file.

    Login or Signup to reply.
  2. Conditional Expressions may solve your problem.

    data "template_files" "wininv"{
      count = ${var.cnt} # either 0 and 1
      template = file(ansible/inventory.tpl)
      var = {
        winpw = ${var.cnt} == 0 ? "" : data.azurerm_key_vault.keyvault[count.index].id
      }
    }
    

    You need to use rendered attritube to get the rendered template. (doc)

    resource "local_file" "wininv" {
      count = ${var.cnt} 
      content = data.template_files.wininv[count.index].rendered  # NOTICE rendered
      filename = "ansible/inventory.cfg"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search