How to fetch azure secret if exist in KV using terraform



  • I am using below terraform code for fetch azure secret and this is working fine when secret is exist in the azure KV.

    Getting error when secret is not available in KV.

    data "azurerm_key_vault_secret" "win_admin_pass" {
        name         = "${var.secret_name}"
        key_vault_id = "${data.azurerm_key_vault.keyvault.id}"
    }
    

    In my case, this secret may available or may not available.

    How can we ignore error for this particular task when secret not available, or how can we check if secret exist or not, based on this condition we can fetch and ignore set of code?



  • This looks like a case for a conditional resource.

    First, look up the secrets with a https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/data-sources/key_vault_secrets block:

    data "azurerm_key_vault_secrets" "example" {
      key_vault_id = data.azurerm_key_vault.keyvault.id
    }
    

    and then a condition on the lookup:

    data "azure_rm_key_vault_secret" "win_admin_pass" {
      count        = contains(data.azurerm_key_vault_secrets.win_admin_pass.names, var.secret_name) ? 1 : 0
      name         = var.secret_name
      key_vault_id = data.azurerm_key_vault.keyvault.id
    

    }

    If the secret doesn't exist, the data will look up zero resources.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2